miner.c 323 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2012-2013 Andrew Smith
  5. * Copyright 2010 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef HAVE_CURSES
  14. #ifdef USE_UNICODE
  15. #define PDC_WIDE
  16. #endif
  17. // Must be before stdbool, since pdcurses typedefs bool :/
  18. #include <curses.h>
  19. #endif
  20. #include <ctype.h>
  21. #include <float.h>
  22. #include <limits.h>
  23. #include <locale.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <stdbool.h>
  28. #include <stdint.h>
  29. #include <unistd.h>
  30. #include <sys/time.h>
  31. #include <time.h>
  32. #include <math.h>
  33. #include <stdarg.h>
  34. #include <assert.h>
  35. #include <signal.h>
  36. #include <wctype.h>
  37. #include <sys/stat.h>
  38. #include <sys/types.h>
  39. #include <dirent.h>
  40. #ifdef HAVE_PWD_H
  41. #include <pwd.h>
  42. #endif
  43. #ifndef WIN32
  44. #include <sys/resource.h>
  45. #include <sys/socket.h>
  46. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  47. #include <libudev.h>
  48. #include <sys/epoll.h>
  49. #define HAVE_BFG_HOTPLUG
  50. #endif
  51. #else
  52. #include <winsock2.h>
  53. #include <windows.h>
  54. #include <dbt.h>
  55. #define HAVE_BFG_HOTPLUG
  56. #endif
  57. #include <ccan/opt/opt.h>
  58. #include <jansson.h>
  59. #include <curl/curl.h>
  60. #include <libgen.h>
  61. #include <sha2.h>
  62. #include <utlist.h>
  63. #include <blkmaker.h>
  64. #include <blkmaker_jansson.h>
  65. #include <blktemplate.h>
  66. #include "compat.h"
  67. #include "deviceapi.h"
  68. #include "logging.h"
  69. #include "miner.h"
  70. #include "adl.h"
  71. #include "driver-cpu.h"
  72. #include "driver-opencl.h"
  73. #include "scrypt.h"
  74. #include "util.h"
  75. #ifdef USE_AVALON
  76. #include "driver-avalon.h"
  77. #endif
  78. #ifdef HAVE_BFG_LOWLEVEL
  79. #include "lowlevel.h"
  80. #endif
  81. #if defined(unix) || defined(__APPLE__)
  82. #include <errno.h>
  83. #include <fcntl.h>
  84. #include <sys/wait.h>
  85. #endif
  86. #ifdef USE_SCRYPT
  87. #include "scrypt.h"
  88. #endif
  89. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  90. # define USE_FPGA
  91. #endif
  92. enum bfg_quit_summary {
  93. BQS_DEFAULT,
  94. BQS_NONE,
  95. BQS_DEVS,
  96. BQS_PROCS,
  97. BQS_DETAILED,
  98. };
  99. struct strategies strategies[] = {
  100. { "Failover" },
  101. { "Round Robin" },
  102. { "Rotate" },
  103. { "Load Balance" },
  104. { "Balance" },
  105. };
  106. static char packagename[256];
  107. bool opt_protocol;
  108. bool opt_dev_protocol;
  109. static bool opt_benchmark;
  110. static bool want_longpoll = true;
  111. static bool want_gbt = true;
  112. static bool want_getwork = true;
  113. #if BLKMAKER_VERSION > 1
  114. static bool have_at_least_one_getcbaddr;
  115. static bytes_t opt_coinbase_script = BYTES_INIT;
  116. static uint32_t template_nonce;
  117. #endif
  118. #if BLKMAKER_VERSION > 0
  119. char *opt_coinbase_sig;
  120. #endif
  121. static enum bfg_quit_summary opt_quit_summary = BQS_DEFAULT;
  122. static bool include_serial_in_statline;
  123. char *request_target_str;
  124. float request_pdiff = 1.0;
  125. double request_bdiff;
  126. static bool want_stratum = true;
  127. bool have_longpoll;
  128. int opt_skip_checks;
  129. bool want_per_device_stats;
  130. bool use_syslog;
  131. bool opt_quiet_work_updates = true;
  132. bool opt_quiet;
  133. bool opt_realquiet;
  134. int loginput_size;
  135. bool opt_compact;
  136. bool opt_show_procs;
  137. const int opt_cutofftemp = 95;
  138. int opt_hysteresis = 3;
  139. static int opt_retries = -1;
  140. int opt_fail_pause = 5;
  141. int opt_log_interval = 20;
  142. int opt_queue = 1;
  143. int opt_scantime = 60;
  144. int opt_expiry = 120;
  145. int opt_expiry_lp = 3600;
  146. unsigned long long global_hashrate;
  147. static bool opt_unittest = false;
  148. unsigned long global_quota_gcd = 1;
  149. time_t last_getwork;
  150. #ifdef HAVE_OPENCL
  151. int opt_dynamic_interval = 7;
  152. int nDevs;
  153. int opt_g_threads = -1;
  154. #endif
  155. #ifdef USE_SCRYPT
  156. static char detect_algo = 1;
  157. bool opt_scrypt;
  158. #else
  159. static char detect_algo;
  160. #endif
  161. bool opt_restart = true;
  162. #ifdef USE_LIBMICROHTTPD
  163. #include "httpsrv.h"
  164. int httpsrv_port = -1;
  165. #endif
  166. #ifdef USE_LIBEVENT
  167. int stratumsrv_port = -1;
  168. #endif
  169. const
  170. int rescan_delay_ms = 1000;
  171. #ifdef HAVE_BFG_HOTPLUG
  172. bool opt_hotplug = 1;
  173. const
  174. int hotplug_delay_ms = 100;
  175. #else
  176. const bool opt_hotplug;
  177. #endif
  178. struct string_elist *scan_devices;
  179. static struct string_elist *opt_set_device_list;
  180. bool opt_force_dev_init;
  181. static struct string_elist *opt_devices_enabled_list;
  182. static bool opt_display_devs;
  183. int total_devices;
  184. struct cgpu_info **devices;
  185. int total_devices_new;
  186. struct cgpu_info **devices_new;
  187. bool have_opencl;
  188. int opt_n_threads = -1;
  189. int mining_threads;
  190. int num_processors;
  191. #ifdef HAVE_CURSES
  192. bool use_curses = true;
  193. #else
  194. bool use_curses;
  195. #endif
  196. #ifdef HAVE_LIBUSB
  197. bool have_libusb;
  198. #endif
  199. static bool opt_submit_stale = true;
  200. static float opt_shares;
  201. static int opt_submit_threads = 0x40;
  202. bool opt_fail_only;
  203. int opt_fail_switch_delay = 300;
  204. bool opt_autofan;
  205. bool opt_autoengine;
  206. bool opt_noadl;
  207. char *opt_api_allow = NULL;
  208. char *opt_api_groups;
  209. char *opt_api_description = PACKAGE_STRING;
  210. int opt_api_port = 4028;
  211. bool opt_api_listen;
  212. bool opt_api_mcast;
  213. char *opt_api_mcast_addr = API_MCAST_ADDR;
  214. char *opt_api_mcast_code = API_MCAST_CODE;
  215. char *opt_api_mcast_des = "";
  216. int opt_api_mcast_port = 4028;
  217. bool opt_api_network;
  218. bool opt_delaynet;
  219. bool opt_disable_pool;
  220. bool opt_disable_client_reconnect = false;
  221. static bool no_work;
  222. bool opt_worktime;
  223. bool opt_weighed_stats;
  224. char *opt_kernel_path;
  225. char *cgminer_path;
  226. #if defined(USE_BITFORCE)
  227. bool opt_bfl_noncerange;
  228. #endif
  229. #define QUIET (opt_quiet || opt_realquiet)
  230. struct thr_info *control_thr;
  231. struct thr_info **mining_thr;
  232. static int watchpool_thr_id;
  233. static int watchdog_thr_id;
  234. #ifdef HAVE_CURSES
  235. static int input_thr_id;
  236. #endif
  237. int gpur_thr_id;
  238. static int api_thr_id;
  239. static int total_control_threads;
  240. pthread_mutex_t hash_lock;
  241. static pthread_mutex_t *stgd_lock;
  242. pthread_mutex_t console_lock;
  243. cglock_t ch_lock;
  244. static pthread_rwlock_t blk_lock;
  245. static pthread_mutex_t sshare_lock;
  246. pthread_rwlock_t netacc_lock;
  247. pthread_rwlock_t mining_thr_lock;
  248. pthread_rwlock_t devices_lock;
  249. static pthread_mutex_t lp_lock;
  250. static pthread_cond_t lp_cond;
  251. pthread_cond_t gws_cond;
  252. bool shutting_down;
  253. double total_rolling;
  254. double total_mhashes_done;
  255. static struct timeval total_tv_start, total_tv_end;
  256. static struct timeval miner_started;
  257. cglock_t control_lock;
  258. pthread_mutex_t stats_lock;
  259. static pthread_mutex_t submitting_lock;
  260. static int total_submitting;
  261. static struct work *submit_waiting;
  262. notifier_t submit_waiting_notifier;
  263. int hw_errors;
  264. int total_accepted, total_rejected;
  265. int total_getworks, total_stale, total_discarded;
  266. uint64_t total_bytes_rcvd, total_bytes_sent;
  267. double total_diff1, total_bad_diff1;
  268. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  269. static int staged_rollable;
  270. unsigned int new_blocks;
  271. unsigned int found_blocks;
  272. unsigned int local_work;
  273. unsigned int total_go, total_ro;
  274. struct pool **pools;
  275. static struct pool *currentpool = NULL;
  276. int total_pools, enabled_pools;
  277. enum pool_strategy pool_strategy = POOL_FAILOVER;
  278. int opt_rotate_period;
  279. static int total_urls, total_users, total_passes;
  280. static
  281. #ifndef HAVE_CURSES
  282. const
  283. #endif
  284. bool curses_active;
  285. #ifdef HAVE_CURSES
  286. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  287. const
  288. #endif
  289. short default_bgcolor = COLOR_BLACK;
  290. static int attr_title = A_BOLD;
  291. #endif
  292. static
  293. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  294. bool use_unicode;
  295. static
  296. bool have_unicode_degrees;
  297. static
  298. wchar_t unicode_micro = 'u';
  299. #else
  300. const bool use_unicode;
  301. static
  302. const bool have_unicode_degrees;
  303. static
  304. const char unicode_micro = 'u';
  305. #endif
  306. #ifdef HAVE_CURSES
  307. #define U8_BAD_START "\xef\x80\x81"
  308. #define U8_BAD_END "\xef\x80\x80"
  309. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  310. bool selecting_device;
  311. unsigned selected_device;
  312. #endif
  313. static char current_block[40];
  314. /* Protected by ch_lock */
  315. static char *current_hash;
  316. static uint32_t current_block_id;
  317. char *current_fullhash;
  318. static char datestamp[40];
  319. static char blocktime[32];
  320. time_t block_time;
  321. static char best_share[ALLOC_H2B_SHORTV] = "0";
  322. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  323. static char block_diff[ALLOC_H2B_SHORTV];
  324. static char net_hashrate[ALLOC_H2B_SHORT];
  325. double best_diff = 0;
  326. static bool known_blkheight_current;
  327. static uint32_t known_blkheight;
  328. static uint32_t known_blkheight_blkid;
  329. static uint64_t block_subsidy;
  330. struct block {
  331. char hash[40];
  332. UT_hash_handle hh;
  333. int block_no;
  334. };
  335. static struct block *blocks = NULL;
  336. int swork_id;
  337. /* For creating a hash database of stratum shares submitted that have not had
  338. * a response yet */
  339. struct stratum_share {
  340. UT_hash_handle hh;
  341. bool block;
  342. struct work *work;
  343. int id;
  344. };
  345. static struct stratum_share *stratum_shares = NULL;
  346. char *opt_socks_proxy = NULL;
  347. static const char def_conf[] = "bfgminer.conf";
  348. static bool config_loaded;
  349. static int include_count;
  350. #define JSON_INCLUDE_CONF "include"
  351. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  352. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  353. #define JSON_MAX_DEPTH 10
  354. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  355. char *cmd_idle, *cmd_sick, *cmd_dead;
  356. #if defined(unix) || defined(__APPLE__)
  357. static char *opt_stderr_cmd = NULL;
  358. static int forkpid;
  359. #endif // defined(unix)
  360. #ifdef HAVE_CHROOT
  361. char *chroot_dir;
  362. #endif
  363. #ifdef HAVE_PWD_H
  364. char *opt_setuid;
  365. #endif
  366. struct sigaction termhandler, inthandler;
  367. struct thread_q *getq;
  368. static int total_work;
  369. static bool staged_full;
  370. struct work *staged_work = NULL;
  371. struct schedtime {
  372. bool enable;
  373. struct tm tm;
  374. };
  375. struct schedtime schedstart;
  376. struct schedtime schedstop;
  377. bool sched_paused;
  378. static bool time_before(struct tm *tm1, struct tm *tm2)
  379. {
  380. if (tm1->tm_hour < tm2->tm_hour)
  381. return true;
  382. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  383. return true;
  384. return false;
  385. }
  386. static bool should_run(void)
  387. {
  388. struct tm tm;
  389. time_t tt;
  390. bool within_range;
  391. if (!schedstart.enable && !schedstop.enable)
  392. return true;
  393. tt = time(NULL);
  394. localtime_r(&tt, &tm);
  395. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  396. if (time_before(&schedstop.tm, &schedstart.tm))
  397. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  398. else
  399. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  400. if (within_range && !schedstop.enable)
  401. /* This is a once off event with no stop time set */
  402. schedstart.enable = false;
  403. return within_range;
  404. }
  405. void get_datestamp(char *f, size_t fsiz, time_t tt)
  406. {
  407. struct tm _tm;
  408. struct tm *tm = &_tm;
  409. if (tt == INVALID_TIMESTAMP)
  410. tt = time(NULL);
  411. localtime_r(&tt, tm);
  412. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  413. tm->tm_year + 1900,
  414. tm->tm_mon + 1,
  415. tm->tm_mday,
  416. tm->tm_hour,
  417. tm->tm_min,
  418. tm->tm_sec);
  419. }
  420. static
  421. void get_timestamp(char *f, size_t fsiz, time_t tt)
  422. {
  423. struct tm _tm;
  424. struct tm *tm = &_tm;
  425. localtime_r(&tt, tm);
  426. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  427. tm->tm_hour,
  428. tm->tm_min,
  429. tm->tm_sec);
  430. }
  431. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  432. static char exit_buf[512];
  433. static void applog_and_exit(const char *fmt, ...)
  434. {
  435. va_list ap;
  436. va_start(ap, fmt);
  437. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  438. va_end(ap);
  439. _applog(LOG_ERR, exit_buf);
  440. exit(1);
  441. }
  442. char *devpath_to_devid(const char *devpath)
  443. {
  444. #ifndef WIN32
  445. struct stat my_stat;
  446. if (stat(devpath, &my_stat))
  447. return NULL;
  448. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  449. memcpy(devs, "dev_t:", 6);
  450. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  451. #else
  452. if (!strncmp(devpath, "\\\\.\\", 4))
  453. devpath += 4;
  454. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  455. return NULL;
  456. devpath += 3;
  457. char *p;
  458. strtol(devpath, &p, 10);
  459. if (p[0])
  460. return NULL;
  461. const int sz = (p - devpath);
  462. char *devs = malloc(4 + sz + 1);
  463. sprintf(devs, "com:%s", devpath);
  464. #endif
  465. return devs;
  466. }
  467. static
  468. bool devpaths_match(const char * const ap, const char * const bp)
  469. {
  470. char * const a = devpath_to_devid(ap);
  471. if (!a)
  472. return false;
  473. char * const b = devpath_to_devid(bp);
  474. bool rv = false;
  475. if (b)
  476. {
  477. rv = !strcmp(a, b);
  478. free(b);
  479. }
  480. free(a);
  481. return rv;
  482. }
  483. static
  484. int proc_letter_to_number(const char *s, const char ** const rem)
  485. {
  486. int n = 0, c;
  487. for ( ; s[0]; ++s)
  488. {
  489. if (unlikely(n > INT_MAX / 26))
  490. break;
  491. c = tolower(s[0]) - 'a';
  492. if (unlikely(c < 0 || c > 25))
  493. break;
  494. if (unlikely(INT_MAX - c < n))
  495. break;
  496. n = (n * 26) + c;
  497. }
  498. *rem = s;
  499. return n;
  500. }
  501. static
  502. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  503. {
  504. // all - matches anything
  505. // d0 - matches all processors of device 0
  506. // d0-3 - matches all processors of device 0, 1, 2, or 3
  507. // d0a - matches first processor of device 0
  508. // 0 - matches processor 0
  509. // 0-4 - matches processors 0, 1, 2, 3, or 4
  510. // ___ - matches all processors on all devices using driver/name ___
  511. // ___0 - matches all processors of 0th device using driver/name ___
  512. // ___0a - matches first processor of 0th device using driver/name ___
  513. // @* - matches device with serial or path *
  514. // @*@a - matches first processor of device with serial or path *
  515. // ___@* - matches device with serial or path * using driver/name ___
  516. if (!strcasecmp(pattern, "all"))
  517. return true;
  518. const struct device_drv * const drv = cgpu->drv;
  519. const char *p = pattern, *p2;
  520. size_t L;
  521. int n, i, c = -1;
  522. int n2;
  523. int proc_first = -1, proc_last = -1;
  524. struct cgpu_info *device;
  525. if (!(strncasecmp(drv->dname, p, (L = strlen(drv->dname)))
  526. && strncasecmp(drv-> name, p, (L = strlen(drv-> name)))))
  527. // dname or name
  528. p = &pattern[L];
  529. else
  530. if (p[0] == 'd' && (isdigit(p[1]) || p[1] == '-'))
  531. // d#
  532. ++p;
  533. else
  534. if (isdigit(p[0]) || p[0] == '@' || p[0] == '-')
  535. // # or @
  536. {}
  537. else
  538. return false;
  539. L = p - pattern;
  540. while (isspace(p[0]))
  541. ++p;
  542. if (p[0] == '@')
  543. {
  544. // Serial/path
  545. const char * const ser = &p[1];
  546. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  547. {}
  548. p2 = (p[0] == '@') ? &p[1] : p;
  549. const size_t serlen = (p - ser);
  550. p = "";
  551. n = n2 = 0;
  552. const char * const devpath = cgpu->device_path ?: "";
  553. const char * const devser = cgpu->dev_serial ?: "";
  554. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  555. {} // Match
  556. else
  557. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  558. {} // Match
  559. else
  560. {
  561. char devpath2[serlen + 1];
  562. memcpy(devpath2, ser, serlen);
  563. devpath2[serlen] = '\0';
  564. if (!devpaths_match(devpath, ser))
  565. return false;
  566. }
  567. }
  568. else
  569. {
  570. if (isdigit(p[0]))
  571. n = strtol(p, (void*)&p2, 0);
  572. else
  573. {
  574. n = 0;
  575. p2 = p;
  576. }
  577. if (p2[0] == '-')
  578. {
  579. ++p2;
  580. if (p2[0] && isdigit(p2[0]))
  581. n2 = strtol(p2, (void*)&p2, 0);
  582. else
  583. n2 = INT_MAX;
  584. }
  585. else
  586. n2 = n;
  587. if (p == pattern)
  588. {
  589. if (!p[0])
  590. return true;
  591. if (p2 && p2[0])
  592. goto invsyntax;
  593. for (i = n; i <= n2; ++i)
  594. {
  595. if (i >= total_devices)
  596. break;
  597. if (cgpu == devices[i])
  598. return true;
  599. }
  600. return false;
  601. }
  602. }
  603. if (p2[0])
  604. {
  605. proc_first = proc_letter_to_number(&p2[0], &p2);
  606. if (p2[0] == '-')
  607. {
  608. ++p2;
  609. if (p2[0])
  610. proc_last = proc_letter_to_number(p2, &p2);
  611. else
  612. proc_last = INT_MAX;
  613. }
  614. else
  615. proc_last = proc_first;
  616. if (p2[0])
  617. goto invsyntax;
  618. }
  619. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  620. {
  621. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  622. (!L) ||
  623. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  624. {} // Matched name or dname
  625. else
  626. return false;
  627. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  628. return false;
  629. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  630. return false;
  631. return true;
  632. }
  633. // d#
  634. c = -1;
  635. for (i = 0; ; ++i)
  636. {
  637. if (i == total_devices)
  638. return false;
  639. if (devices[i]->device != devices[i])
  640. continue;
  641. ++c;
  642. if (c < n)
  643. continue;
  644. if (c > n2)
  645. break;
  646. for (device = devices[i]; device; device = device->next_proc)
  647. {
  648. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  649. continue;
  650. if (device == cgpu)
  651. return true;
  652. }
  653. }
  654. return false;
  655. invsyntax:
  656. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  657. return false;
  658. }
  659. #define TEST_CGPU_MATCH(pattern) \
  660. if (!cgpu_match(pattern, &cgpu)) \
  661. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  662. // END TEST_CGPU_MATCH
  663. #define TEST_CGPU_NOMATCH(pattern) \
  664. if (cgpu_match(pattern, &cgpu)) \
  665. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  666. // END TEST_CGPU_MATCH
  667. static __maybe_unused
  668. void test_cgpu_match()
  669. {
  670. struct device_drv drv = {
  671. .dname = "test",
  672. .name = "TST",
  673. };
  674. struct cgpu_info cgpu = {
  675. .drv = &drv,
  676. .device = &cgpu,
  677. .device_id = 1,
  678. .proc_id = 1,
  679. .proc_repr = "TST 1b",
  680. }, cgpu0a = {
  681. .drv = &drv,
  682. .device = &cgpu0a,
  683. .device_id = 0,
  684. .proc_id = 0,
  685. .proc_repr = "TST 0a",
  686. }, cgpu1a = {
  687. .drv = &drv,
  688. .device = &cgpu0a,
  689. .device_id = 1,
  690. .proc_id = 0,
  691. .proc_repr = "TST 1a",
  692. };
  693. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  694. devices = devices_list;
  695. total_devices = 3;
  696. TEST_CGPU_MATCH("all")
  697. TEST_CGPU_MATCH("d1")
  698. TEST_CGPU_NOMATCH("d2")
  699. TEST_CGPU_MATCH("d0-5")
  700. TEST_CGPU_NOMATCH("d0-0")
  701. TEST_CGPU_NOMATCH("d2-5")
  702. TEST_CGPU_MATCH("d-1")
  703. TEST_CGPU_MATCH("d1-")
  704. TEST_CGPU_NOMATCH("d-0")
  705. TEST_CGPU_NOMATCH("d2-")
  706. TEST_CGPU_MATCH("2")
  707. TEST_CGPU_NOMATCH("3")
  708. TEST_CGPU_MATCH("1-2")
  709. TEST_CGPU_MATCH("2-3")
  710. TEST_CGPU_NOMATCH("1-1")
  711. TEST_CGPU_NOMATCH("3-4")
  712. TEST_CGPU_MATCH("TST")
  713. TEST_CGPU_MATCH("test")
  714. TEST_CGPU_MATCH("tst")
  715. TEST_CGPU_MATCH("TEST")
  716. TEST_CGPU_NOMATCH("TSF")
  717. TEST_CGPU_NOMATCH("TS")
  718. TEST_CGPU_NOMATCH("TSTF")
  719. TEST_CGPU_MATCH("TST1")
  720. TEST_CGPU_MATCH("test1")
  721. TEST_CGPU_MATCH("TST0-1")
  722. TEST_CGPU_MATCH("TST 1")
  723. TEST_CGPU_MATCH("TST 1-2")
  724. TEST_CGPU_MATCH("TEST 1-2")
  725. TEST_CGPU_NOMATCH("TST2")
  726. TEST_CGPU_NOMATCH("TST2-3")
  727. TEST_CGPU_NOMATCH("TST0-0")
  728. TEST_CGPU_MATCH("TST1b")
  729. TEST_CGPU_MATCH("tst1b")
  730. TEST_CGPU_NOMATCH("TST1c")
  731. TEST_CGPU_NOMATCH("TST1bb")
  732. TEST_CGPU_MATCH("TST0-1b")
  733. TEST_CGPU_NOMATCH("TST0-1c")
  734. TEST_CGPU_MATCH("TST1a-d")
  735. TEST_CGPU_NOMATCH("TST1a-a")
  736. TEST_CGPU_NOMATCH("TST1-a")
  737. TEST_CGPU_NOMATCH("TST1c-z")
  738. TEST_CGPU_NOMATCH("TST1c-")
  739. TEST_CGPU_MATCH("@")
  740. TEST_CGPU_NOMATCH("@abc")
  741. TEST_CGPU_MATCH("@@b")
  742. TEST_CGPU_NOMATCH("@@c")
  743. TEST_CGPU_MATCH("TST@")
  744. TEST_CGPU_NOMATCH("TST@abc")
  745. TEST_CGPU_MATCH("TST@@b")
  746. TEST_CGPU_NOMATCH("TST@@c")
  747. TEST_CGPU_MATCH("TST@@b-f")
  748. TEST_CGPU_NOMATCH("TST@@c-f")
  749. TEST_CGPU_NOMATCH("TST@@-a")
  750. cgpu.device_path = "/dev/test";
  751. cgpu.dev_serial = "testy";
  752. TEST_CGPU_MATCH("TST@/dev/test")
  753. TEST_CGPU_MATCH("TST@testy")
  754. TEST_CGPU_NOMATCH("TST@")
  755. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  756. TEST_CGPU_NOMATCH("TST@testy3@b")
  757. TEST_CGPU_MATCH("TST@/dev/test@b")
  758. TEST_CGPU_MATCH("TST@testy@b")
  759. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  760. TEST_CGPU_NOMATCH("TST@testy@c")
  761. cgpu.device_path = "usb:000:999";
  762. TEST_CGPU_MATCH("TST@usb:000:999")
  763. drv.dname = "test7";
  764. TEST_CGPU_MATCH("test7")
  765. TEST_CGPU_MATCH("TEST7")
  766. TEST_CGPU_NOMATCH("test&")
  767. TEST_CGPU_MATCH("test7 1-2")
  768. TEST_CGPU_MATCH("test7@testy@b")
  769. }
  770. static
  771. int cgpu_search(const char * const pattern, const int first)
  772. {
  773. int i;
  774. struct cgpu_info *cgpu;
  775. #define CHECK_CGPU_SEARCH do{ \
  776. cgpu = get_devices(i); \
  777. if (cgpu_match(pattern, cgpu)) \
  778. return i; \
  779. }while(0)
  780. for (i = first; i < total_devices; ++i)
  781. CHECK_CGPU_SEARCH;
  782. for (i = 0; i < first; ++i)
  783. CHECK_CGPU_SEARCH;
  784. #undef CHECK_CGPU_SEARCH
  785. return -1;
  786. }
  787. static pthread_mutex_t sharelog_lock;
  788. static FILE *sharelog_file = NULL;
  789. struct thr_info *get_thread(int thr_id)
  790. {
  791. struct thr_info *thr;
  792. rd_lock(&mining_thr_lock);
  793. thr = mining_thr[thr_id];
  794. rd_unlock(&mining_thr_lock);
  795. return thr;
  796. }
  797. static struct cgpu_info *get_thr_cgpu(int thr_id)
  798. {
  799. struct thr_info *thr = get_thread(thr_id);
  800. return thr->cgpu;
  801. }
  802. struct cgpu_info *get_devices(int id)
  803. {
  804. struct cgpu_info *cgpu;
  805. rd_lock(&devices_lock);
  806. cgpu = devices[id];
  807. rd_unlock(&devices_lock);
  808. return cgpu;
  809. }
  810. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  811. static FILE *noncelog_file = NULL;
  812. static
  813. void noncelog(const struct work * const work)
  814. {
  815. const int thr_id = work->thr_id;
  816. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  817. char buf[0x200], hash[65], data[161], midstate[65];
  818. int rv;
  819. size_t ret;
  820. bin2hex(hash, work->hash, 32);
  821. bin2hex(data, work->data, 80);
  822. bin2hex(midstate, work->midstate, 32);
  823. // timestamp,proc,hash,data,midstate
  824. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  825. (unsigned long)time(NULL), proc->proc_repr_ns,
  826. hash, data, midstate);
  827. if (unlikely(rv < 1))
  828. {
  829. applog(LOG_ERR, "noncelog printf error");
  830. return;
  831. }
  832. mutex_lock(&noncelog_lock);
  833. ret = fwrite(buf, rv, 1, noncelog_file);
  834. fflush(noncelog_file);
  835. mutex_unlock(&noncelog_lock);
  836. if (ret != 1)
  837. applog(LOG_ERR, "noncelog fwrite error");
  838. }
  839. static void sharelog(const char*disposition, const struct work*work)
  840. {
  841. char target[(sizeof(work->target) * 2) + 1];
  842. char hash[(sizeof(work->hash) * 2) + 1];
  843. char data[(sizeof(work->data) * 2) + 1];
  844. struct cgpu_info *cgpu;
  845. unsigned long int t;
  846. struct pool *pool;
  847. int thr_id, rv;
  848. char s[1024];
  849. size_t ret;
  850. if (!sharelog_file)
  851. return;
  852. thr_id = work->thr_id;
  853. cgpu = get_thr_cgpu(thr_id);
  854. pool = work->pool;
  855. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  856. bin2hex(target, work->target, sizeof(work->target));
  857. bin2hex(hash, work->hash, sizeof(work->hash));
  858. bin2hex(data, work->data, sizeof(work->data));
  859. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  860. 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);
  861. if (rv >= (int)(sizeof(s)))
  862. s[sizeof(s) - 1] = '\0';
  863. else if (rv < 0) {
  864. applog(LOG_ERR, "sharelog printf error");
  865. return;
  866. }
  867. mutex_lock(&sharelog_lock);
  868. ret = fwrite(s, rv, 1, sharelog_file);
  869. fflush(sharelog_file);
  870. mutex_unlock(&sharelog_lock);
  871. if (ret != 1)
  872. applog(LOG_ERR, "sharelog fwrite error");
  873. }
  874. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  875. /* Adjust all the pools' quota to the greatest common denominator after a pool
  876. * has been added or the quotas changed. */
  877. void adjust_quota_gcd(void)
  878. {
  879. unsigned long gcd, lowest_quota = ~0UL, quota;
  880. struct pool *pool;
  881. int i;
  882. for (i = 0; i < total_pools; i++) {
  883. pool = pools[i];
  884. quota = pool->quota;
  885. if (!quota)
  886. continue;
  887. if (quota < lowest_quota)
  888. lowest_quota = quota;
  889. }
  890. if (likely(lowest_quota < ~0UL)) {
  891. gcd = lowest_quota;
  892. for (i = 0; i < total_pools; i++) {
  893. pool = pools[i];
  894. quota = pool->quota;
  895. if (!quota)
  896. continue;
  897. while (quota % gcd)
  898. gcd--;
  899. }
  900. } else
  901. gcd = 1;
  902. for (i = 0; i < total_pools; i++) {
  903. pool = pools[i];
  904. pool->quota_used *= global_quota_gcd;
  905. pool->quota_used /= gcd;
  906. pool->quota_gcd = pool->quota / gcd;
  907. }
  908. global_quota_gcd = gcd;
  909. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  910. }
  911. static void enable_pool(struct pool *);
  912. /* Return value is ignored if not called from add_pool_details */
  913. struct pool *add_pool(void)
  914. {
  915. struct pool *pool;
  916. pool = calloc(sizeof(struct pool), 1);
  917. if (!pool)
  918. quit(1, "Failed to malloc pool in add_pool");
  919. pool->pool_no = pool->prio = total_pools;
  920. mutex_init(&pool->last_work_lock);
  921. mutex_init(&pool->pool_lock);
  922. mutex_init(&pool->pool_test_lock);
  923. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  924. quit(1, "Failed to pthread_cond_init in add_pool");
  925. cglock_init(&pool->data_lock);
  926. mutex_init(&pool->stratum_lock);
  927. timer_unset(&pool->swork.tv_transparency);
  928. pool->swork.pool = pool;
  929. pool->idle = true;
  930. /* Make sure the pool doesn't think we've been idle since time 0 */
  931. pool->tv_idle.tv_sec = ~0UL;
  932. cgtime(&pool->cgminer_stats.start_tv);
  933. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  934. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  935. pool->rpc_proxy = NULL;
  936. pool->quota = 1;
  937. pool->sock = INVSOCK;
  938. pool->lp_socket = CURL_SOCKET_BAD;
  939. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  940. pools[total_pools++] = pool;
  941. if (opt_benchmark)
  942. {
  943. // Immediately remove it
  944. remove_pool(pool);
  945. return pool;
  946. }
  947. adjust_quota_gcd();
  948. enable_pool(pool);
  949. return pool;
  950. }
  951. static
  952. void pool_set_uri(struct pool * const pool, char * const uri)
  953. {
  954. pool->rpc_url = uri;
  955. if (uri_get_param_bool(uri, "getcbaddr", false))
  956. have_at_least_one_getcbaddr = true;
  957. }
  958. /* Pool variant of test and set */
  959. static bool pool_tset(struct pool *pool, bool *var)
  960. {
  961. bool ret;
  962. mutex_lock(&pool->pool_lock);
  963. ret = *var;
  964. *var = true;
  965. mutex_unlock(&pool->pool_lock);
  966. return ret;
  967. }
  968. bool pool_tclear(struct pool *pool, bool *var)
  969. {
  970. bool ret;
  971. mutex_lock(&pool->pool_lock);
  972. ret = *var;
  973. *var = false;
  974. mutex_unlock(&pool->pool_lock);
  975. return ret;
  976. }
  977. struct pool *current_pool(void)
  978. {
  979. struct pool *pool;
  980. cg_rlock(&control_lock);
  981. pool = currentpool;
  982. cg_runlock(&control_lock);
  983. return pool;
  984. }
  985. // Copied from ccan/opt/helpers.c
  986. static char *arg_bad(const char *fmt, const char *arg)
  987. {
  988. char *str = malloc(strlen(fmt) + strlen(arg));
  989. sprintf(str, fmt, arg);
  990. return str;
  991. }
  992. static
  993. char *opt_set_floatval(const char *arg, float *f)
  994. {
  995. char *endp;
  996. errno = 0;
  997. *f = strtof(arg, &endp);
  998. if (*endp || !arg[0])
  999. return arg_bad("'%s' is not a number", arg);
  1000. if (errno)
  1001. return arg_bad("'%s' is out of range", arg);
  1002. return NULL;
  1003. }
  1004. static
  1005. void opt_show_floatval(char buf[OPT_SHOW_LEN], const float *f)
  1006. {
  1007. snprintf(buf, OPT_SHOW_LEN, "%.1f", *f);
  1008. }
  1009. static
  1010. char *set_bool_ignore_arg(const char * const arg, bool * const b)
  1011. {
  1012. return opt_set_bool(b);
  1013. }
  1014. char *set_int_range(const char *arg, int *i, int min, int max)
  1015. {
  1016. char *err = opt_set_intval(arg, i);
  1017. if (err)
  1018. return err;
  1019. if (*i < min || *i > max)
  1020. return "Value out of range";
  1021. return NULL;
  1022. }
  1023. static char *set_int_0_to_9999(const char *arg, int *i)
  1024. {
  1025. return set_int_range(arg, i, 0, 9999);
  1026. }
  1027. static char *set_int_1_to_65535(const char *arg, int *i)
  1028. {
  1029. return set_int_range(arg, i, 1, 65535);
  1030. }
  1031. static char *set_int_0_to_10(const char *arg, int *i)
  1032. {
  1033. return set_int_range(arg, i, 0, 10);
  1034. }
  1035. static char *set_int_1_to_10(const char *arg, int *i)
  1036. {
  1037. return set_int_range(arg, i, 1, 10);
  1038. }
  1039. char *set_strdup(const char *arg, char **p)
  1040. {
  1041. *p = strdup((char *)arg);
  1042. return NULL;
  1043. }
  1044. #if BLKMAKER_VERSION > 1
  1045. static
  1046. char *set_b58addr(const char * const arg, bytes_t * const b)
  1047. {
  1048. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  1049. if (!scriptsz)
  1050. return "Invalid address";
  1051. char *script = malloc(scriptsz);
  1052. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  1053. free(script);
  1054. return "Failed to convert address to script";
  1055. }
  1056. bytes_assimilate_raw(b, script, scriptsz, scriptsz);
  1057. return NULL;
  1058. }
  1059. #endif
  1060. static
  1061. char *set_quit_summary(const char * const arg)
  1062. {
  1063. if (!(strcasecmp(arg, "none") && strcasecmp(arg, "no")))
  1064. opt_quit_summary = BQS_NONE;
  1065. else
  1066. if (!(strcasecmp(arg, "devs") && strcasecmp(arg, "devices")))
  1067. opt_quit_summary = BQS_DEVS;
  1068. else
  1069. if (!(strcasecmp(arg, "procs") && strcasecmp(arg, "processors") && strcasecmp(arg, "chips") && strcasecmp(arg, "cores")))
  1070. opt_quit_summary = BQS_PROCS;
  1071. else
  1072. if (!(strcasecmp(arg, "detailed") && strcasecmp(arg, "detail") && strcasecmp(arg, "all")))
  1073. opt_quit_summary = BQS_DETAILED;
  1074. else
  1075. return "Quit summary must be one of none/devs/procs/detailed";
  1076. return NULL;
  1077. }
  1078. static void pdiff_target_leadzero(void *, double);
  1079. char *set_request_diff(const char *arg, float *p)
  1080. {
  1081. unsigned char target[32];
  1082. char *e = opt_set_floatval(arg, p);
  1083. if (e)
  1084. return e;
  1085. request_bdiff = (double)*p * 0.9999847412109375;
  1086. pdiff_target_leadzero(target, *p);
  1087. request_target_str = malloc(65);
  1088. bin2hex(request_target_str, target, 32);
  1089. return NULL;
  1090. }
  1091. #ifdef NEED_BFG_LOWL_VCOM
  1092. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  1093. #ifdef WIN32
  1094. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  1095. {
  1096. char dev[PATH_MAX];
  1097. char *devp = dev;
  1098. size_t bufLen = 0x100;
  1099. tryagain: ;
  1100. char buf[bufLen];
  1101. if (!QueryDosDevice(NULL, buf, bufLen)) {
  1102. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  1103. bufLen *= 2;
  1104. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  1105. goto tryagain;
  1106. }
  1107. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  1108. }
  1109. size_t tLen;
  1110. memcpy(devp, "\\\\.\\", 4);
  1111. devp = &devp[4];
  1112. for (char *t = buf; *t; t += tLen) {
  1113. tLen = strlen(t) + 1;
  1114. if (strncmp("COM", t, 3))
  1115. continue;
  1116. memcpy(devp, t, tLen);
  1117. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1118. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1119. }
  1120. }
  1121. #else
  1122. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1123. {
  1124. char dev[PATH_MAX];
  1125. char *devp = dev;
  1126. DIR *D;
  1127. struct dirent *de;
  1128. const char devdir[] = "/dev";
  1129. const size_t devdirlen = sizeof(devdir) - 1;
  1130. char *devpath = devp;
  1131. char *devfile = devpath + devdirlen + 1;
  1132. D = opendir(devdir);
  1133. if (!D)
  1134. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1135. memcpy(devpath, devdir, devdirlen);
  1136. devpath[devdirlen] = '/';
  1137. while ( (de = readdir(D)) ) {
  1138. if (!strncmp(de->d_name, "cu.", 3)
  1139. //don't probe Bluetooth devices - causes bus errors and segfaults
  1140. && strncmp(de->d_name, "cu.Bluetooth", 12))
  1141. goto trydev;
  1142. if (strncmp(de->d_name, "tty", 3))
  1143. continue;
  1144. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1145. continue;
  1146. trydev:
  1147. strcpy(devfile, de->d_name);
  1148. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1149. }
  1150. closedir(D);
  1151. }
  1152. #endif
  1153. #endif
  1154. static char *add_serial(const char *arg)
  1155. {
  1156. string_elist_add(arg, &scan_devices);
  1157. return NULL;
  1158. }
  1159. static
  1160. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1161. {
  1162. string_elist_add(arg, elist);
  1163. return NULL;
  1164. }
  1165. bool get_intrange(const char *arg, int *val1, int *val2)
  1166. {
  1167. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1168. char *p, *p2;
  1169. *val1 = strtol(arg, &p, 0);
  1170. if (arg == p)
  1171. // Zero-length ending number, invalid
  1172. return false;
  1173. while (true)
  1174. {
  1175. if (!p[0])
  1176. {
  1177. *val2 = *val1;
  1178. return true;
  1179. }
  1180. if (p[0] == '-')
  1181. break;
  1182. if (!isspace(p[0]))
  1183. // Garbage, invalid
  1184. return false;
  1185. ++p;
  1186. }
  1187. p2 = &p[1];
  1188. *val2 = strtol(p2, &p, 0);
  1189. if (p2 == p)
  1190. // Zero-length ending number, invalid
  1191. return false;
  1192. while (true)
  1193. {
  1194. if (!p[0])
  1195. return true;
  1196. if (!isspace(p[0]))
  1197. // Garbage, invalid
  1198. return false;
  1199. ++p;
  1200. }
  1201. }
  1202. static
  1203. void _test_intrange(const char *s, const int v[2])
  1204. {
  1205. int a[2];
  1206. if (!get_intrange(s, &a[0], &a[1]))
  1207. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1208. for (int i = 0; i < 2; ++i)
  1209. if (unlikely(a[i] != v[i]))
  1210. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1211. }
  1212. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1213. static
  1214. void _test_intrange_fail(const char *s)
  1215. {
  1216. int a[2];
  1217. if (get_intrange(s, &a[0], &a[1]))
  1218. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1219. }
  1220. static
  1221. void test_intrange()
  1222. {
  1223. _test_intrange("-1--2", -1, -2);
  1224. _test_intrange("-1-2", -1, 2);
  1225. _test_intrange("1--2", 1, -2);
  1226. _test_intrange("1-2", 1, 2);
  1227. _test_intrange("111-222", 111, 222);
  1228. _test_intrange(" 11 - 22 ", 11, 22);
  1229. _test_intrange("+11-+22", 11, 22);
  1230. _test_intrange("-1", -1, -1);
  1231. _test_intrange_fail("all");
  1232. _test_intrange_fail("1-");
  1233. _test_intrange_fail("");
  1234. _test_intrange_fail("1-54x");
  1235. }
  1236. static char *set_devices(char *arg)
  1237. {
  1238. if (*arg) {
  1239. if (*arg == '?') {
  1240. opt_display_devs = true;
  1241. return NULL;
  1242. }
  1243. } else
  1244. return "Invalid device parameters";
  1245. string_elist_add(arg, &opt_devices_enabled_list);
  1246. return NULL;
  1247. }
  1248. static char *set_balance(enum pool_strategy *strategy)
  1249. {
  1250. *strategy = POOL_BALANCE;
  1251. return NULL;
  1252. }
  1253. static char *set_loadbalance(enum pool_strategy *strategy)
  1254. {
  1255. *strategy = POOL_LOADBALANCE;
  1256. return NULL;
  1257. }
  1258. static char *set_rotate(const char *arg, int *i)
  1259. {
  1260. pool_strategy = POOL_ROTATE;
  1261. return set_int_range(arg, i, 0, 9999);
  1262. }
  1263. static char *set_rr(enum pool_strategy *strategy)
  1264. {
  1265. *strategy = POOL_ROUNDROBIN;
  1266. return NULL;
  1267. }
  1268. /* Detect that url is for a stratum protocol either via the presence of
  1269. * stratum+tcp or by detecting a stratum server response */
  1270. bool detect_stratum(struct pool *pool, char *url)
  1271. {
  1272. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1273. return false;
  1274. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1275. pool_set_uri(pool, strdup(url));
  1276. pool->has_stratum = true;
  1277. pool->stratum_url = pool->sockaddr_url;
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. static struct pool *add_url(void)
  1283. {
  1284. total_urls++;
  1285. if (total_urls > total_pools)
  1286. add_pool();
  1287. return pools[total_urls - 1];
  1288. }
  1289. static void setup_url(struct pool *pool, char *arg)
  1290. {
  1291. if (detect_stratum(pool, arg))
  1292. return;
  1293. opt_set_charp(arg, &pool->rpc_url);
  1294. if (strncmp(arg, "http://", 7) &&
  1295. strncmp(arg, "https://", 8)) {
  1296. const size_t L = strlen(arg);
  1297. char *httpinput;
  1298. httpinput = malloc(8 + L);
  1299. if (!httpinput)
  1300. quit(1, "Failed to malloc httpinput");
  1301. sprintf(httpinput, "http://%s", arg);
  1302. pool_set_uri(pool, httpinput);
  1303. }
  1304. }
  1305. static char *set_url(char *arg)
  1306. {
  1307. struct pool *pool = add_url();
  1308. setup_url(pool, arg);
  1309. return NULL;
  1310. }
  1311. static char *set_quota(char *arg)
  1312. {
  1313. char *semicolon = strchr(arg, ';'), *url;
  1314. int len, qlen, quota;
  1315. struct pool *pool;
  1316. if (!semicolon)
  1317. return "No semicolon separated quota;URL pair found";
  1318. len = strlen(arg);
  1319. *semicolon = '\0';
  1320. qlen = strlen(arg);
  1321. if (!qlen)
  1322. return "No parameter for quota found";
  1323. len -= qlen + 1;
  1324. if (len < 1)
  1325. return "No parameter for URL found";
  1326. quota = atoi(arg);
  1327. if (quota < 0)
  1328. return "Invalid negative parameter for quota set";
  1329. url = arg + qlen + 1;
  1330. pool = add_url();
  1331. setup_url(pool, url);
  1332. pool->quota = quota;
  1333. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1334. adjust_quota_gcd();
  1335. return NULL;
  1336. }
  1337. static char *set_user(const char *arg)
  1338. {
  1339. struct pool *pool;
  1340. total_users++;
  1341. if (total_users > total_pools)
  1342. add_pool();
  1343. pool = pools[total_users - 1];
  1344. opt_set_charp(arg, &pool->rpc_user);
  1345. return NULL;
  1346. }
  1347. static char *set_pass(const char *arg)
  1348. {
  1349. struct pool *pool;
  1350. total_passes++;
  1351. if (total_passes > total_pools)
  1352. add_pool();
  1353. pool = pools[total_passes - 1];
  1354. opt_set_charp(arg, &pool->rpc_pass);
  1355. return NULL;
  1356. }
  1357. static char *set_userpass(const char *arg)
  1358. {
  1359. struct pool *pool;
  1360. char *updup;
  1361. if (total_users != total_passes)
  1362. return "User + pass options must be balanced before userpass";
  1363. ++total_users;
  1364. ++total_passes;
  1365. if (total_users > total_pools)
  1366. add_pool();
  1367. pool = pools[total_users - 1];
  1368. updup = strdup(arg);
  1369. opt_set_charp(arg, &pool->rpc_userpass);
  1370. pool->rpc_user = updup;
  1371. pool->rpc_pass = strchr(updup, ':');
  1372. if (pool->rpc_pass)
  1373. pool->rpc_pass++[0] = '\0';
  1374. else
  1375. pool->rpc_pass = &updup[strlen(updup)];
  1376. return NULL;
  1377. }
  1378. static char *set_pool_priority(const char *arg)
  1379. {
  1380. struct pool *pool;
  1381. if (!total_pools)
  1382. return "Usage of --pool-priority before pools are defined does not make sense";
  1383. pool = pools[total_pools - 1];
  1384. opt_set_intval(arg, &pool->prio);
  1385. return NULL;
  1386. }
  1387. static char *set_pool_proxy(const char *arg)
  1388. {
  1389. struct pool *pool;
  1390. if (!total_pools)
  1391. return "Usage of --pool-proxy before pools are defined does not make sense";
  1392. if (!our_curl_supports_proxy_uris())
  1393. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1394. pool = pools[total_pools - 1];
  1395. opt_set_charp(arg, &pool->rpc_proxy);
  1396. return NULL;
  1397. }
  1398. static char *set_pool_force_rollntime(const char *arg)
  1399. {
  1400. struct pool *pool;
  1401. if (!total_pools)
  1402. return "Usage of --force-rollntime before pools are defined does not make sense";
  1403. pool = pools[total_pools - 1];
  1404. opt_set_intval(arg, &pool->force_rollntime);
  1405. return NULL;
  1406. }
  1407. static char *enable_debug(bool *flag)
  1408. {
  1409. *flag = true;
  1410. opt_debug_console = true;
  1411. /* Turn on verbose output, too. */
  1412. opt_log_output = true;
  1413. return NULL;
  1414. }
  1415. static char *set_schedtime(const char *arg, struct schedtime *st)
  1416. {
  1417. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1418. {
  1419. if (strcasecmp(arg, "now"))
  1420. return "Invalid time set, should be HH:MM";
  1421. } else
  1422. schedstop.tm.tm_sec = 0;
  1423. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1424. return "Invalid time set.";
  1425. st->enable = true;
  1426. return NULL;
  1427. }
  1428. static
  1429. char *set_log_file(char *arg)
  1430. {
  1431. char *r = "";
  1432. long int i = strtol(arg, &r, 10);
  1433. int fd, stderr_fd = fileno(stderr);
  1434. if ((!*r) && i >= 0 && i <= INT_MAX)
  1435. fd = i;
  1436. else
  1437. if (!strcmp(arg, "-"))
  1438. {
  1439. fd = fileno(stdout);
  1440. if (unlikely(fd == -1))
  1441. return "Standard output missing for log-file";
  1442. }
  1443. else
  1444. {
  1445. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1446. if (unlikely(fd == -1))
  1447. return "Failed to open log-file";
  1448. }
  1449. close(stderr_fd);
  1450. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1451. return "Failed to dup2 for log-file";
  1452. close(fd);
  1453. return NULL;
  1454. }
  1455. static
  1456. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1457. {
  1458. char *r = "";
  1459. long int i = strtol(arg, &r, 10);
  1460. static char *err = NULL;
  1461. const size_t errbufsz = 0x100;
  1462. free(err);
  1463. err = NULL;
  1464. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1465. *F = fdopen((int)i, mode);
  1466. if (!*F)
  1467. {
  1468. err = malloc(errbufsz);
  1469. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1470. (int)i, purpose);
  1471. return err;
  1472. }
  1473. } else if (!strcmp(arg, "-")) {
  1474. *F = (mode[0] == 'a') ? stdout : stdin;
  1475. if (!*F)
  1476. {
  1477. err = malloc(errbufsz);
  1478. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1479. (mode[0] == 'a') ? "out" : "in", purpose);
  1480. return err;
  1481. }
  1482. } else {
  1483. *F = fopen(arg, mode);
  1484. if (!*F)
  1485. {
  1486. err = malloc(errbufsz);
  1487. snprintf(err, errbufsz, "Failed to open %s for %s",
  1488. arg, purpose);
  1489. return err;
  1490. }
  1491. }
  1492. return NULL;
  1493. }
  1494. static char *set_noncelog(char *arg)
  1495. {
  1496. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1497. }
  1498. static char *set_sharelog(char *arg)
  1499. {
  1500. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1501. }
  1502. static
  1503. void _add_set_device_option(const char * const func, const char * const buf)
  1504. {
  1505. applog(LOG_DEBUG, "%s: Using --set-device %s", func, buf);
  1506. string_elist_add(buf, &opt_set_device_list);
  1507. }
  1508. #define add_set_device_option(...) do{ \
  1509. char _tmp1718[0x100]; \
  1510. snprintf(_tmp1718, sizeof(_tmp1718), __VA_ARGS__); \
  1511. _add_set_device_option(__func__, _tmp1718); \
  1512. }while(0)
  1513. char *set_temp_cutoff(char *arg)
  1514. {
  1515. if (strchr(arg, ','))
  1516. return "temp-cutoff no longer supports comma-delimited syntax, use --set-device for better control";
  1517. applog(LOG_WARNING, "temp-cutoff is deprecated! Use --set-device for better control");
  1518. add_set_device_option("all:temp-cutoff=%s", arg);
  1519. return NULL;
  1520. }
  1521. char *set_temp_target(char *arg)
  1522. {
  1523. if (strchr(arg, ','))
  1524. return "temp-target no longer supports comma-delimited syntax, use --set-device for better control";
  1525. applog(LOG_WARNING, "temp-target is deprecated! Use --set-device for better control");
  1526. add_set_device_option("all:temp-target=%s", arg);
  1527. return NULL;
  1528. }
  1529. #ifdef HAVE_OPENCL
  1530. static
  1531. char *set_no_opencl_binaries(__maybe_unused void * const dummy)
  1532. {
  1533. applog(LOG_WARNING, "The --no-opencl-binaries option is deprecated! Use --set-device OCL:binary=no");
  1534. add_set_device_option("OCL:binary=no");
  1535. return NULL;
  1536. }
  1537. #endif
  1538. static
  1539. char *disable_pool_redirect(__maybe_unused void * const dummy)
  1540. {
  1541. opt_disable_client_reconnect = true;
  1542. want_stratum = false;
  1543. return NULL;
  1544. }
  1545. static char *set_api_allow(const char *arg)
  1546. {
  1547. opt_set_charp(arg, &opt_api_allow);
  1548. return NULL;
  1549. }
  1550. static char *set_api_groups(const char *arg)
  1551. {
  1552. opt_set_charp(arg, &opt_api_groups);
  1553. return NULL;
  1554. }
  1555. static char *set_api_description(const char *arg)
  1556. {
  1557. opt_set_charp(arg, &opt_api_description);
  1558. return NULL;
  1559. }
  1560. static char *set_api_mcast_des(const char *arg)
  1561. {
  1562. opt_set_charp(arg, &opt_api_mcast_des);
  1563. return NULL;
  1564. }
  1565. #ifdef USE_ICARUS
  1566. extern const struct bfg_set_device_definition icarus_set_device_funcs[];
  1567. static char *set_icarus_options(const char *arg)
  1568. {
  1569. if (strchr(arg, ','))
  1570. return "icarus-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1571. applog(LOG_WARNING, "icarus-options is deprecated! See README.FPGA for better control");
  1572. char *opts = strdup(arg), *argdup;
  1573. argdup = opts;
  1574. const struct bfg_set_device_definition *sdf = icarus_set_device_funcs;
  1575. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1576. char *saveptr, *opt;
  1577. for (int i = 0; i < 4; ++i, ++sdf)
  1578. {
  1579. opt = strtok_r(opts, ":", &saveptr);
  1580. opts = NULL;
  1581. if (!opt)
  1582. break;
  1583. if (!opt[0])
  1584. continue;
  1585. for (int j = 0; j < 4; ++j)
  1586. add_set_device_option("%s:%s=%s", drivers[j], sdf->optname, opt);
  1587. }
  1588. free(argdup);
  1589. return NULL;
  1590. }
  1591. static char *set_icarus_timing(const char *arg)
  1592. {
  1593. if (strchr(arg, ','))
  1594. return "icarus-timing no longer supports comma-delimited syntax, see README.FPGA for better control";
  1595. applog(LOG_WARNING, "icarus-timing is deprecated! See README.FPGA for better control");
  1596. const char *drivers[] = {"antminer", "cairnsmore", "erupter", "icarus"};
  1597. for (int j = 0; j < 4; ++j)
  1598. add_set_device_option("%s:timing=%s", drivers[j], arg);
  1599. return NULL;
  1600. }
  1601. #endif
  1602. #ifdef USE_AVALON
  1603. extern const struct bfg_set_device_definition avalon_set_device_funcs[];
  1604. static char *set_avalon_options(const char *arg)
  1605. {
  1606. if (strchr(arg, ','))
  1607. return "avalon-options no longer supports comma-delimited syntax, see README.FPGA for better control";
  1608. applog(LOG_WARNING, "avalon-options is deprecated! See README.FPGA for better control");
  1609. char *opts = strdup(arg), *argdup;
  1610. argdup = opts;
  1611. const struct bfg_set_device_definition *sdf = avalon_set_device_funcs;
  1612. char *saveptr, *opt;
  1613. for (int i = 0; i < 5; ++i, ++sdf)
  1614. {
  1615. opt = strtok_r(opts, ":", &saveptr);
  1616. opts = NULL;
  1617. if (!opt)
  1618. break;
  1619. if (!opt[0])
  1620. continue;
  1621. add_set_device_option("avalon:%s=%s", sdf->optname, opt);
  1622. }
  1623. free(argdup);
  1624. return NULL;
  1625. }
  1626. #endif
  1627. #ifdef USE_KLONDIKE
  1628. static char *set_klondike_options(const char *arg)
  1629. {
  1630. int hashclock;
  1631. double temptarget;
  1632. switch (sscanf(arg, "%d:%lf", &hashclock, &temptarget))
  1633. {
  1634. default:
  1635. return "Unrecognised --klondike-options";
  1636. case 2:
  1637. add_set_device_option("klondike:temp-target=%lf", temptarget);
  1638. // fallthru
  1639. case 1:
  1640. add_set_device_option("klondike:clock=%d", hashclock);
  1641. }
  1642. applog(LOG_WARNING, "klondike-options is deprecated! Use --set-device for better control");
  1643. return NULL;
  1644. }
  1645. #endif
  1646. __maybe_unused
  1647. static char *set_null(const char __maybe_unused *arg)
  1648. {
  1649. return NULL;
  1650. }
  1651. /* These options are available from config file or commandline */
  1652. static struct opt_table opt_config_table[] = {
  1653. #ifdef WANT_CPUMINE
  1654. OPT_WITH_ARG("--algo",
  1655. set_algo, show_algo, &opt_algo,
  1656. "Specify sha256 implementation for CPU mining:\n"
  1657. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1658. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1659. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1660. #ifdef WANT_SSE2_4WAY
  1661. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1662. #endif
  1663. #ifdef WANT_VIA_PADLOCK
  1664. "\n\tvia\t\tVIA padlock implementation"
  1665. #endif
  1666. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1667. #ifdef WANT_CRYPTOPP_ASM32
  1668. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1669. #endif
  1670. #ifdef WANT_X8632_SSE2
  1671. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1672. #endif
  1673. #ifdef WANT_X8664_SSE2
  1674. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1675. #endif
  1676. #ifdef WANT_X8664_SSE4
  1677. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1678. #endif
  1679. #ifdef WANT_ALTIVEC_4WAY
  1680. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1681. #endif
  1682. ),
  1683. OPT_WITH_ARG("-a",
  1684. set_algo, show_algo, &opt_algo,
  1685. opt_hidden),
  1686. #endif
  1687. OPT_WITH_ARG("--api-allow",
  1688. set_api_allow, NULL, NULL,
  1689. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1690. OPT_WITH_ARG("--api-description",
  1691. set_api_description, NULL, NULL,
  1692. "Description placed in the API status header, default: BFGMiner version"),
  1693. OPT_WITH_ARG("--api-groups",
  1694. set_api_groups, NULL, NULL,
  1695. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1696. OPT_WITHOUT_ARG("--api-listen",
  1697. opt_set_bool, &opt_api_listen,
  1698. "Enable API, default: disabled"),
  1699. OPT_WITHOUT_ARG("--api-mcast",
  1700. opt_set_bool, &opt_api_mcast,
  1701. "Enable API Multicast listener, default: disabled"),
  1702. OPT_WITH_ARG("--api-mcast-addr",
  1703. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1704. "API Multicast listen address"),
  1705. OPT_WITH_ARG("--api-mcast-code",
  1706. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1707. "Code expected in the API Multicast message, don't use '-'"),
  1708. OPT_WITH_ARG("--api-mcast-des",
  1709. set_api_mcast_des, NULL, NULL,
  1710. "Description appended to the API Multicast reply, default: ''"),
  1711. OPT_WITH_ARG("--api-mcast-port",
  1712. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1713. "API Multicast listen port"),
  1714. OPT_WITHOUT_ARG("--api-network",
  1715. opt_set_bool, &opt_api_network,
  1716. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1717. OPT_WITH_ARG("--api-port",
  1718. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1719. "Port number of miner API"),
  1720. #ifdef HAVE_ADL
  1721. OPT_WITHOUT_ARG("--auto-fan",
  1722. opt_set_bool, &opt_autofan,
  1723. opt_hidden),
  1724. OPT_WITHOUT_ARG("--auto-gpu",
  1725. opt_set_bool, &opt_autoengine,
  1726. opt_hidden),
  1727. #endif
  1728. OPT_WITHOUT_ARG("--balance",
  1729. set_balance, &pool_strategy,
  1730. "Change multipool strategy from failover to even share balance"),
  1731. OPT_WITHOUT_ARG("--benchmark",
  1732. opt_set_bool, &opt_benchmark,
  1733. "Run BFGMiner in benchmark mode - produces no shares"),
  1734. #if defined(USE_BITFORCE)
  1735. OPT_WITHOUT_ARG("--bfl-range",
  1736. opt_set_bool, &opt_bfl_noncerange,
  1737. "Use nonce range on bitforce devices if supported"),
  1738. #endif
  1739. #ifdef HAVE_CHROOT
  1740. OPT_WITH_ARG("--chroot-dir",
  1741. opt_set_charp, NULL, &chroot_dir,
  1742. "Chroot to a directory right after startup"),
  1743. #endif
  1744. OPT_WITH_ARG("--cmd-idle",
  1745. opt_set_charp, NULL, &cmd_idle,
  1746. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1747. OPT_WITH_ARG("--cmd-sick",
  1748. opt_set_charp, NULL, &cmd_sick,
  1749. "Execute a command when a device is declared sick"),
  1750. OPT_WITH_ARG("--cmd-dead",
  1751. opt_set_charp, NULL, &cmd_dead,
  1752. "Execute a command when a device is declared dead"),
  1753. #if BLKMAKER_VERSION > 1
  1754. OPT_WITH_ARG("--coinbase-addr",
  1755. set_b58addr, NULL, &opt_coinbase_script,
  1756. "Set coinbase payout address for solo mining"),
  1757. OPT_WITH_ARG("--coinbase-address|--coinbase-payout|--cbaddress|--cbaddr|--cb-address|--cb-addr|--payout",
  1758. set_b58addr, NULL, &opt_coinbase_script,
  1759. opt_hidden),
  1760. #endif
  1761. #if BLKMAKER_VERSION > 0
  1762. OPT_WITH_ARG("--coinbase-sig",
  1763. set_strdup, NULL, &opt_coinbase_sig,
  1764. "Set coinbase signature when possible"),
  1765. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1766. set_strdup, NULL, &opt_coinbase_sig,
  1767. opt_hidden),
  1768. #endif
  1769. #ifdef HAVE_CURSES
  1770. OPT_WITHOUT_ARG("--compact",
  1771. opt_set_bool, &opt_compact,
  1772. "Use compact display without per device statistics"),
  1773. #endif
  1774. #ifdef WANT_CPUMINE
  1775. OPT_WITH_ARG("--cpu-threads",
  1776. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1777. "Number of miner CPU threads"),
  1778. OPT_WITH_ARG("-t",
  1779. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1780. opt_hidden),
  1781. #endif
  1782. OPT_WITHOUT_ARG("--debug|-D",
  1783. enable_debug, &opt_debug,
  1784. "Enable debug output"),
  1785. OPT_WITHOUT_ARG("--debuglog",
  1786. opt_set_bool, &opt_debug,
  1787. "Enable debug logging"),
  1788. OPT_WITHOUT_ARG("--device-protocol-dump",
  1789. opt_set_bool, &opt_dev_protocol,
  1790. "Verbose dump of device protocol-level activities"),
  1791. OPT_WITH_ARG("--device|-d",
  1792. set_devices, NULL, NULL,
  1793. "Enable only devices matching pattern (default: all)"),
  1794. OPT_WITHOUT_ARG("--disable-rejecting",
  1795. opt_set_bool, &opt_disable_pool,
  1796. "Automatically disable pools that continually reject shares"),
  1797. #ifdef USE_LIBMICROHTTPD
  1798. OPT_WITH_ARG("--http-port",
  1799. opt_set_intval, opt_show_intval, &httpsrv_port,
  1800. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1801. #endif
  1802. OPT_WITH_ARG("--expiry",
  1803. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1804. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1805. OPT_WITH_ARG("-E",
  1806. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1807. opt_hidden),
  1808. OPT_WITH_ARG("--expiry-lp",
  1809. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1810. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1811. OPT_WITHOUT_ARG("--failover-only",
  1812. opt_set_bool, &opt_fail_only,
  1813. "Don't leak work to backup pools when primary pool is lagging"),
  1814. OPT_WITH_ARG("--failover-switch-delay",
  1815. set_int_1_to_65535, opt_show_intval, &opt_fail_switch_delay,
  1816. "Delay in seconds before switching back to a failed pool"),
  1817. #ifdef USE_FPGA
  1818. OPT_WITHOUT_ARG("--force-dev-init",
  1819. opt_set_bool, &opt_force_dev_init,
  1820. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1821. #endif
  1822. #ifdef HAVE_OPENCL
  1823. OPT_WITH_ARG("--gpu-dyninterval",
  1824. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1825. opt_hidden),
  1826. OPT_WITH_ARG("--gpu-platform",
  1827. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1828. "Select OpenCL platform ID to use for GPU mining"),
  1829. OPT_WITH_ARG("--gpu-threads|-g",
  1830. set_gpu_threads, opt_show_intval, &opt_g_threads,
  1831. opt_hidden),
  1832. #ifdef HAVE_ADL
  1833. OPT_WITH_ARG("--gpu-engine",
  1834. set_gpu_engine, NULL, NULL,
  1835. opt_hidden),
  1836. OPT_WITH_ARG("--gpu-fan",
  1837. set_gpu_fan, NULL, NULL,
  1838. opt_hidden),
  1839. OPT_WITH_ARG("--gpu-map",
  1840. set_gpu_map, NULL, NULL,
  1841. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1842. OPT_WITH_ARG("--gpu-memclock",
  1843. set_gpu_memclock, NULL, NULL,
  1844. opt_hidden),
  1845. OPT_WITH_ARG("--gpu-memdiff",
  1846. set_gpu_memdiff, NULL, NULL,
  1847. opt_hidden),
  1848. OPT_WITH_ARG("--gpu-powertune",
  1849. set_gpu_powertune, NULL, NULL,
  1850. opt_hidden),
  1851. OPT_WITHOUT_ARG("--gpu-reorder",
  1852. opt_set_bool, &opt_reorder,
  1853. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1854. OPT_WITH_ARG("--gpu-vddc",
  1855. set_gpu_vddc, NULL, NULL,
  1856. opt_hidden),
  1857. #endif
  1858. #ifdef USE_SCRYPT
  1859. OPT_WITH_ARG("--lookup-gap",
  1860. set_lookup_gap, NULL, NULL,
  1861. opt_hidden),
  1862. #endif
  1863. OPT_WITH_ARG("--intensity|-I",
  1864. set_intensity, NULL, NULL,
  1865. opt_hidden),
  1866. #endif
  1867. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1868. OPT_WITH_ARG("--kernel-path",
  1869. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1870. "Specify a path to where bitstream and kernel files are"),
  1871. OPT_WITH_ARG("-K",
  1872. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1873. opt_hidden),
  1874. #endif
  1875. #ifdef HAVE_OPENCL
  1876. OPT_WITH_ARG("--kernel|-k",
  1877. set_kernel, NULL, NULL,
  1878. opt_hidden),
  1879. #endif
  1880. #ifdef USE_ICARUS
  1881. OPT_WITH_ARG("--icarus-options",
  1882. set_icarus_options, NULL, NULL,
  1883. opt_hidden),
  1884. OPT_WITH_ARG("--icarus-timing",
  1885. set_icarus_timing, NULL, NULL,
  1886. opt_hidden),
  1887. #endif
  1888. #ifdef USE_AVALON
  1889. OPT_WITH_ARG("--avalon-options",
  1890. set_avalon_options, NULL, NULL,
  1891. opt_hidden),
  1892. #endif
  1893. #ifdef USE_KLONDIKE
  1894. OPT_WITH_ARG("--klondike-options",
  1895. set_klondike_options, NULL, NULL,
  1896. "Set klondike options clock:temptarget"),
  1897. #endif
  1898. OPT_WITHOUT_ARG("--load-balance",
  1899. set_loadbalance, &pool_strategy,
  1900. "Change multipool strategy from failover to quota based balance"),
  1901. OPT_WITH_ARG("--log|-l",
  1902. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1903. "Interval in seconds between log output"),
  1904. OPT_WITH_ARG("--log-file|-L",
  1905. set_log_file, NULL, NULL,
  1906. "Append log file for output messages"),
  1907. OPT_WITH_ARG("--logfile",
  1908. set_log_file, NULL, NULL,
  1909. opt_hidden),
  1910. OPT_WITHOUT_ARG("--log-microseconds",
  1911. opt_set_bool, &opt_log_microseconds,
  1912. "Include microseconds in log output"),
  1913. #if defined(unix) || defined(__APPLE__)
  1914. OPT_WITH_ARG("--monitor|-m",
  1915. opt_set_charp, NULL, &opt_stderr_cmd,
  1916. "Use custom pipe cmd for output messages"),
  1917. #endif // defined(unix)
  1918. OPT_WITHOUT_ARG("--net-delay",
  1919. opt_set_bool, &opt_delaynet,
  1920. "Impose small delays in networking to avoid overloading slow routers"),
  1921. OPT_WITHOUT_ARG("--no-adl",
  1922. opt_set_bool, &opt_noadl,
  1923. #ifdef HAVE_ADL
  1924. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1925. #else
  1926. opt_hidden
  1927. #endif
  1928. ),
  1929. OPT_WITHOUT_ARG("--no-gbt",
  1930. opt_set_invbool, &want_gbt,
  1931. "Disable getblocktemplate support"),
  1932. OPT_WITHOUT_ARG("--no-getwork",
  1933. opt_set_invbool, &want_getwork,
  1934. "Disable getwork support"),
  1935. OPT_WITHOUT_ARG("--no-hotplug",
  1936. #ifdef HAVE_BFG_HOTPLUG
  1937. opt_set_invbool, &opt_hotplug,
  1938. "Disable hotplug detection"
  1939. #else
  1940. set_null, &opt_hotplug,
  1941. opt_hidden
  1942. #endif
  1943. ),
  1944. OPT_WITHOUT_ARG("--no-longpoll",
  1945. opt_set_invbool, &want_longpoll,
  1946. "Disable X-Long-Polling support"),
  1947. OPT_WITHOUT_ARG("--no-pool-disable",
  1948. opt_set_invbool, &opt_disable_pool,
  1949. opt_hidden),
  1950. OPT_WITHOUT_ARG("--no-client-reconnect",
  1951. opt_set_invbool, &opt_disable_client_reconnect,
  1952. opt_hidden),
  1953. OPT_WITHOUT_ARG("--no-pool-redirect",
  1954. disable_pool_redirect, NULL,
  1955. "Ignore pool requests to redirect to another server"),
  1956. OPT_WITHOUT_ARG("--no-restart",
  1957. opt_set_invbool, &opt_restart,
  1958. "Do not attempt to restart devices that hang"
  1959. ),
  1960. OPT_WITHOUT_ARG("--no-show-processors",
  1961. opt_set_invbool, &opt_show_procs,
  1962. opt_hidden),
  1963. OPT_WITHOUT_ARG("--no-show-procs",
  1964. opt_set_invbool, &opt_show_procs,
  1965. opt_hidden),
  1966. OPT_WITHOUT_ARG("--no-stratum",
  1967. opt_set_invbool, &want_stratum,
  1968. "Disable Stratum detection"),
  1969. OPT_WITHOUT_ARG("--no-submit-stale",
  1970. opt_set_invbool, &opt_submit_stale,
  1971. "Don't submit shares if they are detected as stale"),
  1972. #ifdef HAVE_OPENCL
  1973. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1974. set_no_opencl_binaries, NULL,
  1975. opt_hidden),
  1976. #endif
  1977. OPT_WITHOUT_ARG("--no-unicode",
  1978. #ifdef USE_UNICODE
  1979. opt_set_invbool, &use_unicode,
  1980. "Don't use Unicode characters in TUI"
  1981. #else
  1982. set_null, &use_unicode,
  1983. opt_hidden
  1984. #endif
  1985. ),
  1986. OPT_WITH_ARG("--noncelog",
  1987. set_noncelog, NULL, NULL,
  1988. "Create log of all nonces found"),
  1989. OPT_WITH_ARG("--pass|-p",
  1990. set_pass, NULL, NULL,
  1991. "Password for bitcoin JSON-RPC server"),
  1992. OPT_WITHOUT_ARG("--per-device-stats",
  1993. opt_set_bool, &want_per_device_stats,
  1994. "Force verbose mode and output per-device statistics"),
  1995. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1996. set_userpass, NULL, NULL,
  1997. opt_hidden),
  1998. OPT_WITH_ARG("--pool-priority",
  1999. set_pool_priority, NULL, NULL,
  2000. "Priority for just the previous-defined pool"),
  2001. OPT_WITH_ARG("--pool-proxy|-x",
  2002. set_pool_proxy, NULL, NULL,
  2003. "Proxy URI to use for connecting to just the previous-defined pool"),
  2004. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  2005. set_pool_force_rollntime, NULL, NULL,
  2006. opt_hidden),
  2007. OPT_WITHOUT_ARG("--protocol-dump|-P",
  2008. opt_set_bool, &opt_protocol,
  2009. "Verbose dump of protocol-level activities"),
  2010. OPT_WITH_ARG("--queue|-Q",
  2011. set_int_0_to_9999, opt_show_intval, &opt_queue,
  2012. "Minimum number of work items to have queued (0+)"),
  2013. OPT_WITHOUT_ARG("--quiet|-q",
  2014. opt_set_bool, &opt_quiet,
  2015. "Disable logging output, display status and errors"),
  2016. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  2017. opt_set_bool, &opt_quiet_work_updates,
  2018. opt_hidden),
  2019. OPT_WITH_ARG("--quit-summary",
  2020. set_quit_summary, NULL, NULL,
  2021. "Summary printed when you quit: none/devs/procs/detailed"),
  2022. OPT_WITH_ARG("--quota|-U",
  2023. set_quota, NULL, NULL,
  2024. "quota;URL combination for server with load-balance strategy quotas"),
  2025. OPT_WITHOUT_ARG("--real-quiet",
  2026. opt_set_bool, &opt_realquiet,
  2027. "Disable all output"),
  2028. OPT_WITH_ARG("--request-diff",
  2029. set_request_diff, opt_show_floatval, &request_pdiff,
  2030. "Request a specific difficulty from pools"),
  2031. OPT_WITH_ARG("--retries",
  2032. opt_set_intval, opt_show_intval, &opt_retries,
  2033. "Number of times to retry failed submissions before giving up (-1 means never)"),
  2034. OPT_WITH_ARG("--retry-pause",
  2035. set_null, NULL, NULL,
  2036. opt_hidden),
  2037. OPT_WITH_ARG("--rotate",
  2038. set_rotate, opt_show_intval, &opt_rotate_period,
  2039. "Change multipool strategy from failover to regularly rotate at N minutes"),
  2040. OPT_WITHOUT_ARG("--round-robin",
  2041. set_rr, &pool_strategy,
  2042. "Change multipool strategy from failover to round robin on failure"),
  2043. OPT_WITH_ARG("--scan|-S",
  2044. add_serial, NULL, NULL,
  2045. "Configure how to scan for mining devices"),
  2046. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  2047. add_serial, NULL, NULL,
  2048. opt_hidden),
  2049. OPT_WITH_ARG("--scan-time",
  2050. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2051. "Upper bound on time spent scanning current work, in seconds"),
  2052. OPT_WITH_ARG("-s",
  2053. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2054. opt_hidden),
  2055. OPT_WITH_ARG("--scantime",
  2056. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  2057. opt_hidden),
  2058. OPT_WITH_ARG("--sched-start",
  2059. set_schedtime, NULL, &schedstart,
  2060. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  2061. OPT_WITH_ARG("--sched-stop",
  2062. set_schedtime, NULL, &schedstop,
  2063. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  2064. #ifdef USE_SCRYPT
  2065. OPT_WITHOUT_ARG("--scrypt",
  2066. opt_set_bool, &opt_scrypt,
  2067. "Use the scrypt algorithm for mining (non-bitcoin)"),
  2068. #endif
  2069. OPT_WITH_ARG("--set-device|--set",
  2070. opt_string_elist_add, NULL, &opt_set_device_list,
  2071. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  2072. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2073. OPT_WITH_ARG("--shaders",
  2074. set_shaders, NULL, NULL,
  2075. opt_hidden),
  2076. #endif
  2077. #ifdef HAVE_PWD_H
  2078. OPT_WITH_ARG("--setuid",
  2079. opt_set_charp, NULL, &opt_setuid,
  2080. "Username of an unprivileged user to run as"),
  2081. #endif
  2082. OPT_WITH_ARG("--sharelog",
  2083. set_sharelog, NULL, NULL,
  2084. "Append share log to file"),
  2085. OPT_WITH_ARG("--shares",
  2086. opt_set_floatval, NULL, &opt_shares,
  2087. "Quit after mining 2^32 * N hashes worth of shares (default: unlimited)"),
  2088. OPT_WITHOUT_ARG("--show-processors",
  2089. opt_set_bool, &opt_show_procs,
  2090. "Show per processor statistics in summary"),
  2091. OPT_WITHOUT_ARG("--show-procs",
  2092. opt_set_bool, &opt_show_procs,
  2093. opt_hidden),
  2094. OPT_WITH_ARG("--skip-security-checks",
  2095. set_int_0_to_9999, NULL, &opt_skip_checks,
  2096. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  2097. OPT_WITH_ARG("--socks-proxy",
  2098. opt_set_charp, NULL, &opt_socks_proxy,
  2099. "Set socks proxy (host:port)"),
  2100. #ifdef USE_LIBEVENT
  2101. OPT_WITH_ARG("--stratum-port",
  2102. opt_set_intval, opt_show_intval, &stratumsrv_port,
  2103. "Port number to listen on for stratum miners (-1 means disabled)"),
  2104. #endif
  2105. OPT_WITHOUT_ARG("--submit-stale",
  2106. opt_set_bool, &opt_submit_stale,
  2107. opt_hidden),
  2108. OPT_WITH_ARG("--submit-threads",
  2109. opt_set_intval, opt_show_intval, &opt_submit_threads,
  2110. "Minimum number of concurrent share submissions (default: 64)"),
  2111. #ifdef HAVE_SYSLOG_H
  2112. OPT_WITHOUT_ARG("--syslog",
  2113. opt_set_bool, &use_syslog,
  2114. "Use system log for output messages (default: standard error)"),
  2115. #endif
  2116. OPT_WITH_ARG("--temp-cutoff",
  2117. set_temp_cutoff, NULL, &opt_cutofftemp,
  2118. opt_hidden),
  2119. OPT_WITH_ARG("--temp-hysteresis",
  2120. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  2121. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  2122. #ifdef HAVE_ADL
  2123. OPT_WITH_ARG("--temp-overheat",
  2124. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  2125. opt_hidden),
  2126. #endif
  2127. OPT_WITH_ARG("--temp-target",
  2128. set_temp_target, NULL, NULL,
  2129. opt_hidden),
  2130. OPT_WITHOUT_ARG("--text-only|-T",
  2131. opt_set_invbool, &use_curses,
  2132. #ifdef HAVE_CURSES
  2133. "Disable ncurses formatted screen output"
  2134. #else
  2135. opt_hidden
  2136. #endif
  2137. ),
  2138. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  2139. OPT_WITH_ARG("--thread-concurrency",
  2140. set_thread_concurrency, NULL, NULL,
  2141. opt_hidden),
  2142. #endif
  2143. #ifdef USE_UNICODE
  2144. OPT_WITHOUT_ARG("--unicode",
  2145. opt_set_bool, &use_unicode,
  2146. "Use Unicode characters in TUI"),
  2147. #endif
  2148. OPT_WITH_ARG("--url|-o",
  2149. set_url, NULL, NULL,
  2150. "URL for bitcoin JSON-RPC server"),
  2151. OPT_WITH_ARG("--user|-u",
  2152. set_user, NULL, NULL,
  2153. "Username for bitcoin JSON-RPC server"),
  2154. #ifdef HAVE_OPENCL
  2155. OPT_WITH_ARG("--vectors|-v",
  2156. set_vector, NULL, NULL,
  2157. opt_hidden),
  2158. #endif
  2159. OPT_WITHOUT_ARG("--verbose",
  2160. opt_set_bool, &opt_log_output,
  2161. "Log verbose output to stderr as well as status output"),
  2162. OPT_WITHOUT_ARG("--verbose-work-updates|--verbose-work-update",
  2163. opt_set_invbool, &opt_quiet_work_updates,
  2164. opt_hidden),
  2165. OPT_WITHOUT_ARG("--weighed-stats",
  2166. opt_set_bool, &opt_weighed_stats,
  2167. "Display statistics weighed to difficulty 1"),
  2168. #ifdef HAVE_OPENCL
  2169. OPT_WITH_ARG("--worksize|-w",
  2170. set_worksize, NULL, NULL,
  2171. opt_hidden),
  2172. #endif
  2173. OPT_WITHOUT_ARG("--unittest",
  2174. opt_set_bool, &opt_unittest, opt_hidden),
  2175. OPT_WITH_ARG("--userpass|-O",
  2176. set_userpass, NULL, NULL,
  2177. "Username:Password pair for bitcoin JSON-RPC server"),
  2178. OPT_WITHOUT_ARG("--worktime",
  2179. opt_set_bool, &opt_worktime,
  2180. "Display extra work time debug information"),
  2181. OPT_WITH_ARG("--pools",
  2182. opt_set_bool, NULL, NULL, opt_hidden),
  2183. OPT_ENDTABLE
  2184. };
  2185. static char *load_config(const char *arg, void __maybe_unused *unused);
  2186. static char *parse_config(json_t *config, bool fileconf, int * const fileconf_load_p)
  2187. {
  2188. static char err_buf[200];
  2189. struct opt_table *opt;
  2190. json_t *val;
  2191. if (fileconf && !*fileconf_load_p)
  2192. *fileconf_load_p = 1;
  2193. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2194. char *p, *name, *sp;
  2195. /* We don't handle subtables. */
  2196. assert(!(opt->type & OPT_SUBTABLE));
  2197. if (!opt->names)
  2198. continue;
  2199. /* Pull apart the option name(s). */
  2200. name = strdup(opt->names);
  2201. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2202. char *err = "Invalid value";
  2203. /* Ignore short options. */
  2204. if (p[1] != '-')
  2205. continue;
  2206. val = json_object_get(config, p+2);
  2207. if (!val)
  2208. continue;
  2209. if (opt->type & OPT_HASARG) {
  2210. if (json_is_string(val)) {
  2211. err = opt->cb_arg(json_string_value(val),
  2212. opt->u.arg);
  2213. } else if (json_is_number(val)) {
  2214. char buf[256], *p, *q;
  2215. snprintf(buf, 256, "%f", json_number_value(val));
  2216. if ( (p = strchr(buf, '.')) ) {
  2217. // Trim /\.0*$/ to work properly with integer-only arguments
  2218. q = p;
  2219. while (*(++q) == '0') {}
  2220. if (*q == '\0')
  2221. *p = '\0';
  2222. }
  2223. err = opt->cb_arg(buf, opt->u.arg);
  2224. } else if (json_is_array(val)) {
  2225. int n, size = json_array_size(val);
  2226. err = NULL;
  2227. for (n = 0; n < size && !err; n++) {
  2228. if (json_is_string(json_array_get(val, n)))
  2229. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2230. else if (json_is_object(json_array_get(val, n)))
  2231. err = parse_config(json_array_get(val, n), false, fileconf_load_p);
  2232. }
  2233. }
  2234. } else if (opt->type & OPT_NOARG) {
  2235. if (json_is_true(val))
  2236. err = opt->cb(opt->u.arg);
  2237. else if (json_is_boolean(val)) {
  2238. if (opt->cb == (void*)opt_set_bool)
  2239. err = opt_set_invbool(opt->u.arg);
  2240. else if (opt->cb == (void*)opt_set_invbool)
  2241. err = opt_set_bool(opt->u.arg);
  2242. }
  2243. }
  2244. if (err) {
  2245. /* Allow invalid values to be in configuration
  2246. * file, just skipping over them provided the
  2247. * JSON is still valid after that. */
  2248. if (fileconf) {
  2249. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2250. *fileconf_load_p = -1;
  2251. } else {
  2252. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2253. p, err);
  2254. return err_buf;
  2255. }
  2256. }
  2257. }
  2258. free(name);
  2259. }
  2260. val = json_object_get(config, JSON_INCLUDE_CONF);
  2261. if (val && json_is_string(val))
  2262. return load_config(json_string_value(val), NULL);
  2263. return NULL;
  2264. }
  2265. struct bfg_loaded_configfile *bfg_loaded_configfiles;
  2266. static char *load_config(const char *arg, void __maybe_unused *unused)
  2267. {
  2268. json_error_t err;
  2269. json_t *config;
  2270. char *json_error;
  2271. size_t siz;
  2272. struct bfg_loaded_configfile *cfginfo;
  2273. cfginfo = malloc(sizeof(*cfginfo));
  2274. *cfginfo = (struct bfg_loaded_configfile){
  2275. .filename = strdup(arg),
  2276. };
  2277. LL_APPEND(bfg_loaded_configfiles, cfginfo);
  2278. if (++include_count > JSON_MAX_DEPTH)
  2279. return JSON_MAX_DEPTH_ERR;
  2280. #if JANSSON_MAJOR_VERSION > 1
  2281. config = json_load_file(arg, 0, &err);
  2282. #else
  2283. config = json_load_file(arg, &err);
  2284. #endif
  2285. if (!json_is_object(config)) {
  2286. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2287. json_error = malloc(siz);
  2288. if (!json_error)
  2289. quit(1, "Malloc failure in json error");
  2290. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2291. return json_error;
  2292. }
  2293. config_loaded = true;
  2294. /* Parse the config now, so we can override it. That can keep pointers
  2295. * so don't free config object. */
  2296. return parse_config(config, true, &cfginfo->fileconf_load);
  2297. }
  2298. static void load_default_config(void)
  2299. {
  2300. char cnfbuf[PATH_MAX];
  2301. #if defined(unix)
  2302. if (getenv("HOME") && *getenv("HOME")) {
  2303. strcpy(cnfbuf, getenv("HOME"));
  2304. strcat(cnfbuf, "/");
  2305. } else
  2306. strcpy(cnfbuf, "");
  2307. char *dirp = cnfbuf + strlen(cnfbuf);
  2308. strcpy(dirp, ".bfgminer/");
  2309. strcat(dirp, def_conf);
  2310. if (access(cnfbuf, R_OK))
  2311. // No BFGMiner config, try Cgminer's...
  2312. strcpy(dirp, ".cgminer/cgminer.conf");
  2313. #else
  2314. strcpy(cnfbuf, "");
  2315. strcat(cnfbuf, def_conf);
  2316. #endif
  2317. if (!access(cnfbuf, R_OK))
  2318. load_config(cnfbuf, NULL);
  2319. }
  2320. extern const char *opt_argv0;
  2321. static char *opt_verusage_and_exit(const char *extra)
  2322. {
  2323. puts(packagename);
  2324. printf(" Lowlevel:%s\n", BFG_LOWLLIST);
  2325. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2326. printf(" Algorithms:%s\n", BFG_ALGOLIST);
  2327. printf(" Options:%s\n", BFG_OPTLIST);
  2328. printf("%s", opt_usage(opt_argv0, extra));
  2329. fflush(stdout);
  2330. exit(0);
  2331. }
  2332. /* These options are parsed before anything else */
  2333. static struct opt_table opt_early_table[] = {
  2334. OPT_EARLY_WITH_ARG("--config|-c",
  2335. set_bool_ignore_arg, NULL, &config_loaded,
  2336. opt_hidden),
  2337. OPT_EARLY_WITHOUT_ARG("--no-config",
  2338. opt_set_bool, &config_loaded,
  2339. "Inhibit loading default config file"),
  2340. OPT_ENDTABLE
  2341. };
  2342. /* These options are available from commandline only */
  2343. static struct opt_table opt_cmdline_table[] = {
  2344. OPT_WITH_ARG("--config|-c",
  2345. load_config, NULL, NULL,
  2346. "Load a JSON-format configuration file\n"
  2347. "See example.conf for an example configuration."),
  2348. OPT_EARLY_WITHOUT_ARG("--no-config",
  2349. opt_set_bool, &config_loaded,
  2350. "Inhibit loading default config file"),
  2351. OPT_WITHOUT_ARG("--help|-h",
  2352. opt_verusage_and_exit, NULL,
  2353. "Print this message"),
  2354. #ifdef HAVE_OPENCL
  2355. OPT_WITHOUT_ARG("--ndevs|-n",
  2356. print_ndevs_and_exit, &nDevs,
  2357. opt_hidden),
  2358. #endif
  2359. OPT_WITHOUT_ARG("--version|-V",
  2360. opt_version_and_exit, packagename,
  2361. "Display version and exit"),
  2362. OPT_ENDTABLE
  2363. };
  2364. static bool jobj_binary(const json_t *obj, const char *key,
  2365. void *buf, size_t buflen, bool required)
  2366. {
  2367. const char *hexstr;
  2368. json_t *tmp;
  2369. tmp = json_object_get(obj, key);
  2370. if (unlikely(!tmp)) {
  2371. if (unlikely(required))
  2372. applog(LOG_ERR, "JSON key '%s' not found", key);
  2373. return false;
  2374. }
  2375. hexstr = json_string_value(tmp);
  2376. if (unlikely(!hexstr)) {
  2377. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2378. return false;
  2379. }
  2380. if (!hex2bin(buf, hexstr, buflen))
  2381. return false;
  2382. return true;
  2383. }
  2384. static void calc_midstate(struct work *work)
  2385. {
  2386. union {
  2387. unsigned char c[64];
  2388. uint32_t i[16];
  2389. } data;
  2390. swap32yes(&data.i[0], work->data, 16);
  2391. sha256_ctx ctx;
  2392. sha256_init(&ctx);
  2393. sha256_update(&ctx, data.c, 64);
  2394. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2395. swap32tole(work->midstate, work->midstate, 8);
  2396. }
  2397. static
  2398. struct bfg_tmpl_ref *tmpl_makeref(blktemplate_t * const tmpl)
  2399. {
  2400. struct bfg_tmpl_ref * const tr = malloc(sizeof(*tr));
  2401. *tr = (struct bfg_tmpl_ref){
  2402. .tmpl = tmpl,
  2403. .refcount = 1,
  2404. };
  2405. mutex_init(&tr->mutex);
  2406. return tr;
  2407. }
  2408. static
  2409. void tmpl_incref(struct bfg_tmpl_ref * const tr)
  2410. {
  2411. mutex_lock(&tr->mutex);
  2412. ++tr->refcount;
  2413. mutex_unlock(&tr->mutex);
  2414. }
  2415. void tmpl_decref(struct bfg_tmpl_ref * const tr)
  2416. {
  2417. mutex_lock(&tr->mutex);
  2418. bool free_tmpl = !--tr->refcount;
  2419. mutex_unlock(&tr->mutex);
  2420. if (free_tmpl)
  2421. {
  2422. blktmpl_free(tr->tmpl);
  2423. mutex_destroy(&tr->mutex);
  2424. free(tr);
  2425. }
  2426. }
  2427. static struct work *make_work(void)
  2428. {
  2429. struct work *work = calloc(1, sizeof(struct work));
  2430. if (unlikely(!work))
  2431. quit(1, "Failed to calloc work in make_work");
  2432. cg_wlock(&control_lock);
  2433. work->id = total_work++;
  2434. cg_wunlock(&control_lock);
  2435. return work;
  2436. }
  2437. /* This is the central place all work that is about to be retired should be
  2438. * cleaned to remove any dynamically allocated arrays within the struct */
  2439. void clean_work(struct work *work)
  2440. {
  2441. free(work->job_id);
  2442. bytes_free(&work->nonce2);
  2443. free(work->nonce1);
  2444. if (work->device_data_free_func)
  2445. work->device_data_free_func(work);
  2446. if (work->tr)
  2447. tmpl_decref(work->tr);
  2448. memset(work, 0, sizeof(struct work));
  2449. }
  2450. /* All dynamically allocated work structs should be freed here to not leak any
  2451. * ram from arrays allocated within the work struct */
  2452. void free_work(struct work *work)
  2453. {
  2454. clean_work(work);
  2455. free(work);
  2456. }
  2457. static const char *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";
  2458. // Must only be called with ch_lock held!
  2459. static
  2460. void __update_block_title(const unsigned char *hash_swap)
  2461. {
  2462. if (hash_swap) {
  2463. char tmp[17];
  2464. // Only provided when the block has actually changed
  2465. free(current_hash);
  2466. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2467. bin2hex(tmp, &hash_swap[24], 8);
  2468. memset(current_hash, '.', 3);
  2469. memcpy(&current_hash[3], tmp, 17);
  2470. known_blkheight_current = false;
  2471. } else if (likely(known_blkheight_current)) {
  2472. return;
  2473. }
  2474. if (current_block_id == known_blkheight_blkid) {
  2475. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2476. if (known_blkheight < 1000000) {
  2477. memmove(&current_hash[3], &current_hash[11], 8);
  2478. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2479. }
  2480. known_blkheight_current = true;
  2481. }
  2482. }
  2483. static
  2484. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2485. {
  2486. if (known_blkheight == blkheight)
  2487. return;
  2488. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2489. cg_wlock(&ch_lock);
  2490. known_blkheight = blkheight;
  2491. known_blkheight_blkid = block_id;
  2492. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2493. if (block_id == current_block_id)
  2494. __update_block_title(NULL);
  2495. cg_wunlock(&ch_lock);
  2496. }
  2497. static
  2498. void pool_set_opaque(struct pool *pool, bool opaque)
  2499. {
  2500. if (pool->swork.opaque == opaque)
  2501. return;
  2502. pool->swork.opaque = opaque;
  2503. if (opaque)
  2504. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2505. pool->pool_no);
  2506. else
  2507. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2508. pool->pool_no);
  2509. }
  2510. bool pool_may_redirect_to(struct pool * const pool, const char * const uri)
  2511. {
  2512. if (uri_get_param_bool(pool->rpc_url, "redirect", false))
  2513. return true;
  2514. return match_domains(pool->rpc_url, strlen(pool->rpc_url), uri, strlen(uri));
  2515. }
  2516. void set_simple_ntime_roll_limit(struct ntime_roll_limits * const nrl, const uint32_t ntime_base, const int ntime_roll)
  2517. {
  2518. *nrl = (struct ntime_roll_limits){
  2519. .min = ntime_base,
  2520. .max = ntime_base + ntime_roll,
  2521. .minoff = -ntime_roll,
  2522. .maxoff = ntime_roll,
  2523. };
  2524. }
  2525. void work_set_simple_ntime_roll_limit(struct work * const work, const int ntime_roll)
  2526. {
  2527. set_simple_ntime_roll_limit(&work->ntime_roll_limits, upk_u32be(work->data, 0x44), ntime_roll);
  2528. }
  2529. static
  2530. void refresh_bitcoind_address(const bool fresh)
  2531. {
  2532. if (!have_at_least_one_getcbaddr)
  2533. return;
  2534. char getcbaddr_req[60];
  2535. CURL *curl = NULL;
  2536. json_t *json, *j2;
  2537. const char *s, *s2;
  2538. bytes_t newscript = BYTES_INIT;
  2539. snprintf(getcbaddr_req, sizeof(getcbaddr_req), "{\"method\":\"get%saddress\",\"id\":0,\"params\":[\"BFGMiner\"]}", fresh ? "new" : "account");
  2540. for (int i = 0; i < total_pools; ++i)
  2541. {
  2542. struct pool * const pool = pools[i];
  2543. if (!uri_get_param_bool(pool->rpc_url, "getcbaddr", false))
  2544. continue;
  2545. applog(LOG_DEBUG, "Refreshing coinbase address from pool %d", pool->pool_no);
  2546. if (!curl)
  2547. {
  2548. curl = curl_easy_init();
  2549. if (unlikely(!curl))
  2550. {
  2551. applogfail(LOG_ERR, "curl_easy_init");
  2552. break;
  2553. }
  2554. }
  2555. json = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, getcbaddr_req, false, false, NULL, pool, true);
  2556. j2 = json_object_get(json, "error");
  2557. if (unlikely(!json_is_null(j2)))
  2558. {
  2559. char *estr = NULL;
  2560. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, json_string_value(j2) ?: (estr = json_dumps_ANY(j2, JSON_ENSURE_ASCII | JSON_SORT_KEYS)));
  2561. free(estr);
  2562. continue;
  2563. }
  2564. s = bfg_json_obj_string(json, "result", NULL);
  2565. if (unlikely(!s))
  2566. {
  2567. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 'g', pool->pool_no, "(return value was not a String)");
  2568. continue;
  2569. }
  2570. s2 = set_b58addr(s, &newscript);
  2571. if (unlikely(s2))
  2572. {
  2573. applog(LOG_WARNING, "Error %cetting coinbase address from pool %d: %s", 's', pool->pool_no, s2);
  2574. continue;
  2575. }
  2576. if (bytes_eq(&newscript, &opt_coinbase_script))
  2577. {
  2578. applog(LOG_DEBUG, "Pool %d returned coinbase address already in use (%s)", pool->pool_no, s2);
  2579. break;
  2580. }
  2581. bytes_assimilate(&opt_coinbase_script, &newscript);
  2582. applog(LOG_NOTICE, "Now using coinbase address %s, provided by pool %d", s, pool->pool_no);
  2583. break;
  2584. }
  2585. bytes_free(&newscript);
  2586. if (curl)
  2587. curl_easy_cleanup(curl);
  2588. }
  2589. static double target_diff(const unsigned char *);
  2590. #define GBT_XNONCESZ (sizeof(uint32_t))
  2591. #if BLKMAKER_VERSION > 4
  2592. #define blkmk_append_coinbase_safe(tmpl, append, appendsz) \
  2593. blkmk_append_coinbase_safe2(tmpl, append, appendsz, GBT_XNONCESZ, false)
  2594. #endif
  2595. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2596. {
  2597. json_t *res_val = json_object_get(val, "result");
  2598. json_t *tmp_val;
  2599. bool ret = false;
  2600. struct timeval tv_now;
  2601. if (unlikely(detect_algo == 1)) {
  2602. json_t *tmp = json_object_get(res_val, "algorithm");
  2603. const char *v = tmp ? json_string_value(tmp) : "";
  2604. if (strncasecmp(v, "scrypt", 6))
  2605. detect_algo = 2;
  2606. }
  2607. timer_set_now(&tv_now);
  2608. if (work->tr)
  2609. {
  2610. blktemplate_t * const tmpl = work->tr->tmpl;
  2611. const char *err = blktmpl_add_jansson(tmpl, res_val, tv_now.tv_sec);
  2612. if (err) {
  2613. applog(LOG_ERR, "blktmpl error: %s", err);
  2614. return false;
  2615. }
  2616. work->rolltime = blkmk_time_left(tmpl, tv_now.tv_sec);
  2617. #if BLKMAKER_VERSION > 1
  2618. if ((!tmpl->cbtxn) && !bytes_len(&opt_coinbase_script))
  2619. {
  2620. // We are about to fail here because we lack a coinbase transaction
  2621. // Try to get an address from bitcoind to use to avoid this
  2622. refresh_bitcoind_address(false);
  2623. }
  2624. if (bytes_len(&opt_coinbase_script))
  2625. {
  2626. bool newcb;
  2627. #if BLKMAKER_VERSION > 2
  2628. blkmk_init_generation2(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script), &newcb);
  2629. #else
  2630. newcb = !tmpl->cbtxn;
  2631. blkmk_init_generation(tmpl, bytes_buf(&opt_coinbase_script), bytes_len(&opt_coinbase_script));
  2632. #endif
  2633. if (newcb)
  2634. {
  2635. ssize_t ae = blkmk_append_coinbase_safe(tmpl, &template_nonce, sizeof(template_nonce));
  2636. if (ae < (ssize_t)sizeof(template_nonce))
  2637. 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);
  2638. ++template_nonce;
  2639. }
  2640. }
  2641. #endif
  2642. #if BLKMAKER_VERSION > 0
  2643. {
  2644. ssize_t ae = blkmk_append_coinbase_safe(tmpl, opt_coinbase_sig, 101);
  2645. static bool appenderr = false;
  2646. if (ae <= 0) {
  2647. if (opt_coinbase_sig) {
  2648. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2649. appenderr = true;
  2650. }
  2651. } else if (ae >= 3 || opt_coinbase_sig) {
  2652. const char *cbappend = opt_coinbase_sig;
  2653. const char full[] = PACKAGE " " VERSION;
  2654. if (!cbappend) {
  2655. if ((size_t)ae >= sizeof(full) - 1)
  2656. cbappend = full;
  2657. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2658. cbappend = PACKAGE;
  2659. else
  2660. cbappend = "BFG";
  2661. }
  2662. size_t cbappendsz = strlen(cbappend);
  2663. static bool truncatewarning = false;
  2664. if (cbappendsz <= (size_t)ae) {
  2665. if (cbappendsz < (size_t)ae)
  2666. // If we have space, include the trailing \0
  2667. ++cbappendsz;
  2668. ae = cbappendsz;
  2669. truncatewarning = false;
  2670. } else {
  2671. char *tmp = malloc(ae + 1);
  2672. memcpy(tmp, opt_coinbase_sig, ae);
  2673. tmp[ae] = '\0';
  2674. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2675. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2676. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2677. free(tmp);
  2678. truncatewarning = true;
  2679. }
  2680. ae = blkmk_append_coinbase_safe(tmpl, cbappend, ae);
  2681. if (ae <= 0) {
  2682. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2683. appenderr = true;
  2684. } else
  2685. appenderr = false;
  2686. }
  2687. }
  2688. #endif
  2689. if (blkmk_get_data(tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2690. return false;
  2691. swap32yes(work->data, work->data, 80 / 4);
  2692. memcpy(&work->data[80], workpadding_bin, 48);
  2693. work->ntime_roll_limits = (struct ntime_roll_limits){
  2694. .min = tmpl->mintime,
  2695. .max = tmpl->maxtime,
  2696. .minoff = tmpl->mintimeoff,
  2697. .maxoff = tmpl->maxtimeoff,
  2698. };
  2699. const struct blktmpl_longpoll_req *lp;
  2700. if ((lp = blktmpl_get_longpoll(tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2701. free(pool->lp_id);
  2702. pool->lp_id = strdup(lp->id);
  2703. #if 0 /* This just doesn't work :( */
  2704. curl_socket_t sock = pool->lp_socket;
  2705. if (sock != CURL_SOCKET_BAD) {
  2706. pool->lp_socket = CURL_SOCKET_BAD;
  2707. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2708. shutdown(sock, SHUT_RDWR);
  2709. }
  2710. #endif
  2711. }
  2712. }
  2713. else
  2714. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2715. applog(LOG_ERR, "JSON inval data");
  2716. return false;
  2717. }
  2718. else
  2719. work_set_simple_ntime_roll_limit(work, 0);
  2720. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2721. // Calculate it ourselves
  2722. applog(LOG_DEBUG, "Calculating midstate locally");
  2723. calc_midstate(work);
  2724. }
  2725. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2726. applog(LOG_ERR, "JSON inval target");
  2727. return false;
  2728. }
  2729. if (work->tr)
  2730. {
  2731. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2732. {
  2733. int p = (sizeof(work->target) - 1) - i;
  2734. unsigned char c = work->target[i];
  2735. work->target[i] = work->target[p];
  2736. work->target[p] = c;
  2737. }
  2738. }
  2739. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2740. uint32_t blkheight = json_number_value(tmp_val);
  2741. uint32_t block_id = ((uint32_t*)work->data)[1];
  2742. have_block_height(block_id, blkheight);
  2743. }
  2744. memset(work->hash, 0, sizeof(work->hash));
  2745. work->tv_staged = tv_now;
  2746. #if BLKMAKER_VERSION > 4
  2747. if (work->tr)
  2748. {
  2749. blktemplate_t * const tmpl = work->tr->tmpl;
  2750. uint8_t buf[80];
  2751. int16_t expire;
  2752. uint8_t *cbtxn;
  2753. size_t cbtxnsz;
  2754. size_t cbextranonceoffset;
  2755. int branchcount;
  2756. libblkmaker_hash_t *branches;
  2757. if (blkmk_get_mdata(tmpl, buf, sizeof(buf), tv_now.tv_sec, &expire, &cbtxn, &cbtxnsz, &cbextranonceoffset, &branchcount, &branches, GBT_XNONCESZ, false))
  2758. {
  2759. struct stratum_work * const swork = &pool->swork;
  2760. const size_t branchdatasz = branchcount * 0x20;
  2761. cg_wlock(&pool->data_lock);
  2762. swork->tr = work->tr;
  2763. bytes_assimilate_raw(&swork->coinbase, cbtxn, cbtxnsz, cbtxnsz);
  2764. swork->nonce2_offset = cbextranonceoffset;
  2765. bytes_assimilate_raw(&swork->merkle_bin, branches, branchdatasz, branchdatasz);
  2766. swork->merkles = branchcount;
  2767. memcpy(swork->header1, &buf[0], 36);
  2768. swork->ntime = le32toh(*(uint32_t *)(&buf[68]));
  2769. swork->tv_received = tv_now;
  2770. memcpy(swork->diffbits, &buf[72], 4);
  2771. memcpy(swork->target, work->target, sizeof(swork->target));
  2772. free(swork->job_id);
  2773. swork->job_id = NULL;
  2774. swork->clean = true;
  2775. swork->work_restart_id = pool->work_restart_id;
  2776. // FIXME: Do something with expire
  2777. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  2778. pool->nonce2 = 0;
  2779. cg_wunlock(&pool->data_lock);
  2780. }
  2781. else
  2782. applog(LOG_DEBUG, "blkmk_get_mdata failed for pool %u", pool->pool_no);
  2783. }
  2784. #endif // BLKMAKER_VERSION > 4
  2785. pool_set_opaque(pool, !work->tr);
  2786. ret = true;
  2787. return ret;
  2788. }
  2789. /* Returns whether the pool supports local work generation or not. */
  2790. static bool pool_localgen(struct pool *pool)
  2791. {
  2792. return (pool->last_work_copy || pool->has_stratum);
  2793. }
  2794. int dev_from_id(int thr_id)
  2795. {
  2796. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2797. return cgpu->device_id;
  2798. }
  2799. /* Create an exponentially decaying average over the opt_log_interval */
  2800. void decay_time(double *f, double fadd, double fsecs)
  2801. {
  2802. double ftotal, fprop;
  2803. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2804. ftotal = 1.0 + fprop;
  2805. *f += (fadd * fprop);
  2806. *f /= ftotal;
  2807. }
  2808. static int __total_staged(void)
  2809. {
  2810. return HASH_COUNT(staged_work);
  2811. }
  2812. static int total_staged(void)
  2813. {
  2814. int ret;
  2815. mutex_lock(stgd_lock);
  2816. ret = __total_staged();
  2817. mutex_unlock(stgd_lock);
  2818. return ret;
  2819. }
  2820. #ifdef HAVE_CURSES
  2821. WINDOW *mainwin, *statuswin, *logwin;
  2822. #endif
  2823. double total_secs = 1.0;
  2824. static char statusline[256];
  2825. /* logstart is where the log window should start */
  2826. static int devcursor, logstart, logcursor;
  2827. #ifdef HAVE_CURSES
  2828. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2829. static int statusy;
  2830. static int devsummaryYOffset;
  2831. static int total_lines;
  2832. #endif
  2833. #ifdef HAVE_OPENCL
  2834. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2835. #endif
  2836. struct cgpu_info *cpus;
  2837. bool _bfg_console_cancel_disabled;
  2838. int _bfg_console_prev_cancelstate;
  2839. #ifdef HAVE_CURSES
  2840. #define lock_curses() bfg_console_lock()
  2841. #define unlock_curses() bfg_console_unlock()
  2842. static bool curses_active_locked(void)
  2843. {
  2844. bool ret;
  2845. lock_curses();
  2846. ret = curses_active;
  2847. if (!ret)
  2848. unlock_curses();
  2849. return ret;
  2850. }
  2851. // Cancellable getch
  2852. int my_cancellable_getch(void)
  2853. {
  2854. // This only works because the macro only hits direct getch() calls
  2855. typedef int (*real_getch_t)(void);
  2856. const real_getch_t real_getch = __real_getch;
  2857. int type, rv;
  2858. bool sct;
  2859. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2860. rv = real_getch();
  2861. if (sct)
  2862. pthread_setcanceltype(type, &type);
  2863. return rv;
  2864. }
  2865. #ifdef PDCURSES
  2866. static
  2867. int bfg_wresize(WINDOW *win, int lines, int columns)
  2868. {
  2869. int rv = wresize(win, lines, columns);
  2870. int x, y;
  2871. getyx(win, y, x);
  2872. if (unlikely(y >= lines || x >= columns))
  2873. {
  2874. if (y >= lines)
  2875. y = lines - 1;
  2876. if (x >= columns)
  2877. x = columns - 1;
  2878. wmove(win, y, x);
  2879. }
  2880. return rv;
  2881. }
  2882. #else
  2883. # define bfg_wresize wresize
  2884. #endif
  2885. #endif
  2886. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2887. {
  2888. va_list ap;
  2889. size_t presz = strlen(buf);
  2890. va_start(ap, fmt);
  2891. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2892. va_end(ap);
  2893. }
  2894. double stats_elapsed(struct cgminer_stats *stats)
  2895. {
  2896. struct timeval now;
  2897. double elapsed;
  2898. if (stats->start_tv.tv_sec == 0)
  2899. elapsed = total_secs;
  2900. else {
  2901. cgtime(&now);
  2902. elapsed = tdiff(&now, &stats->start_tv);
  2903. }
  2904. if (elapsed < 1.0)
  2905. elapsed = 1.0;
  2906. return elapsed;
  2907. }
  2908. bool drv_ready(struct cgpu_info *cgpu)
  2909. {
  2910. switch (cgpu->status) {
  2911. case LIFE_INIT:
  2912. case LIFE_DEAD2:
  2913. return false;
  2914. default:
  2915. return true;
  2916. }
  2917. }
  2918. double cgpu_utility(struct cgpu_info *cgpu)
  2919. {
  2920. double dev_runtime = cgpu_runtime(cgpu);
  2921. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2922. }
  2923. #define suffix_string(val, buf, bufsiz, sigdigits) do{ \
  2924. _Static_assert(sigdigits == 0, "suffix_string only supported with sigdigits==0"); \
  2925. format_unit3(buf, bufsiz, FUP_DIFF, "", H2B_SHORTV, val, -1); \
  2926. }while(0)
  2927. static float
  2928. utility_to_hashrate(double utility)
  2929. {
  2930. return utility * 0x4444444;
  2931. }
  2932. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2933. static const int _unitbase = 4;
  2934. static
  2935. void pick_unit(float hashrate, unsigned char *unit)
  2936. {
  2937. unsigned char i;
  2938. if (hashrate == 0 || !isfinite(hashrate))
  2939. {
  2940. if (*unit < _unitbase)
  2941. *unit = _unitbase;
  2942. return;
  2943. }
  2944. hashrate *= 1e12;
  2945. for (i = 0; i < *unit; ++i)
  2946. hashrate /= 1e3;
  2947. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2948. while (hashrate >= 999.95)
  2949. {
  2950. hashrate /= 1e3;
  2951. if (likely(_unitchar[*unit] != '?'))
  2952. ++*unit;
  2953. }
  2954. }
  2955. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2956. enum h2bs_fmt {
  2957. H2B_NOUNIT, // "xxx.x"
  2958. H2B_SHORT, // "xxx.xMH/s"
  2959. H2B_SPACED, // "xxx.x MH/s"
  2960. H2B_SHORTV, // Like H2B_SHORT, but omit space for base unit
  2961. };
  2962. enum bfu_floatprec {
  2963. FUP_INTEGER,
  2964. FUP_HASHES,
  2965. FUP_BTC,
  2966. FUP_DIFF,
  2967. };
  2968. static
  2969. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2970. {
  2971. char *s = buf;
  2972. unsigned char prec, i, unit;
  2973. int rv = 0;
  2974. if (unitin == -1)
  2975. {
  2976. unit = 0;
  2977. hashrate_pick_unit(hashrate, &unit);
  2978. }
  2979. else
  2980. unit = unitin;
  2981. hashrate *= 1e12;
  2982. for (i = 0; i < unit; ++i)
  2983. hashrate /= 1000;
  2984. switch (fprec)
  2985. {
  2986. case FUP_HASHES:
  2987. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2988. if (hashrate >= 99.995 || unit < 6)
  2989. prec = 1;
  2990. else
  2991. prec = 2;
  2992. _SNP("%5.*f", prec, hashrate);
  2993. break;
  2994. case FUP_INTEGER:
  2995. _SNP("%3d", (int)hashrate);
  2996. break;
  2997. case FUP_BTC:
  2998. if (hashrate >= 99.995)
  2999. prec = 0;
  3000. else
  3001. prec = 2;
  3002. _SNP("%5.*f", prec, hashrate);
  3003. break;
  3004. case FUP_DIFF:
  3005. if (unit > _unitbase)
  3006. _SNP("%.3g", hashrate);
  3007. else
  3008. _SNP("%u", (unsigned int)hashrate);
  3009. }
  3010. if (fmt != H2B_NOUNIT)
  3011. {
  3012. char uc[3] = {_unitchar[unit], '\0'};
  3013. switch (fmt) {
  3014. case H2B_SPACED:
  3015. _SNP(" ");
  3016. default:
  3017. break;
  3018. case H2B_SHORTV:
  3019. if (isspace(uc[0]))
  3020. uc[0] = '\0';
  3021. }
  3022. if (uc[0] == '\xb5')
  3023. // Convert to UTF-8
  3024. snprintf(uc, sizeof(uc), "%s", U8_MICRO);
  3025. _SNP("%s%s", uc, measurement);
  3026. }
  3027. return rv;
  3028. }
  3029. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  3030. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  3031. static
  3032. 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)
  3033. {
  3034. unsigned char unit = 0;
  3035. bool allzero = true;
  3036. int i;
  3037. size_t delimsz = 0;
  3038. char *buf = buflist[0];
  3039. size_t bufsz = bufszlist[0];
  3040. size_t itemwidth = (floatprec ? 5 : 3);
  3041. if (!isarray)
  3042. delimsz = strlen(delim);
  3043. for (i = 0; i < count; ++i)
  3044. if (numbers[i] != 0)
  3045. {
  3046. pick_unit(numbers[i], &unit);
  3047. allzero = false;
  3048. }
  3049. if (allzero)
  3050. unit = _unitbase;
  3051. --count;
  3052. for (i = 0; i < count; ++i)
  3053. {
  3054. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  3055. if (isarray)
  3056. {
  3057. buf = buflist[i + 1];
  3058. bufsz = bufszlist[i + 1];
  3059. }
  3060. else
  3061. {
  3062. buf += itemwidth;
  3063. bufsz -= itemwidth;
  3064. if (delimsz > bufsz)
  3065. delimsz = bufsz;
  3066. memcpy(buf, delim, delimsz);
  3067. buf += delimsz;
  3068. bufsz -= delimsz;
  3069. }
  3070. }
  3071. // Last entry has the unit
  3072. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  3073. return buflist[0];
  3074. }
  3075. #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)
  3076. #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)
  3077. static
  3078. int percentf3(char * const buf, size_t sz, double p, const double t)
  3079. {
  3080. char *s = buf;
  3081. int rv = 0;
  3082. if (!p)
  3083. _SNP("none");
  3084. else
  3085. if (t <= p)
  3086. _SNP("100%%");
  3087. else
  3088. {
  3089. p /= t;
  3090. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  3091. _SNP(".%02.0f%%", p * 10000); // ".01%"
  3092. else
  3093. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  3094. _SNP("%.1f%%", p * 100); // "9.1%"
  3095. else
  3096. _SNP("%3.0f%%", p * 100); // " 99%"
  3097. }
  3098. return rv;
  3099. }
  3100. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  3101. static
  3102. void test_decimal_width()
  3103. {
  3104. // The pipe character at end of each line should perfectly line up
  3105. char printbuf[512];
  3106. char testbuf1[64];
  3107. char testbuf2[64];
  3108. char testbuf3[64];
  3109. char testbuf4[64];
  3110. double testn;
  3111. int width;
  3112. int saved;
  3113. // Hotspots around 0.1 and 0.01
  3114. saved = -1;
  3115. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  3116. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  3117. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  3118. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  3119. if (unlikely((saved != -1) && (width != saved))) {
  3120. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  3121. applog(LOG_ERR, "%s", printbuf);
  3122. }
  3123. saved = width;
  3124. }
  3125. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  3126. saved = -1;
  3127. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  3128. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3129. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3130. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3131. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  3132. width = utf8_strlen(printbuf);
  3133. if (unlikely((saved != -1) && (width != saved))) {
  3134. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  3135. applog(LOG_ERR, "%s", printbuf);
  3136. }
  3137. saved = width;
  3138. }
  3139. // Hotspot around unit transition boundary in pick_unit
  3140. saved = -1;
  3141. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  3142. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  3143. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  3144. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  3145. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  3146. snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  3147. width = utf8_strlen(printbuf);
  3148. if (unlikely((saved != -1) && (width != saved))) {
  3149. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  3150. applog(LOG_ERR, "%s", printbuf);
  3151. }
  3152. saved = width;
  3153. }
  3154. }
  3155. #ifdef HAVE_CURSES
  3156. static void adj_width(int var, int *length);
  3157. #endif
  3158. #ifdef HAVE_CURSES
  3159. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  3160. static
  3161. void format_statline(char *buf, size_t bufsz, const char *cHr, const char *aHr, const char *uHr, int accepted, int rejected, int stale, int wnotaccepted, int waccepted, int hwerrs, int bad_diff1, int allnonces)
  3162. {
  3163. char rejpcbuf[6];
  3164. char bnbuf[6];
  3165. adj_width(accepted, &awidth);
  3166. adj_width(rejected, &rwidth);
  3167. adj_width(stale, &swidth);
  3168. adj_width(hwerrs, &hwwidth);
  3169. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3170. percentf3(bnbuf, sizeof(bnbuf), bad_diff1, allnonces);
  3171. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  3172. cHr, aHr, uHr,
  3173. awidth, accepted,
  3174. rwidth, rejected,
  3175. swidth, stale,
  3176. rejpcbuf,
  3177. hwwidth, hwerrs,
  3178. bnbuf
  3179. );
  3180. }
  3181. static
  3182. const char *pool_proto_str(const struct pool * const pool)
  3183. {
  3184. if (pool->idle)
  3185. return "Dead ";
  3186. if (pool->has_stratum)
  3187. return "Strtm";
  3188. if (pool->lp_url && pool->proto != pool->lp_proto)
  3189. return "Mixed";
  3190. switch (pool->proto)
  3191. {
  3192. case PLP_GETBLOCKTEMPLATE:
  3193. return " GBT ";
  3194. case PLP_GETWORK:
  3195. return "GWork";
  3196. default:
  3197. return "Alive";
  3198. }
  3199. }
  3200. #endif
  3201. static inline
  3202. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  3203. {
  3204. if (!(use_unicode && have_unicode_degrees))
  3205. maybe_unicode = false;
  3206. if (temp && *temp > 0.)
  3207. if (maybe_unicode)
  3208. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  3209. else
  3210. snprintf(buf, bufsz, "%4.1fC", *temp);
  3211. else
  3212. {
  3213. if (temp)
  3214. snprintf(buf, bufsz, " ");
  3215. if (maybe_unicode)
  3216. tailsprintf(buf, bufsz, " ");
  3217. }
  3218. tailsprintf(buf, bufsz, " | ");
  3219. }
  3220. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  3221. {
  3222. #ifndef HAVE_CURSES
  3223. assert(for_curses == false);
  3224. #endif
  3225. struct device_drv *drv = cgpu->drv;
  3226. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  3227. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[max(ALLOC_H2B_SHORT, ALLOC_H2B_SPACED)+3+1];
  3228. char rejpcbuf[6];
  3229. char bnbuf[6];
  3230. double dev_runtime;
  3231. if (!opt_show_procs)
  3232. cgpu = cgpu->device;
  3233. dev_runtime = cgpu_runtime(cgpu);
  3234. double rolling, mhashes;
  3235. int accepted, rejected, stale;
  3236. double waccepted;
  3237. double wnotaccepted;
  3238. int hwerrs;
  3239. double bad_diff1, good_diff1;
  3240. rolling = mhashes = waccepted = wnotaccepted = 0;
  3241. accepted = rejected = stale = hwerrs = bad_diff1 = good_diff1 = 0;
  3242. {
  3243. struct cgpu_info *slave = cgpu;
  3244. for (int i = 0; i < cgpu->procs; ++i, (slave = slave->next_proc))
  3245. {
  3246. slave->utility = slave->accepted / dev_runtime * 60;
  3247. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  3248. rolling += slave->rolling;
  3249. mhashes += slave->total_mhashes;
  3250. if (opt_weighed_stats)
  3251. {
  3252. accepted += slave->diff_accepted;
  3253. rejected += slave->diff_rejected;
  3254. stale += slave->diff_stale;
  3255. }
  3256. else
  3257. {
  3258. accepted += slave->accepted;
  3259. rejected += slave->rejected;
  3260. stale += slave->stale;
  3261. }
  3262. waccepted += slave->diff_accepted;
  3263. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  3264. hwerrs += slave->hw_errors;
  3265. bad_diff1 += slave->bad_diff1;
  3266. good_diff1 += slave->diff1;
  3267. if (opt_show_procs)
  3268. break;
  3269. }
  3270. }
  3271. double wtotal = (waccepted + wnotaccepted);
  3272. multi_format_unit_array2(
  3273. ((char*[]){cHr, aHr, uHr}),
  3274. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  3275. true, "h/s", hashrate_style,
  3276. 3,
  3277. 1e6*rolling,
  3278. 1e6*mhashes / dev_runtime,
  3279. utility_to_hashrate(good_diff1 * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  3280. // Processor representation
  3281. #ifdef HAVE_CURSES
  3282. if (for_curses)
  3283. {
  3284. if (opt_show_procs)
  3285. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  3286. else
  3287. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  3288. }
  3289. else
  3290. #endif
  3291. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  3292. if (include_serial_in_statline && cgpu->dev_serial)
  3293. tailsprintf(buf, bufsz, "[serial=%s] ", cgpu->dev_serial);
  3294. if (unlikely(cgpu->status == LIFE_INIT))
  3295. {
  3296. tailsprintf(buf, bufsz, "Initializing...");
  3297. return;
  3298. }
  3299. {
  3300. const size_t bufln = strlen(buf);
  3301. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  3302. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  3303. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  3304. else
  3305. {
  3306. float temp = cgpu->temp;
  3307. if (!opt_show_procs)
  3308. {
  3309. // Find the highest temperature of all processors
  3310. struct cgpu_info *proc = cgpu;
  3311. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3312. if (proc->temp > temp)
  3313. temp = proc->temp;
  3314. }
  3315. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  3316. }
  3317. }
  3318. #ifdef HAVE_CURSES
  3319. if (for_curses)
  3320. {
  3321. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  3322. const char *cHrStats;
  3323. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3324. bool all_dead = true, all_off = true, all_rdrv = true;
  3325. struct cgpu_info *proc = cgpu;
  3326. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3327. {
  3328. switch (cHrStatsI) {
  3329. default:
  3330. if (proc->status == LIFE_WAIT)
  3331. cHrStatsI = 5;
  3332. case 5:
  3333. if (proc->deven == DEV_RECOVER_ERR)
  3334. cHrStatsI = 4;
  3335. case 4:
  3336. if (proc->deven == DEV_RECOVER)
  3337. cHrStatsI = 3;
  3338. case 3:
  3339. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3340. {
  3341. cHrStatsI = 1;
  3342. all_off = false;
  3343. }
  3344. else
  3345. {
  3346. if (likely(proc->deven == DEV_ENABLED))
  3347. all_off = false;
  3348. if (proc->deven != DEV_RECOVER_DRV)
  3349. all_rdrv = false;
  3350. }
  3351. case 1:
  3352. break;
  3353. }
  3354. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3355. all_dead = false;
  3356. if (opt_show_procs)
  3357. break;
  3358. }
  3359. if (unlikely(all_dead))
  3360. cHrStatsI = 0;
  3361. else
  3362. if (unlikely(all_off))
  3363. cHrStatsI = 2;
  3364. cHrStats = cHrStatsOpt[cHrStatsI];
  3365. if (cHrStatsI == 2 && all_rdrv)
  3366. cHrStats = " RST ";
  3367. format_statline(buf, bufsz,
  3368. cHrStats,
  3369. aHr, uHr,
  3370. accepted, rejected, stale,
  3371. wnotaccepted, waccepted,
  3372. hwerrs,
  3373. bad_diff1, bad_diff1 + good_diff1);
  3374. }
  3375. else
  3376. #endif
  3377. {
  3378. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3379. percentf4(bnbuf, sizeof(bnbuf), bad_diff1, good_diff1);
  3380. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3381. opt_log_interval,
  3382. cHr, aHr, uHr,
  3383. accepted,
  3384. rejected,
  3385. stale,
  3386. rejpcbuf,
  3387. hwerrs,
  3388. bnbuf
  3389. );
  3390. }
  3391. }
  3392. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3393. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3394. static void text_print_status(int thr_id)
  3395. {
  3396. struct cgpu_info *cgpu;
  3397. char logline[256];
  3398. cgpu = get_thr_cgpu(thr_id);
  3399. if (cgpu) {
  3400. get_statline(logline, sizeof(logline), cgpu);
  3401. printf("%s\n", logline);
  3402. }
  3403. }
  3404. #ifdef HAVE_CURSES
  3405. static int attr_bad = A_BOLD;
  3406. #ifdef WIN32
  3407. #define swprintf snwprintf
  3408. #endif
  3409. static
  3410. void bfg_waddstr(WINDOW *win, const char *s)
  3411. {
  3412. const char *p = s;
  3413. int32_t w;
  3414. int wlen;
  3415. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3416. while (true)
  3417. {
  3418. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3419. {
  3420. // Printable ASCII
  3421. ++p;
  3422. }
  3423. if (p != s)
  3424. waddnstr(win, s, p - s);
  3425. w = utf8_decode(p, &wlen);
  3426. s = p += wlen;
  3427. switch(w)
  3428. {
  3429. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3430. case '\0':
  3431. return;
  3432. case 0xb5: // micro symbol
  3433. w = unicode_micro;
  3434. goto default_addch;
  3435. case 0xf000: // "bad" off
  3436. wattroff(win, attr_bad);
  3437. break;
  3438. case 0xf001: // "bad" on
  3439. wattron(win, attr_bad);
  3440. break;
  3441. #ifdef USE_UNICODE
  3442. case '|':
  3443. wadd_wch(win, WACS_VLINE);
  3444. break;
  3445. #endif
  3446. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3447. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3448. if (!use_unicode)
  3449. {
  3450. waddch(win, '-');
  3451. break;
  3452. }
  3453. #ifdef USE_UNICODE
  3454. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3455. break;
  3456. #endif
  3457. case 0x2022:
  3458. if (w > WCHAR_MAX || !iswprint(w))
  3459. w = '*';
  3460. default:
  3461. default_addch:
  3462. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3463. {
  3464. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3465. if (iswprint(REPLACEMENT_CHAR))
  3466. w = REPLACEMENT_CHAR;
  3467. else
  3468. #endif
  3469. w = '?';
  3470. }
  3471. {
  3472. #ifdef USE_UNICODE
  3473. wchar_t wbuf[0x10];
  3474. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3475. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3476. waddnwstr(win, wbuf, wbuflen);
  3477. #else
  3478. wprintw(win, "%lc", (wint_t)w);
  3479. #endif
  3480. }
  3481. }
  3482. }
  3483. }
  3484. static inline
  3485. void bfg_hline(WINDOW *win, int y)
  3486. {
  3487. int maxx, __maybe_unused maxy;
  3488. getmaxyx(win, maxy, maxx);
  3489. #ifdef USE_UNICODE
  3490. if (use_unicode)
  3491. mvwhline_set(win, y, 0, WACS_HLINE, maxx);
  3492. else
  3493. #endif
  3494. mvwhline(win, y, 0, '-', maxx);
  3495. }
  3496. // Spaces until end of line, using current attributes (ie, not completely clear)
  3497. static
  3498. void bfg_wspctoeol(WINDOW * const win, const int offset)
  3499. {
  3500. int x, maxx;
  3501. int __maybe_unused y;
  3502. getmaxyx(win, y, maxx);
  3503. getyx(win, y, x);
  3504. const int space_count = (maxx - x) - offset;
  3505. // Check for negative - terminal too narrow
  3506. if (space_count <= 0)
  3507. return;
  3508. char buf[space_count];
  3509. memset(buf, ' ', space_count);
  3510. waddnstr(win, buf, space_count);
  3511. }
  3512. static int menu_attr = A_REVERSE;
  3513. #define CURBUFSIZ 256
  3514. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3515. char tmp42[CURBUFSIZ]; \
  3516. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3517. wmove(win, y, x); \
  3518. bfg_waddstr(win, tmp42); \
  3519. } while (0)
  3520. #define cg_wprintw(win, fmt, ...) do { \
  3521. char tmp42[CURBUFSIZ]; \
  3522. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3523. bfg_waddstr(win, tmp42); \
  3524. } while (0)
  3525. static bool pool_unworkable(const struct pool *);
  3526. /* Must be called with curses mutex lock held and curses_active */
  3527. static void curses_print_status(const int ts)
  3528. {
  3529. struct pool *pool = currentpool;
  3530. struct timeval now, tv;
  3531. float efficiency;
  3532. double income;
  3533. int logdiv;
  3534. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3535. wattron(statuswin, attr_title);
  3536. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3537. timer_set_now(&now);
  3538. {
  3539. unsigned int days, hours;
  3540. div_t d;
  3541. timersub(&now, &miner_started, &tv);
  3542. d = div(tv.tv_sec, 86400);
  3543. days = d.quot;
  3544. d = div(d.rem, 3600);
  3545. hours = d.quot;
  3546. d = div(d.rem, 60);
  3547. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3548. , days
  3549. , (days == 1) ? ' ' : 's'
  3550. , hours
  3551. , d.quot
  3552. , d.rem
  3553. );
  3554. }
  3555. bfg_wspctoeol(statuswin, 0);
  3556. wattroff(statuswin, attr_title);
  3557. wattron(statuswin, menu_attr);
  3558. wmove(statuswin, 1, 0);
  3559. bfg_waddstr(statuswin, " [M]anage devices [P]ool management [S]ettings [D]isplay options ");
  3560. bfg_wspctoeol(statuswin, 14);
  3561. bfg_waddstr(statuswin, "[H]elp [Q]uit ");
  3562. wattroff(statuswin, menu_attr);
  3563. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && enabled_pools > 1) {
  3564. char poolinfo[20], poolinfo2[20];
  3565. int poolinfooff = 0, poolinfo2off, workable_pools = 0;
  3566. double lowdiff = DBL_MAX, highdiff = -1;
  3567. struct pool *lowdiff_pool = pools[0], *highdiff_pool = pools[0];
  3568. time_t oldest_work_restart = time(NULL) + 1;
  3569. struct pool *oldest_work_restart_pool = pools[0];
  3570. for (int i = 0; i < total_pools; ++i)
  3571. {
  3572. if (pool_unworkable(pools[i]))
  3573. continue;
  3574. // NOTE: Only set pool var when it's workable; if only one is, it gets used by single-pool code
  3575. pool = pools[i];
  3576. ++workable_pools;
  3577. if (poolinfooff < sizeof(poolinfo))
  3578. poolinfooff += snprintf(&poolinfo[poolinfooff], sizeof(poolinfo) - poolinfooff, "%u,", pool->pool_no);
  3579. struct cgminer_pool_stats * const pool_stats = &pool->cgminer_pool_stats;
  3580. if (pool_stats->last_diff < lowdiff)
  3581. {
  3582. lowdiff = pool_stats->last_diff;
  3583. lowdiff_pool = pool;
  3584. }
  3585. if (pool_stats->last_diff > highdiff)
  3586. {
  3587. highdiff = pool_stats->last_diff;
  3588. highdiff_pool = pool;
  3589. }
  3590. if (oldest_work_restart >= pool->work_restart_time)
  3591. {
  3592. oldest_work_restart = pool->work_restart_time;
  3593. oldest_work_restart_pool = pool;
  3594. }
  3595. }
  3596. if (unlikely(!workable_pools))
  3597. goto no_workable_pools;
  3598. if (workable_pools == 1)
  3599. goto one_workable_pool;
  3600. poolinfo2off = snprintf(poolinfo2, sizeof(poolinfo2), "%u (", workable_pools);
  3601. if (poolinfooff > sizeof(poolinfo2) - poolinfo2off - 1)
  3602. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s...)", (int)(sizeof(poolinfo2) - poolinfo2off - 5), poolinfo);
  3603. else
  3604. snprintf(&poolinfo2[poolinfo2off], sizeof(poolinfo2) - poolinfo2off, "%.*s)%*s", (int)(poolinfooff - 1), poolinfo, (int)(sizeof(poolinfo2)), "");
  3605. cg_mvwprintw(statuswin, 2, 0, " Pools: %s Diff:%s%s%s %c LU:%s",
  3606. poolinfo2,
  3607. lowdiff_pool->diff,
  3608. (lowdiff == highdiff) ? "" : "-",
  3609. (lowdiff == highdiff) ? "" : highdiff_pool->diff,
  3610. have_longpoll ? '+' : '-',
  3611. oldest_work_restart_pool->work_restart_timestamp);
  3612. }
  3613. else
  3614. if (pool_unworkable(pool))
  3615. {
  3616. no_workable_pools: ;
  3617. wattron(statuswin, attr_bad);
  3618. cg_mvwprintw(statuswin, 2, 0, " (all pools are dead) ");
  3619. wattroff(statuswin, attr_bad);
  3620. }
  3621. else
  3622. {
  3623. one_workable_pool: ;
  3624. char pooladdr[19];
  3625. {
  3626. const char *rawaddr = pool->sockaddr_url;
  3627. BFGINIT(rawaddr, pool->rpc_url);
  3628. size_t pooladdrlen = strlen(rawaddr);
  3629. if (pooladdrlen > 20)
  3630. snprintf(pooladdr, sizeof(pooladdr), "...%s", &rawaddr[pooladdrlen - (sizeof(pooladdr) - 4)]);
  3631. else
  3632. snprintf(pooladdr, sizeof(pooladdr), "%*s", -(int)(sizeof(pooladdr) - 1), rawaddr);
  3633. }
  3634. cg_mvwprintw(statuswin, 2, 0, " Pool%2u: %s Diff:%s %c%s LU:%s User:%s",
  3635. pool->pool_no, pooladdr, pool->diff,
  3636. have_longpoll ? '+' : '-', pool_proto_str(pool),
  3637. pool->work_restart_timestamp,
  3638. pool->rpc_user);
  3639. }
  3640. wclrtoeol(statuswin);
  3641. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3642. current_hash, block_diff, net_hashrate, blocktime);
  3643. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3644. char bwstr[(ALLOC_H2B_SHORT*2)+3+1], incomestr[ALLOC_H2B_SHORT+6+1];
  3645. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3646. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3647. ts,
  3648. total_go + total_ro,
  3649. new_blocks,
  3650. total_submitting,
  3651. multi_format_unit2(bwstr, sizeof(bwstr),
  3652. false, "B/s", H2B_SHORT, "/", 2,
  3653. (float)(total_bytes_rcvd / total_secs),
  3654. (float)(total_bytes_sent / total_secs)),
  3655. efficiency,
  3656. incomestr,
  3657. best_share);
  3658. wclrtoeol(statuswin);
  3659. mvwaddstr(statuswin, 5, 0, " ");
  3660. bfg_waddstr(statuswin, statusline);
  3661. wclrtoeol(statuswin);
  3662. logdiv = statusy - 1;
  3663. bfg_hline(statuswin, 6);
  3664. bfg_hline(statuswin, logdiv);
  3665. #ifdef USE_UNICODE
  3666. if (use_unicode)
  3667. {
  3668. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3669. if (opt_show_procs && !opt_compact)
  3670. ++offset; // proc letter
  3671. if (have_unicode_degrees)
  3672. ++offset; // degrees symbol
  3673. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3674. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3675. offset += 24; // hashrates etc
  3676. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3677. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3678. }
  3679. #endif
  3680. }
  3681. static void adj_width(int var, int *length)
  3682. {
  3683. if ((int)(log10(var) + 1) > *length)
  3684. (*length)++;
  3685. }
  3686. static int dev_width;
  3687. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3688. {
  3689. char logline[256];
  3690. int ypos;
  3691. if (opt_compact)
  3692. return;
  3693. /* Check this isn't out of the window size */
  3694. if (opt_show_procs)
  3695. ypos = cgpu->cgminer_id;
  3696. else
  3697. {
  3698. if (cgpu->proc_id)
  3699. return;
  3700. ypos = cgpu->device_line_id;
  3701. }
  3702. ypos += devsummaryYOffset;
  3703. if (ypos < 0)
  3704. return;
  3705. ypos += devcursor - 1;
  3706. if (ypos >= statusy - 1)
  3707. return;
  3708. if (wmove(statuswin, ypos, 0) == ERR)
  3709. return;
  3710. get_statline2(logline, sizeof(logline), cgpu, true);
  3711. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3712. wattron(statuswin, A_REVERSE);
  3713. bfg_waddstr(statuswin, logline);
  3714. wattroff(statuswin, A_REVERSE);
  3715. wclrtoeol(statuswin);
  3716. }
  3717. static
  3718. void _refresh_devstatus(const bool already_have_lock) {
  3719. if ((!opt_compact) && (already_have_lock || curses_active_locked())) {
  3720. int i;
  3721. if (unlikely(!total_devices))
  3722. {
  3723. const int ypos = devcursor - 1;
  3724. if (ypos < statusy - 1 && wmove(statuswin, ypos, 0) != ERR)
  3725. {
  3726. wattron(statuswin, attr_bad);
  3727. bfg_waddstr(statuswin, "NO DEVICES FOUND: Press 'M' and '+' to add");
  3728. wclrtoeol(statuswin);
  3729. wattroff(statuswin, attr_bad);
  3730. }
  3731. }
  3732. for (i = 0; i < total_devices; i++)
  3733. curses_print_devstatus(get_devices(i));
  3734. touchwin(statuswin);
  3735. wrefresh(statuswin);
  3736. if (!already_have_lock)
  3737. unlock_curses();
  3738. }
  3739. }
  3740. #define refresh_devstatus() _refresh_devstatus(false)
  3741. #endif
  3742. static void print_status(int thr_id)
  3743. {
  3744. if (!curses_active)
  3745. text_print_status(thr_id);
  3746. }
  3747. #ifdef HAVE_CURSES
  3748. static
  3749. bool set_statusy(int maxy)
  3750. {
  3751. if (loginput_size)
  3752. {
  3753. maxy -= loginput_size;
  3754. if (maxy < 0)
  3755. maxy = 0;
  3756. }
  3757. if (logstart < maxy)
  3758. maxy = logstart;
  3759. if (statusy == maxy)
  3760. return false;
  3761. statusy = maxy;
  3762. logcursor = statusy;
  3763. return true;
  3764. }
  3765. /* Check for window resize. Called with curses mutex locked */
  3766. static inline void change_logwinsize(void)
  3767. {
  3768. int x, y, logx, logy;
  3769. getmaxyx(mainwin, y, x);
  3770. if (x < 80 || y < 25)
  3771. return;
  3772. if (y > statusy + 2 && statusy < logstart) {
  3773. set_statusy(y - 2);
  3774. mvwin(logwin, logcursor, 0);
  3775. bfg_wresize(statuswin, statusy, x);
  3776. }
  3777. y -= logcursor;
  3778. getmaxyx(logwin, logy, logx);
  3779. /* Detect screen size change */
  3780. if (x != logx || y != logy)
  3781. bfg_wresize(logwin, y, x);
  3782. }
  3783. static void check_winsizes(void)
  3784. {
  3785. if (!use_curses)
  3786. return;
  3787. if (curses_active_locked()) {
  3788. int y, x;
  3789. x = getmaxx(statuswin);
  3790. if (set_statusy(LINES - 2))
  3791. {
  3792. erase();
  3793. bfg_wresize(statuswin, statusy, x);
  3794. getmaxyx(mainwin, y, x);
  3795. y -= logcursor;
  3796. bfg_wresize(logwin, y, x);
  3797. mvwin(logwin, logcursor, 0);
  3798. }
  3799. unlock_curses();
  3800. }
  3801. }
  3802. static int device_line_id_count;
  3803. static void switch_logsize(void)
  3804. {
  3805. if (curses_active_locked()) {
  3806. if (opt_compact) {
  3807. logstart = devcursor - 1;
  3808. logcursor = logstart + 1;
  3809. } else {
  3810. total_lines = (opt_show_procs ? total_devices : device_line_id_count) ?: 1;
  3811. logstart = devcursor + total_lines;
  3812. logcursor = logstart;
  3813. }
  3814. unlock_curses();
  3815. }
  3816. check_winsizes();
  3817. }
  3818. /* For mandatory printing when mutex is already locked */
  3819. void _wlog(const char *str)
  3820. {
  3821. static bool newline;
  3822. size_t end = strlen(str) - 1;
  3823. if (newline)
  3824. bfg_waddstr(logwin, "\n");
  3825. if (str[end] == '\n')
  3826. {
  3827. char *s;
  3828. newline = true;
  3829. s = alloca(end + 1);
  3830. memcpy(s, str, end);
  3831. s[end] = '\0';
  3832. str = s;
  3833. }
  3834. else
  3835. newline = false;
  3836. bfg_waddstr(logwin, str);
  3837. }
  3838. /* Mandatory printing */
  3839. void _wlogprint(const char *str)
  3840. {
  3841. if (curses_active_locked()) {
  3842. _wlog(str);
  3843. unlock_curses();
  3844. }
  3845. }
  3846. #endif
  3847. #ifdef HAVE_CURSES
  3848. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3849. {
  3850. bool high_prio;
  3851. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3852. if (curses_active)
  3853. {
  3854. if (!loginput_size || high_prio) {
  3855. wlog(" %s %s\n", datetime, str);
  3856. if (high_prio) {
  3857. touchwin(logwin);
  3858. wrefresh(logwin);
  3859. }
  3860. }
  3861. return true;
  3862. }
  3863. return false;
  3864. }
  3865. void clear_logwin(void)
  3866. {
  3867. if (curses_active_locked()) {
  3868. wclear(logwin);
  3869. unlock_curses();
  3870. }
  3871. }
  3872. void logwin_update(void)
  3873. {
  3874. if (curses_active_locked()) {
  3875. touchwin(logwin);
  3876. wrefresh(logwin);
  3877. unlock_curses();
  3878. }
  3879. }
  3880. #endif
  3881. static void enable_pool(struct pool *pool)
  3882. {
  3883. if (pool->enabled != POOL_ENABLED) {
  3884. mutex_lock(&lp_lock);
  3885. enabled_pools++;
  3886. pool->enabled = POOL_ENABLED;
  3887. pthread_cond_broadcast(&lp_cond);
  3888. mutex_unlock(&lp_lock);
  3889. }
  3890. }
  3891. #ifdef HAVE_CURSES
  3892. static void disable_pool(struct pool *pool)
  3893. {
  3894. if (pool->enabled == POOL_ENABLED)
  3895. enabled_pools--;
  3896. pool->enabled = POOL_DISABLED;
  3897. }
  3898. #endif
  3899. static void reject_pool(struct pool *pool)
  3900. {
  3901. if (pool->enabled == POOL_ENABLED)
  3902. enabled_pools--;
  3903. pool->enabled = POOL_REJECTING;
  3904. }
  3905. static double share_diff(const struct work *);
  3906. static
  3907. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3908. struct cgpu_info *cgpu;
  3909. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3910. char shrdiffdisp[ALLOC_H2B_SHORTV];
  3911. const double tgtdiff = work->work_difficulty;
  3912. char tgtdiffdisp[ALLOC_H2B_SHORTV];
  3913. char where[20];
  3914. cgpu = get_thr_cgpu(work->thr_id);
  3915. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3916. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3917. if (total_pools > 1)
  3918. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3919. else
  3920. where[0] = '\0';
  3921. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3922. disp,
  3923. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3924. cgpu->proc_repr,
  3925. where,
  3926. shrdiffdisp, tgtdiffdisp,
  3927. reason,
  3928. resubmit ? "(resubmit)" : "",
  3929. worktime
  3930. );
  3931. }
  3932. static bool test_work_current(struct work *);
  3933. static void _submit_work_async(struct work *);
  3934. static
  3935. void maybe_local_submit(const struct work *work)
  3936. {
  3937. #if BLKMAKER_VERSION > 3
  3938. if (unlikely(work->block && work->tr))
  3939. {
  3940. // This is a block with a full template (GBT)
  3941. // Regardless of the result, submit to local bitcoind(s) as well
  3942. struct work *work_cp;
  3943. for (int i = 0; i < total_pools; ++i)
  3944. {
  3945. if (!uri_get_param_bool(pools[i]->rpc_url, "allblocks", false))
  3946. continue;
  3947. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3948. work_cp = copy_work(work);
  3949. work_cp->pool = pools[i];
  3950. work_cp->do_foreign_submit = true;
  3951. _submit_work_async(work_cp);
  3952. }
  3953. }
  3954. #endif
  3955. }
  3956. /* Theoretically threads could race when modifying accepted and
  3957. * rejected values but the chance of two submits completing at the
  3958. * same time is zero so there is no point adding extra locking */
  3959. static void
  3960. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3961. /*char *hashshow,*/ bool resubmit, char *worktime)
  3962. {
  3963. struct pool *pool = work->pool;
  3964. struct cgpu_info *cgpu;
  3965. cgpu = get_thr_cgpu(work->thr_id);
  3966. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3967. mutex_lock(&stats_lock);
  3968. cgpu->accepted++;
  3969. total_accepted++;
  3970. pool->accepted++;
  3971. cgpu->diff_accepted += work->work_difficulty;
  3972. total_diff_accepted += work->work_difficulty;
  3973. pool->diff_accepted += work->work_difficulty;
  3974. mutex_unlock(&stats_lock);
  3975. pool->seq_rejects = 0;
  3976. cgpu->last_share_pool = pool->pool_no;
  3977. cgpu->last_share_pool_time = time(NULL);
  3978. cgpu->last_share_diff = work->work_difficulty;
  3979. pool->last_share_time = cgpu->last_share_pool_time;
  3980. pool->last_share_diff = work->work_difficulty;
  3981. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3982. if (!QUIET) {
  3983. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3984. }
  3985. sharelog("accept", work);
  3986. if (opt_shares && total_diff_accepted >= opt_shares) {
  3987. applog(LOG_WARNING, "Successfully mined %g accepted shares as requested and exiting.", opt_shares);
  3988. kill_work();
  3989. return;
  3990. }
  3991. /* Detect if a pool that has been temporarily disabled for
  3992. * continually rejecting shares has started accepting shares.
  3993. * This will only happen with the work returned from a
  3994. * longpoll */
  3995. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3996. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3997. enable_pool(pool);
  3998. switch_pools(NULL);
  3999. }
  4000. if (unlikely(work->block)) {
  4001. // Force moving on to this new block :)
  4002. struct work fakework;
  4003. memset(&fakework, 0, sizeof(fakework));
  4004. fakework.pool = work->pool;
  4005. // Copy block version, bits, and time from share
  4006. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  4007. memcpy(&fakework.data[68], &work->data[68], 8);
  4008. // Set prevblock to winning hash (swap32'd)
  4009. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  4010. test_work_current(&fakework);
  4011. }
  4012. } else {
  4013. mutex_lock(&stats_lock);
  4014. cgpu->rejected++;
  4015. total_rejected++;
  4016. pool->rejected++;
  4017. cgpu->diff_rejected += work->work_difficulty;
  4018. total_diff_rejected += work->work_difficulty;
  4019. pool->diff_rejected += work->work_difficulty;
  4020. pool->seq_rejects++;
  4021. mutex_unlock(&stats_lock);
  4022. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  4023. if (!QUIET) {
  4024. char where[20];
  4025. char disposition[36] = "reject";
  4026. char reason[32];
  4027. strcpy(reason, "");
  4028. if (total_pools > 1)
  4029. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  4030. else
  4031. strcpy(where, "");
  4032. if (!json_is_string(res))
  4033. res = json_object_get(val, "reject-reason");
  4034. if (res) {
  4035. const char *reasontmp = json_string_value(res);
  4036. size_t reasonLen = strlen(reasontmp);
  4037. if (reasonLen > 28)
  4038. reasonLen = 28;
  4039. reason[0] = ' '; reason[1] = '(';
  4040. memcpy(2 + reason, reasontmp, reasonLen);
  4041. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  4042. memcpy(disposition + 7, reasontmp, reasonLen);
  4043. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  4044. } else if (work->stratum && err && json_is_array(err)) {
  4045. json_t *reason_val = json_array_get(err, 1);
  4046. char *reason_str;
  4047. if (reason_val && json_is_string(reason_val)) {
  4048. reason_str = (char *)json_string_value(reason_val);
  4049. snprintf(reason, 31, " (%s)", reason_str);
  4050. }
  4051. }
  4052. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  4053. sharelog(disposition, work);
  4054. }
  4055. /* Once we have more than a nominal amount of sequential rejects,
  4056. * at least 10 and more than 3 mins at the current utility,
  4057. * disable the pool because some pool error is likely to have
  4058. * ensued. Do not do this if we know the share just happened to
  4059. * be stale due to networking delays.
  4060. */
  4061. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  4062. double utility = total_accepted / total_secs * 60;
  4063. if (pool->seq_rejects > utility * 3) {
  4064. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  4065. pool->pool_no, pool->seq_rejects);
  4066. reject_pool(pool);
  4067. if (pool == current_pool())
  4068. switch_pools(NULL);
  4069. pool->seq_rejects = 0;
  4070. }
  4071. }
  4072. }
  4073. maybe_local_submit(work);
  4074. }
  4075. static char *submit_upstream_work_request(struct work *work)
  4076. {
  4077. char *hexstr = NULL;
  4078. char *s, *sd;
  4079. struct pool *pool = work->pool;
  4080. if (work->tr)
  4081. {
  4082. blktemplate_t * const tmpl = work->tr->tmpl;
  4083. json_t *req;
  4084. unsigned char data[80];
  4085. swap32yes(data, work->data, 80 / 4);
  4086. #if BLKMAKER_VERSION > 3
  4087. if (work->do_foreign_submit)
  4088. req = blkmk_submit_foreign_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4089. else
  4090. #endif
  4091. req = blkmk_submit_jansson(tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  4092. s = json_dumps(req, 0);
  4093. json_decref(req);
  4094. sd = malloc(161);
  4095. bin2hex(sd, data, 80);
  4096. } else {
  4097. /* build hex string */
  4098. hexstr = malloc((sizeof(work->data) * 2) + 1);
  4099. bin2hex(hexstr, work->data, sizeof(work->data));
  4100. /* build JSON-RPC request */
  4101. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  4102. s = realloc_strcat(s, hexstr);
  4103. s = realloc_strcat(s, "\" ], \"id\":1}");
  4104. free(hexstr);
  4105. sd = s;
  4106. }
  4107. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  4108. if (work->tr)
  4109. free(sd);
  4110. else
  4111. s = realloc_strcat(s, "\n");
  4112. return s;
  4113. }
  4114. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  4115. json_t *res, *err;
  4116. bool rc = false;
  4117. int thr_id = work->thr_id;
  4118. struct pool *pool = work->pool;
  4119. struct timeval tv_submit_reply;
  4120. time_t ts_submit_reply;
  4121. char worktime[200] = "";
  4122. cgtime(&tv_submit_reply);
  4123. ts_submit_reply = time(NULL);
  4124. if (unlikely(!val)) {
  4125. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  4126. if (!pool_tset(pool, &pool->submit_fail)) {
  4127. total_ro++;
  4128. pool->remotefail_occasions++;
  4129. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  4130. }
  4131. goto out;
  4132. } else if (pool_tclear(pool, &pool->submit_fail))
  4133. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4134. res = json_object_get(val, "result");
  4135. err = json_object_get(val, "error");
  4136. if (!QUIET) {
  4137. if (opt_worktime) {
  4138. char workclone[20];
  4139. struct tm _tm;
  4140. struct tm *tm, tm_getwork, tm_submit_reply;
  4141. tm = &_tm;
  4142. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  4143. (struct timeval *)&(work->tv_getwork));
  4144. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  4145. (struct timeval *)&(work->tv_getwork_reply));
  4146. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  4147. (struct timeval *)&(work->tv_work_start));
  4148. double work_to_submit = tdiff(ptv_submit,
  4149. (struct timeval *)&(work->tv_work_found));
  4150. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  4151. int diffplaces = 3;
  4152. localtime_r(&work->ts_getwork, tm);
  4153. memcpy(&tm_getwork, tm, sizeof(struct tm));
  4154. localtime_r(&ts_submit_reply, tm);
  4155. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  4156. if (work->clone) {
  4157. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  4158. tdiff((struct timeval *)&(work->tv_cloned),
  4159. (struct timeval *)&(work->tv_getwork_reply)));
  4160. }
  4161. else
  4162. strcpy(workclone, "O");
  4163. if (work->work_difficulty < 1)
  4164. diffplaces = 6;
  4165. snprintf(worktime, sizeof(worktime),
  4166. " <-%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",
  4167. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  4168. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  4169. work->getwork_mode, diffplaces, work->work_difficulty,
  4170. tm_getwork.tm_hour, tm_getwork.tm_min,
  4171. tm_getwork.tm_sec, getwork_time, workclone,
  4172. getwork_to_work, work_time, work_to_submit, submit_time,
  4173. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  4174. tm_submit_reply.tm_sec);
  4175. }
  4176. }
  4177. share_result(val, res, err, work, resubmit, worktime);
  4178. if (!opt_realquiet)
  4179. print_status(thr_id);
  4180. if (!want_per_device_stats) {
  4181. char logline[256];
  4182. struct cgpu_info *cgpu;
  4183. cgpu = get_thr_cgpu(thr_id);
  4184. get_statline(logline, sizeof(logline), cgpu);
  4185. applog(LOG_INFO, "%s", logline);
  4186. }
  4187. json_decref(val);
  4188. rc = true;
  4189. out:
  4190. return rc;
  4191. }
  4192. /* Specifies whether we can use this pool for work or not. */
  4193. static bool pool_unworkable(const struct pool * const pool)
  4194. {
  4195. if (pool->idle)
  4196. return true;
  4197. if (pool->enabled != POOL_ENABLED)
  4198. return true;
  4199. if (pool->has_stratum && !pool->stratum_active)
  4200. return true;
  4201. return false;
  4202. }
  4203. static
  4204. bool pool_actively_desired(const struct pool * const pool, const struct pool *cp)
  4205. {
  4206. if (pool->enabled != POOL_ENABLED)
  4207. return false;
  4208. if (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4209. return true;
  4210. if (!cp)
  4211. cp = current_pool();
  4212. return (pool == cp);
  4213. }
  4214. static
  4215. bool pool_actively_in_use(const struct pool * const pool, const struct pool *cp)
  4216. {
  4217. return (!pool_unworkable(pool)) && pool_actively_desired(pool, cp);
  4218. }
  4219. static
  4220. bool pool_supports_block_change_notification(struct pool * const pool)
  4221. {
  4222. return pool->has_stratum || pool->lp_url;
  4223. }
  4224. static
  4225. bool pool_has_active_block_change_notification(struct pool * const pool)
  4226. {
  4227. return pool->stratum_active || pool->lp_active;
  4228. }
  4229. static struct pool *_select_longpoll_pool(struct pool *, bool(*)(struct pool *));
  4230. #define select_longpoll_pool(pool) _select_longpoll_pool(pool, pool_supports_block_change_notification)
  4231. #define pool_active_lp_pool(pool) _select_longpoll_pool(pool, pool_has_active_block_change_notification)
  4232. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  4233. * rolling average per 10 minutes and if pools start getting more, it biases
  4234. * away from them to distribute work evenly. The share count is reset to the
  4235. * rolling average every 10 minutes to not send all work to one pool after it
  4236. * has been disabled/out for an extended period. */
  4237. static struct pool *select_balanced(struct pool *cp)
  4238. {
  4239. int i, lowest = cp->shares;
  4240. struct pool *ret = cp;
  4241. for (i = 0; i < total_pools; i++) {
  4242. struct pool *pool = pools[i];
  4243. if (pool_unworkable(pool))
  4244. continue;
  4245. if (pool->shares < lowest) {
  4246. lowest = pool->shares;
  4247. ret = pool;
  4248. }
  4249. }
  4250. ret->shares++;
  4251. return ret;
  4252. }
  4253. static bool pool_active(struct pool *, bool pinging);
  4254. static void pool_died(struct pool *);
  4255. static struct pool *priority_pool(int choice);
  4256. static bool pool_unusable(struct pool *pool);
  4257. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  4258. * it has any quota left. */
  4259. static inline struct pool *select_pool(bool lagging)
  4260. {
  4261. static int rotating_pool = 0;
  4262. struct pool *pool, *cp;
  4263. bool avail = false;
  4264. int tested, i;
  4265. cp = current_pool();
  4266. retry:
  4267. if (pool_strategy == POOL_BALANCE) {
  4268. pool = select_balanced(cp);
  4269. goto out;
  4270. }
  4271. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  4272. pool = cp;
  4273. goto out;
  4274. } else
  4275. pool = NULL;
  4276. for (i = 0; i < total_pools; i++) {
  4277. struct pool *tp = pools[i];
  4278. if (tp->quota_used < tp->quota_gcd) {
  4279. avail = true;
  4280. break;
  4281. }
  4282. }
  4283. /* There are no pools with quota, so reset them. */
  4284. if (!avail) {
  4285. for (i = 0; i < total_pools; i++)
  4286. pools[i]->quota_used = 0;
  4287. if (++rotating_pool >= total_pools)
  4288. rotating_pool = 0;
  4289. }
  4290. /* Try to find the first pool in the rotation that is usable */
  4291. tested = 0;
  4292. while (!pool && tested++ < total_pools) {
  4293. pool = pools[rotating_pool];
  4294. if (pool->quota_used++ < pool->quota_gcd) {
  4295. if (!pool_unworkable(pool))
  4296. break;
  4297. /* Failover-only flag for load-balance means distribute
  4298. * unused quota to priority pool 0. */
  4299. if (opt_fail_only)
  4300. priority_pool(0)->quota_used--;
  4301. }
  4302. pool = NULL;
  4303. if (++rotating_pool >= total_pools)
  4304. rotating_pool = 0;
  4305. }
  4306. /* If there are no alive pools with quota, choose according to
  4307. * priority. */
  4308. if (!pool) {
  4309. for (i = 0; i < total_pools; i++) {
  4310. struct pool *tp = priority_pool(i);
  4311. if (!pool_unusable(tp)) {
  4312. pool = tp;
  4313. break;
  4314. }
  4315. }
  4316. }
  4317. /* If still nothing is usable, use the current pool */
  4318. if (!pool)
  4319. pool = cp;
  4320. out:
  4321. if (!pool_actively_in_use(pool, cp))
  4322. {
  4323. if (!pool_active(pool, false))
  4324. {
  4325. pool_died(pool);
  4326. goto retry;
  4327. }
  4328. pool_tclear(pool, &pool->idle);
  4329. }
  4330. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  4331. return pool;
  4332. }
  4333. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  4334. static double target_diff(const unsigned char *target)
  4335. {
  4336. double targ = 0;
  4337. signed int i;
  4338. for (i = 31; i >= 0; --i)
  4339. targ = (targ * 0x100) + target[i];
  4340. return DIFFEXACTONE / (targ ?: 1);
  4341. }
  4342. /*
  4343. * Calculate the work share difficulty
  4344. */
  4345. static void calc_diff(struct work *work, int known)
  4346. {
  4347. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  4348. double difficulty;
  4349. if (!known) {
  4350. work->work_difficulty = target_diff(work->target);
  4351. } else
  4352. work->work_difficulty = known;
  4353. difficulty = work->work_difficulty;
  4354. pool_stats->last_diff = difficulty;
  4355. suffix_string(difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  4356. if (difficulty == pool_stats->min_diff)
  4357. pool_stats->min_diff_count++;
  4358. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  4359. pool_stats->min_diff = difficulty;
  4360. pool_stats->min_diff_count = 1;
  4361. }
  4362. if (difficulty == pool_stats->max_diff)
  4363. pool_stats->max_diff_count++;
  4364. else if (difficulty > pool_stats->max_diff) {
  4365. pool_stats->max_diff = difficulty;
  4366. pool_stats->max_diff_count = 1;
  4367. }
  4368. }
  4369. static uint32_t benchmark_blkhdr[20];
  4370. static
  4371. void setup_benchmark_pool()
  4372. {
  4373. struct pool *pool;
  4374. want_longpoll = false;
  4375. // Temporarily disable opt_benchmark to avoid auto-removal
  4376. opt_benchmark = false;
  4377. pool = add_pool();
  4378. opt_benchmark = true;
  4379. pool->rpc_url = malloc(255);
  4380. strcpy(pool->rpc_url, "Benchmark");
  4381. pool_set_uri(pool, pool->rpc_url);
  4382. pool->rpc_user = pool->rpc_url;
  4383. pool->rpc_pass = pool->rpc_url;
  4384. enable_pool(pool);
  4385. pool->idle = false;
  4386. successful_connect = true;
  4387. {
  4388. uint32_t * const blkhdr = benchmark_blkhdr;
  4389. blkhdr[2] = htobe32(1);
  4390. blkhdr[17] = htobe32(0x7fffffff); // timestamp
  4391. blkhdr[18] = htobe32(0x1700ffff); // "bits"
  4392. }
  4393. {
  4394. struct stratum_work * const swork = &pool->swork;
  4395. const int branchcount = 15; // 1 MB block
  4396. const size_t branchdatasz = branchcount * 0x20;
  4397. const size_t coinbase_sz = 6 * 1024;
  4398. bytes_resize(&swork->coinbase, coinbase_sz);
  4399. memset(bytes_buf(&swork->coinbase), '\xff', coinbase_sz);
  4400. swork->nonce2_offset = 0;
  4401. bytes_resize(&swork->merkle_bin, branchdatasz);
  4402. memset(bytes_buf(&swork->merkle_bin), '\xff', branchdatasz);
  4403. swork->merkles = branchcount;
  4404. memset(swork->header1, '\xff', 36);
  4405. swork->ntime = 0x7fffffff;
  4406. timer_unset(&swork->tv_received);
  4407. memcpy(swork->diffbits, "\x17\0\xff\xff", 4);
  4408. set_target_to_pdiff(swork->target, opt_scrypt ? (1./0x10000) : 1.);
  4409. pool->nonce2sz = swork->n2size = GBT_XNONCESZ;
  4410. pool->nonce2 = 0;
  4411. }
  4412. }
  4413. void get_benchmark_work(struct work *work)
  4414. {
  4415. struct pool * const pool = pools[0];
  4416. uint32_t * const blkhdr = benchmark_blkhdr;
  4417. for (int i = 16; i >= 0; --i)
  4418. if (++blkhdr[i])
  4419. break;
  4420. memcpy(&work->data[ 0], blkhdr, 80);
  4421. memcpy(&work->data[80], workpadding_bin, 48);
  4422. calc_midstate(work);
  4423. memcpy(work->target, pool->swork.target, sizeof(work->target));
  4424. work->mandatory = true;
  4425. work->pool = pools[0];
  4426. cgtime(&work->tv_getwork);
  4427. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  4428. copy_time(&work->tv_staged, &work->tv_getwork);
  4429. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  4430. calc_diff(work, 0);
  4431. work_set_simple_ntime_roll_limit(work, 60);
  4432. }
  4433. static void wake_gws(void);
  4434. static void update_last_work(struct work *work)
  4435. {
  4436. if (!work->tr)
  4437. // Only save GBT jobs, since rollntime isn't coordinated well yet
  4438. return;
  4439. struct pool *pool = work->pool;
  4440. mutex_lock(&pool->last_work_lock);
  4441. if (pool->last_work_copy)
  4442. free_work(pool->last_work_copy);
  4443. pool->last_work_copy = copy_work(work);
  4444. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  4445. mutex_unlock(&pool->last_work_lock);
  4446. }
  4447. static
  4448. void gbt_req_target(json_t *req)
  4449. {
  4450. json_t *j;
  4451. json_t *n;
  4452. if (!request_target_str)
  4453. return;
  4454. j = json_object_get(req, "params");
  4455. if (!j)
  4456. {
  4457. n = json_array();
  4458. if (!n)
  4459. return;
  4460. if (json_object_set_new(req, "params", n))
  4461. goto erradd;
  4462. j = n;
  4463. }
  4464. n = json_array_get(j, 0);
  4465. if (!n)
  4466. {
  4467. n = json_object();
  4468. if (!n)
  4469. return;
  4470. if (json_array_append_new(j, n))
  4471. goto erradd;
  4472. }
  4473. j = n;
  4474. n = json_string(request_target_str);
  4475. if (!n)
  4476. return;
  4477. if (json_object_set_new(j, "target", n))
  4478. goto erradd;
  4479. return;
  4480. erradd:
  4481. json_decref(n);
  4482. }
  4483. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  4484. {
  4485. char *rpc_req;
  4486. clean_work(work);
  4487. switch (proto) {
  4488. case PLP_GETWORK:
  4489. work->getwork_mode = GETWORK_MODE_POOL;
  4490. return strdup(getwork_req);
  4491. case PLP_GETBLOCKTEMPLATE:
  4492. work->getwork_mode = GETWORK_MODE_GBT;
  4493. blktemplate_t * const tmpl = blktmpl_create();
  4494. if (!tmpl)
  4495. goto gbtfail2;
  4496. work->tr = tmpl_makeref(tmpl);
  4497. gbt_capabilities_t caps = blktmpl_addcaps(tmpl);
  4498. if (!caps)
  4499. goto gbtfail;
  4500. caps |= GBT_LONGPOLL;
  4501. #if BLKMAKER_VERSION > 1
  4502. if (bytes_len(&opt_coinbase_script) || have_at_least_one_getcbaddr)
  4503. caps |= GBT_CBVALUE;
  4504. #endif
  4505. json_t *req = blktmpl_request_jansson(caps, lpid);
  4506. if (!req)
  4507. goto gbtfail;
  4508. if (probe)
  4509. gbt_req_target(req);
  4510. rpc_req = json_dumps(req, 0);
  4511. if (!rpc_req)
  4512. goto gbtfail;
  4513. json_decref(req);
  4514. return rpc_req;
  4515. default:
  4516. return NULL;
  4517. }
  4518. return NULL;
  4519. gbtfail:
  4520. tmpl_decref(work->tr);
  4521. work->tr = NULL;
  4522. gbtfail2:
  4523. return NULL;
  4524. }
  4525. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4526. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4527. static const char *pool_protocol_name(enum pool_protocol proto)
  4528. {
  4529. switch (proto) {
  4530. case PLP_GETBLOCKTEMPLATE:
  4531. return "getblocktemplate";
  4532. case PLP_GETWORK:
  4533. return "getwork";
  4534. default:
  4535. return "UNKNOWN";
  4536. }
  4537. }
  4538. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4539. {
  4540. switch (proto) {
  4541. case PLP_GETBLOCKTEMPLATE:
  4542. if (want_getwork)
  4543. return PLP_GETWORK;
  4544. default:
  4545. return PLP_NONE;
  4546. }
  4547. }
  4548. static bool get_upstream_work(struct work *work, CURL *curl)
  4549. {
  4550. struct pool *pool = work->pool;
  4551. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4552. struct timeval tv_elapsed;
  4553. json_t *val = NULL;
  4554. bool rc = false;
  4555. char *url;
  4556. enum pool_protocol proto;
  4557. char *rpc_req;
  4558. if (pool->proto == PLP_NONE)
  4559. pool->proto = PLP_GETBLOCKTEMPLATE;
  4560. tryagain:
  4561. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4562. work->pool = pool;
  4563. if (!rpc_req)
  4564. return false;
  4565. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4566. url = pool->rpc_url;
  4567. cgtime(&work->tv_getwork);
  4568. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4569. false, &work->rolltime, pool, false);
  4570. pool_stats->getwork_attempts++;
  4571. free(rpc_req);
  4572. if (likely(val)) {
  4573. rc = work_decode(pool, work, val);
  4574. if (unlikely(!rc))
  4575. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4576. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4577. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4578. pool->proto = proto;
  4579. goto tryagain;
  4580. } else
  4581. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4582. cgtime(&work->tv_getwork_reply);
  4583. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4584. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4585. pool_stats->getwork_wait_rolling /= 1.63;
  4586. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4587. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4588. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4589. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4590. }
  4591. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4592. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4593. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4594. }
  4595. pool_stats->getwork_calls++;
  4596. work->pool = pool;
  4597. work->longpoll = false;
  4598. calc_diff(work, 0);
  4599. total_getworks++;
  4600. pool->getwork_requested++;
  4601. if (rc)
  4602. update_last_work(work);
  4603. if (likely(val))
  4604. json_decref(val);
  4605. return rc;
  4606. }
  4607. #ifdef HAVE_CURSES
  4608. static void disable_curses(void)
  4609. {
  4610. if (curses_active_locked()) {
  4611. use_curses = false;
  4612. curses_active = false;
  4613. leaveok(logwin, false);
  4614. leaveok(statuswin, false);
  4615. leaveok(mainwin, false);
  4616. nocbreak();
  4617. echo();
  4618. delwin(logwin);
  4619. delwin(statuswin);
  4620. delwin(mainwin);
  4621. endwin();
  4622. #ifdef WIN32
  4623. // Move the cursor to after curses output.
  4624. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4625. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4626. COORD coord;
  4627. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4628. coord.X = 0;
  4629. coord.Y = csbi.dwSize.Y - 1;
  4630. SetConsoleCursorPosition(hout, coord);
  4631. }
  4632. #endif
  4633. unlock_curses();
  4634. }
  4635. }
  4636. #endif
  4637. static void __kill_work(void)
  4638. {
  4639. struct cgpu_info *cgpu;
  4640. struct thr_info *thr;
  4641. int i;
  4642. if (!successful_connect)
  4643. return;
  4644. applog(LOG_INFO, "Received kill message");
  4645. shutting_down = true;
  4646. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4647. notifier_wake(submit_waiting_notifier);
  4648. #ifdef USE_LIBMICROHTTPD
  4649. httpsrv_stop();
  4650. #endif
  4651. applog(LOG_DEBUG, "Killing off watchpool thread");
  4652. /* Kill the watchpool thread */
  4653. thr = &control_thr[watchpool_thr_id];
  4654. thr_info_cancel(thr);
  4655. applog(LOG_DEBUG, "Killing off watchdog thread");
  4656. /* Kill the watchdog thread */
  4657. thr = &control_thr[watchdog_thr_id];
  4658. thr_info_cancel(thr);
  4659. applog(LOG_DEBUG, "Shutting down mining threads");
  4660. for (i = 0; i < mining_threads; i++) {
  4661. thr = get_thread(i);
  4662. if (!thr)
  4663. continue;
  4664. cgpu = thr->cgpu;
  4665. if (!cgpu)
  4666. continue;
  4667. if (!cgpu->threads)
  4668. continue;
  4669. cgpu->shutdown = true;
  4670. thr->work_restart = true;
  4671. notifier_wake(thr->notifier);
  4672. notifier_wake(thr->work_restart_notifier);
  4673. }
  4674. sleep(1);
  4675. applog(LOG_DEBUG, "Killing off mining threads");
  4676. /* Kill the mining threads*/
  4677. for (i = 0; i < mining_threads; i++) {
  4678. thr = get_thread(i);
  4679. if (!thr)
  4680. continue;
  4681. cgpu = thr->cgpu;
  4682. if (cgpu->threads)
  4683. {
  4684. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4685. thr_info_cancel(thr);
  4686. }
  4687. cgpu->status = LIFE_DEAD2;
  4688. }
  4689. /* Stop the others */
  4690. applog(LOG_DEBUG, "Killing off API thread");
  4691. thr = &control_thr[api_thr_id];
  4692. thr_info_cancel(thr);
  4693. }
  4694. /* This should be the common exit path */
  4695. void kill_work(void)
  4696. {
  4697. __kill_work();
  4698. quit(0, "Shutdown signal received.");
  4699. }
  4700. static
  4701. #ifdef WIN32
  4702. #ifndef _WIN64
  4703. const
  4704. #endif
  4705. #endif
  4706. char **initial_args;
  4707. void _bfg_clean_up(bool);
  4708. void app_restart(void)
  4709. {
  4710. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4711. __kill_work();
  4712. _bfg_clean_up(true);
  4713. #if defined(unix) || defined(__APPLE__)
  4714. if (forkpid > 0) {
  4715. kill(forkpid, SIGTERM);
  4716. forkpid = 0;
  4717. }
  4718. #endif
  4719. execv(initial_args[0], initial_args);
  4720. applog(LOG_WARNING, "Failed to restart application");
  4721. }
  4722. static void sighandler(int __maybe_unused sig)
  4723. {
  4724. /* Restore signal handlers so we can still quit if kill_work fails */
  4725. sigaction(SIGTERM, &termhandler, NULL);
  4726. sigaction(SIGINT, &inthandler, NULL);
  4727. kill_work();
  4728. }
  4729. static void start_longpoll(void);
  4730. static void stop_longpoll(void);
  4731. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4732. * this pool. */
  4733. static void recruit_curl(struct pool *pool)
  4734. {
  4735. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4736. if (unlikely(!ce))
  4737. quit(1, "Failed to calloc in recruit_curl");
  4738. ce->curl = curl_easy_init();
  4739. if (unlikely(!ce->curl))
  4740. quit(1, "Failed to init in recruit_curl");
  4741. LL_PREPEND(pool->curllist, ce);
  4742. pool->curls++;
  4743. }
  4744. /* Grab an available curl if there is one. If not, then recruit extra curls
  4745. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4746. * and there are already 5 curls in circulation. Limit total number to the
  4747. * number of mining threads per pool as well to prevent blasting a pool during
  4748. * network delays/outages. */
  4749. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4750. {
  4751. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4752. bool recruited = false;
  4753. struct curl_ent *ce;
  4754. mutex_lock(&pool->pool_lock);
  4755. retry:
  4756. if (!pool->curls) {
  4757. recruit_curl(pool);
  4758. recruited = true;
  4759. } else if (!pool->curllist) {
  4760. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4761. if (!blocking) {
  4762. mutex_unlock(&pool->pool_lock);
  4763. return NULL;
  4764. }
  4765. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4766. goto retry;
  4767. } else {
  4768. recruit_curl(pool);
  4769. recruited = true;
  4770. }
  4771. }
  4772. ce = pool->curllist;
  4773. LL_DELETE(pool->curllist, ce);
  4774. mutex_unlock(&pool->pool_lock);
  4775. if (recruited)
  4776. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4777. return ce;
  4778. }
  4779. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4780. {
  4781. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4782. }
  4783. __maybe_unused
  4784. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4785. {
  4786. return pop_curl_entry3(pool, 1);
  4787. }
  4788. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4789. {
  4790. mutex_lock(&pool->pool_lock);
  4791. if (!ce || !ce->curl)
  4792. quithere(1, "Attempted to add NULL");
  4793. LL_PREPEND(pool->curllist, ce);
  4794. cgtime(&ce->tv);
  4795. pthread_cond_broadcast(&pool->cr_cond);
  4796. mutex_unlock(&pool->pool_lock);
  4797. }
  4798. bool stale_work(struct work *work, bool share);
  4799. static inline bool should_roll(struct work *work)
  4800. {
  4801. struct timeval now;
  4802. time_t expiry;
  4803. if (!pool_actively_in_use(work->pool, NULL))
  4804. return false;
  4805. if (stale_work(work, false))
  4806. return false;
  4807. if (work->rolltime > opt_scantime)
  4808. expiry = work->rolltime;
  4809. else
  4810. expiry = opt_scantime;
  4811. expiry = expiry * 2 / 3;
  4812. /* We shouldn't roll if we're unlikely to get one shares' duration
  4813. * work out of doing so */
  4814. cgtime(&now);
  4815. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4816. return false;
  4817. return true;
  4818. }
  4819. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4820. * reject blocks as invalid. */
  4821. static inline bool can_roll(struct work *work)
  4822. {
  4823. if (work->stratum)
  4824. return false;
  4825. if (!(work->pool && !work->clone))
  4826. return false;
  4827. if (work->tr)
  4828. {
  4829. if (stale_work(work, false))
  4830. return false;
  4831. return blkmk_work_left(work->tr->tmpl);
  4832. }
  4833. return (work->rolltime &&
  4834. work->rolls < 7000 && !stale_work(work, false));
  4835. }
  4836. static void roll_work(struct work *work)
  4837. {
  4838. if (work->tr)
  4839. {
  4840. struct timeval tv_now;
  4841. cgtime(&tv_now);
  4842. if (blkmk_get_data(work->tr->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4843. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4844. swap32yes(work->data, work->data, 80 / 4);
  4845. calc_midstate(work);
  4846. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4847. } else {
  4848. uint32_t *work_ntime;
  4849. uint32_t ntime;
  4850. work_ntime = (uint32_t *)(work->data + 68);
  4851. ntime = be32toh(*work_ntime);
  4852. ntime++;
  4853. *work_ntime = htobe32(ntime);
  4854. work_set_simple_ntime_roll_limit(work, 0);
  4855. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4856. }
  4857. local_work++;
  4858. work->rolls++;
  4859. work->blk.nonce = 0;
  4860. /* This is now a different work item so it needs a different ID for the
  4861. * hashtable */
  4862. work->id = total_work++;
  4863. }
  4864. /* Duplicates any dynamically allocated arrays within the work struct to
  4865. * prevent a copied work struct from freeing ram belonging to another struct */
  4866. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4867. {
  4868. int id = work->id;
  4869. clean_work(work);
  4870. memcpy(work, base_work, sizeof(struct work));
  4871. /* Keep the unique new id assigned during make_work to prevent copied
  4872. * work from having the same id. */
  4873. work->id = id;
  4874. if (base_work->job_id)
  4875. work->job_id = strdup(base_work->job_id);
  4876. if (base_work->nonce1)
  4877. work->nonce1 = strdup(base_work->nonce1);
  4878. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4879. if (base_work->tr)
  4880. tmpl_incref(base_work->tr);
  4881. if (noffset)
  4882. {
  4883. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4884. uint32_t ntime = be32toh(*work_ntime);
  4885. ntime += noffset;
  4886. *work_ntime = htobe32(ntime);
  4887. }
  4888. if (work->device_data_dup_func)
  4889. work->device_data = work->device_data_dup_func(work);
  4890. }
  4891. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4892. * for all dynamically allocated arrays within the struct */
  4893. struct work *copy_work(const struct work *base_work)
  4894. {
  4895. struct work *work = make_work();
  4896. _copy_work(work, base_work, 0);
  4897. return work;
  4898. }
  4899. void __copy_work(struct work *work, const struct work *base_work)
  4900. {
  4901. _copy_work(work, base_work, 0);
  4902. }
  4903. static struct work *make_clone(struct work *work)
  4904. {
  4905. struct work *work_clone = copy_work(work);
  4906. work_clone->clone = true;
  4907. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4908. work_clone->longpoll = false;
  4909. work_clone->mandatory = false;
  4910. /* Make cloned work appear slightly older to bias towards keeping the
  4911. * master work item which can be further rolled */
  4912. work_clone->tv_staged.tv_sec -= 1;
  4913. return work_clone;
  4914. }
  4915. static void stage_work(struct work *work);
  4916. static bool clone_available(void)
  4917. {
  4918. struct work *work_clone = NULL, *work, *tmp;
  4919. bool cloned = false;
  4920. mutex_lock(stgd_lock);
  4921. if (!staged_rollable)
  4922. goto out_unlock;
  4923. HASH_ITER(hh, staged_work, work, tmp) {
  4924. if (can_roll(work) && should_roll(work)) {
  4925. roll_work(work);
  4926. work_clone = make_clone(work);
  4927. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4928. roll_work(work);
  4929. cloned = true;
  4930. break;
  4931. }
  4932. }
  4933. out_unlock:
  4934. mutex_unlock(stgd_lock);
  4935. if (cloned) {
  4936. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4937. stage_work(work_clone);
  4938. }
  4939. return cloned;
  4940. }
  4941. static void pool_died(struct pool *pool)
  4942. {
  4943. mutex_lock(&lp_lock);
  4944. if (!pool_tset(pool, &pool->idle)) {
  4945. cgtime(&pool->tv_idle);
  4946. pthread_cond_broadcast(&lp_cond);
  4947. mutex_unlock(&lp_lock);
  4948. if (pool == current_pool()) {
  4949. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4950. switch_pools(NULL);
  4951. } else
  4952. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4953. }
  4954. else
  4955. mutex_unlock(&lp_lock);
  4956. }
  4957. bool stale_work(struct work *work, bool share)
  4958. {
  4959. unsigned work_expiry;
  4960. struct pool *pool;
  4961. uint32_t block_id;
  4962. unsigned getwork_delay;
  4963. if (opt_benchmark)
  4964. return false;
  4965. block_id = ((uint32_t*)work->data)[1];
  4966. pool = work->pool;
  4967. /* Technically the rolltime should be correct but some pools
  4968. * advertise a broken expire= that is lower than a meaningful
  4969. * scantime */
  4970. if (work->rolltime >= opt_scantime || work->tr)
  4971. work_expiry = work->rolltime;
  4972. else
  4973. work_expiry = opt_expiry;
  4974. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4975. if (work_expiry > max_expiry)
  4976. work_expiry = max_expiry;
  4977. if (share) {
  4978. /* If the share isn't on this pool's latest block, it's stale */
  4979. if (pool->block_id && pool->block_id != block_id)
  4980. {
  4981. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4982. return true;
  4983. }
  4984. /* If the pool doesn't want old shares, then any found in work before
  4985. * the most recent longpoll is stale */
  4986. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4987. {
  4988. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4989. return true;
  4990. }
  4991. } else {
  4992. /* If this work isn't for the latest Bitcoin block, it's stale */
  4993. /* But only care about the current pool if failover-only */
  4994. if (enabled_pools <= 1 || opt_fail_only) {
  4995. if (pool->block_id && block_id != pool->block_id)
  4996. {
  4997. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4998. return true;
  4999. }
  5000. } else {
  5001. if (block_id != current_block_id)
  5002. {
  5003. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  5004. return true;
  5005. }
  5006. }
  5007. /* If the pool has asked us to restart since this work, it's stale */
  5008. if (work->work_restart_id != pool->work_restart_id)
  5009. {
  5010. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  5011. return true;
  5012. }
  5013. if (pool->has_stratum && work->job_id) {
  5014. bool same_job;
  5015. if (!pool->stratum_active || !pool->stratum_notify) {
  5016. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  5017. return true;
  5018. }
  5019. same_job = true;
  5020. cg_rlock(&pool->data_lock);
  5021. if (strcmp(work->job_id, pool->swork.job_id))
  5022. same_job = false;
  5023. cg_runlock(&pool->data_lock);
  5024. if (!same_job) {
  5025. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  5026. return true;
  5027. }
  5028. }
  5029. /* Factor in the average getwork delay of this pool, rounding it up to
  5030. * the nearest second */
  5031. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  5032. if (unlikely(work_expiry <= getwork_delay + 5))
  5033. work_expiry = 5;
  5034. else
  5035. work_expiry -= getwork_delay;
  5036. }
  5037. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  5038. if (elapsed_since_staged > work_expiry) {
  5039. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  5040. return true;
  5041. }
  5042. /* If the user only wants strict failover, any work from a pool other than
  5043. * the current one is always considered stale */
  5044. if (opt_fail_only && !share && !work->mandatory && !pool_actively_in_use(pool, NULL))
  5045. {
  5046. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  5047. return true;
  5048. }
  5049. return false;
  5050. }
  5051. static double share_diff(const struct work *work)
  5052. {
  5053. double ret;
  5054. bool new_best = false;
  5055. ret = target_diff(work->hash);
  5056. cg_wlock(&control_lock);
  5057. if (unlikely(ret > best_diff)) {
  5058. new_best = true;
  5059. best_diff = ret;
  5060. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5061. }
  5062. if (unlikely(ret > work->pool->best_diff))
  5063. work->pool->best_diff = ret;
  5064. cg_wunlock(&control_lock);
  5065. if (unlikely(new_best))
  5066. applog(LOG_INFO, "New best share: %s", best_share);
  5067. return ret;
  5068. }
  5069. static
  5070. void work_check_for_block(struct work * const work)
  5071. {
  5072. work->share_diff = share_diff(work);
  5073. if (unlikely(work->share_diff >= current_diff)) {
  5074. work->block = true;
  5075. work->pool->solved++;
  5076. found_blocks++;
  5077. work->mandatory = true;
  5078. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  5079. refresh_bitcoind_address(true);
  5080. }
  5081. }
  5082. static void submit_discard_share2(const char *reason, struct work *work)
  5083. {
  5084. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  5085. sharelog(reason, work);
  5086. mutex_lock(&stats_lock);
  5087. ++total_stale;
  5088. ++cgpu->stale;
  5089. ++(work->pool->stale_shares);
  5090. total_diff_stale += work->work_difficulty;
  5091. cgpu->diff_stale += work->work_difficulty;
  5092. work->pool->diff_stale += work->work_difficulty;
  5093. mutex_unlock(&stats_lock);
  5094. }
  5095. static void submit_discard_share(struct work *work)
  5096. {
  5097. submit_discard_share2("discard", work);
  5098. }
  5099. struct submit_work_state {
  5100. struct work *work;
  5101. bool resubmit;
  5102. struct curl_ent *ce;
  5103. int failures;
  5104. struct timeval tv_staleexpire;
  5105. char *s;
  5106. struct timeval tv_submit;
  5107. struct submit_work_state *next;
  5108. };
  5109. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  5110. {
  5111. long *p_timeout_us = userp;
  5112. const long max_ms = LONG_MAX / 1000;
  5113. if (max_ms < timeout_ms)
  5114. timeout_ms = max_ms;
  5115. *p_timeout_us = timeout_ms * 1000;
  5116. return 0;
  5117. }
  5118. static void sws_has_ce(struct submit_work_state *sws)
  5119. {
  5120. struct pool *pool = sws->work->pool;
  5121. sws->s = submit_upstream_work_request(sws->work);
  5122. cgtime(&sws->tv_submit);
  5123. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5124. }
  5125. static struct submit_work_state *begin_submission(struct work *work)
  5126. {
  5127. struct pool *pool;
  5128. struct submit_work_state *sws = NULL;
  5129. pool = work->pool;
  5130. sws = malloc(sizeof(*sws));
  5131. *sws = (struct submit_work_state){
  5132. .work = work,
  5133. };
  5134. work_check_for_block(work);
  5135. if (stale_work(work, true)) {
  5136. work->stale = true;
  5137. if (opt_submit_stale)
  5138. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  5139. else if (pool->submit_old)
  5140. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  5141. else {
  5142. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  5143. submit_discard_share(work);
  5144. goto out;
  5145. }
  5146. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5147. }
  5148. if (work->stratum) {
  5149. char *s;
  5150. s = malloc(1024);
  5151. sws->s = s;
  5152. } else {
  5153. /* submit solution to bitcoin via JSON-RPC */
  5154. sws->ce = pop_curl_entry2(pool, false);
  5155. if (sws->ce) {
  5156. sws_has_ce(sws);
  5157. } else {
  5158. sws->next = pool->sws_waiting_on_curl;
  5159. pool->sws_waiting_on_curl = sws;
  5160. if (sws->next)
  5161. applog(LOG_DEBUG, "submit_thread queuing submission");
  5162. else
  5163. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  5164. }
  5165. }
  5166. return sws;
  5167. out:
  5168. free(sws);
  5169. return NULL;
  5170. }
  5171. static bool retry_submission(struct submit_work_state *sws)
  5172. {
  5173. struct work *work = sws->work;
  5174. struct pool *pool = work->pool;
  5175. sws->resubmit = true;
  5176. if ((!work->stale) && stale_work(work, true)) {
  5177. work->stale = true;
  5178. if (opt_submit_stale)
  5179. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  5180. else if (pool->submit_old)
  5181. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  5182. else {
  5183. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  5184. submit_discard_share(work);
  5185. return false;
  5186. }
  5187. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  5188. }
  5189. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  5190. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  5191. submit_discard_share(work);
  5192. return false;
  5193. }
  5194. else if (work->stale) {
  5195. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  5196. {
  5197. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  5198. submit_discard_share(work);
  5199. return false;
  5200. }
  5201. }
  5202. /* pause, then restart work-request loop */
  5203. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  5204. cgtime(&sws->tv_submit);
  5205. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  5206. return true;
  5207. }
  5208. static void free_sws(struct submit_work_state *sws)
  5209. {
  5210. free(sws->s);
  5211. free_work(sws->work);
  5212. free(sws);
  5213. }
  5214. static void *submit_work_thread(__maybe_unused void *userdata)
  5215. {
  5216. int wip = 0;
  5217. CURLM *curlm;
  5218. long curlm_timeout_us = -1;
  5219. struct timeval curlm_timer;
  5220. struct submit_work_state *sws, **swsp;
  5221. struct submit_work_state *write_sws = NULL;
  5222. unsigned tsreduce = 0;
  5223. pthread_detach(pthread_self());
  5224. RenameThread("submit_work");
  5225. applog(LOG_DEBUG, "Creating extra submit work thread");
  5226. curlm = curl_multi_init();
  5227. curlm_timeout_us = -1;
  5228. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  5229. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  5230. fd_set rfds, wfds, efds;
  5231. int maxfd;
  5232. struct timeval tv_timeout, tv_now;
  5233. int n;
  5234. CURLMsg *cm;
  5235. FD_ZERO(&rfds);
  5236. while (1) {
  5237. mutex_lock(&submitting_lock);
  5238. total_submitting -= tsreduce;
  5239. tsreduce = 0;
  5240. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  5241. notifier_read(submit_waiting_notifier);
  5242. }
  5243. // Receive any new submissions
  5244. while (submit_waiting) {
  5245. struct work *work = submit_waiting;
  5246. DL_DELETE(submit_waiting, work);
  5247. if ( (sws = begin_submission(work)) ) {
  5248. if (sws->ce)
  5249. curl_multi_add_handle(curlm, sws->ce->curl);
  5250. else if (sws->s) {
  5251. sws->next = write_sws;
  5252. write_sws = sws;
  5253. }
  5254. ++wip;
  5255. }
  5256. else {
  5257. --total_submitting;
  5258. free_work(work);
  5259. }
  5260. }
  5261. if (unlikely(shutting_down && !wip))
  5262. break;
  5263. mutex_unlock(&submitting_lock);
  5264. FD_ZERO(&rfds);
  5265. FD_ZERO(&wfds);
  5266. FD_ZERO(&efds);
  5267. tv_timeout.tv_sec = -1;
  5268. // Setup cURL with select
  5269. // Need to call perform to ensure the timeout gets updated
  5270. curl_multi_perform(curlm, &n);
  5271. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  5272. if (curlm_timeout_us >= 0)
  5273. {
  5274. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  5275. reduce_timeout_to(&tv_timeout, &curlm_timer);
  5276. }
  5277. // Setup waiting stratum submissions with select
  5278. for (sws = write_sws; sws; sws = sws->next)
  5279. {
  5280. struct pool *pool = sws->work->pool;
  5281. int fd = pool->sock;
  5282. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  5283. continue;
  5284. FD_SET(fd, &wfds);
  5285. set_maxfd(&maxfd, fd);
  5286. }
  5287. // Setup "submit waiting" notifier with select
  5288. FD_SET(submit_waiting_notifier[0], &rfds);
  5289. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  5290. // Wait for something interesting to happen :)
  5291. cgtime(&tv_now);
  5292. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  5293. FD_ZERO(&rfds);
  5294. continue;
  5295. }
  5296. // Handle any stratum ready-to-write results
  5297. for (swsp = &write_sws; (sws = *swsp); ) {
  5298. struct work *work = sws->work;
  5299. struct pool *pool = work->pool;
  5300. int fd = pool->sock;
  5301. bool sessionid_match;
  5302. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  5303. next_write_sws:
  5304. // TODO: Check if stale, possibly discard etc
  5305. swsp = &sws->next;
  5306. continue;
  5307. }
  5308. cg_rlock(&pool->data_lock);
  5309. // 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
  5310. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  5311. sessionid_match = (!pool->swork.nonce1) || !strcmp(work->nonce1, pool->swork.nonce1);
  5312. cg_runlock(&pool->data_lock);
  5313. if (!sessionid_match)
  5314. {
  5315. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5316. submit_discard_share2("disconnect", work);
  5317. ++tsreduce;
  5318. next_write_sws_del:
  5319. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  5320. FD_CLR(fd, &wfds);
  5321. // Delete sws for this submission, since we're done with it
  5322. *swsp = sws->next;
  5323. free_sws(sws);
  5324. --wip;
  5325. continue;
  5326. }
  5327. char *s = sws->s;
  5328. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  5329. int sshare_id;
  5330. uint32_t nonce;
  5331. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  5332. char noncehex[9];
  5333. char ntimehex[9];
  5334. sshare->work = copy_work(work);
  5335. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  5336. nonce = *((uint32_t *)(work->data + 76));
  5337. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5338. bin2hex(ntimehex, (void *)&work->data[68], 4);
  5339. mutex_lock(&sshare_lock);
  5340. /* Give the stratum share a unique id */
  5341. sshare_id =
  5342. sshare->id = swork_id++;
  5343. HASH_ADD_INT(stratum_shares, id, sshare);
  5344. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5345. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  5346. mutex_unlock(&sshare_lock);
  5347. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  5348. if (likely(stratum_send(pool, s, strlen(s)))) {
  5349. if (pool_tclear(pool, &pool->submit_fail))
  5350. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5351. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5352. goto next_write_sws_del;
  5353. } else if (!pool_tset(pool, &pool->submit_fail)) {
  5354. // Undo stuff
  5355. mutex_lock(&sshare_lock);
  5356. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  5357. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  5358. if (sshare)
  5359. HASH_DEL(stratum_shares, sshare);
  5360. mutex_unlock(&sshare_lock);
  5361. if (sshare)
  5362. {
  5363. free_work(sshare->work);
  5364. free(sshare);
  5365. }
  5366. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5367. total_ro++;
  5368. pool->remotefail_occasions++;
  5369. if (!sshare)
  5370. goto next_write_sws_del;
  5371. goto next_write_sws;
  5372. }
  5373. }
  5374. // Handle any cURL activities
  5375. curl_multi_perform(curlm, &n);
  5376. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  5377. if (cm->msg == CURLMSG_DONE)
  5378. {
  5379. bool finished;
  5380. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  5381. curl_multi_remove_handle(curlm, cm->easy_handle);
  5382. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  5383. if (!finished) {
  5384. if (retry_submission(sws))
  5385. curl_multi_add_handle(curlm, sws->ce->curl);
  5386. else
  5387. finished = true;
  5388. }
  5389. if (finished) {
  5390. --wip;
  5391. ++tsreduce;
  5392. struct pool *pool = sws->work->pool;
  5393. if (pool->sws_waiting_on_curl) {
  5394. pool->sws_waiting_on_curl->ce = sws->ce;
  5395. sws_has_ce(pool->sws_waiting_on_curl);
  5396. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  5397. curl_multi_add_handle(curlm, sws->ce->curl);
  5398. } else {
  5399. push_curl_entry(sws->ce, sws->work->pool);
  5400. }
  5401. free_sws(sws);
  5402. }
  5403. }
  5404. }
  5405. }
  5406. assert(!write_sws);
  5407. mutex_unlock(&submitting_lock);
  5408. curl_multi_cleanup(curlm);
  5409. applog(LOG_DEBUG, "submit_work thread exiting");
  5410. return NULL;
  5411. }
  5412. /* Find the pool that currently has the highest priority */
  5413. static struct pool *priority_pool(int choice)
  5414. {
  5415. struct pool *ret = NULL;
  5416. int i;
  5417. for (i = 0; i < total_pools; i++) {
  5418. struct pool *pool = pools[i];
  5419. if (pool->prio == choice) {
  5420. ret = pool;
  5421. break;
  5422. }
  5423. }
  5424. if (unlikely(!ret)) {
  5425. applog(LOG_ERR, "WTF No pool %d found!", choice);
  5426. return pools[choice];
  5427. }
  5428. return ret;
  5429. }
  5430. int prioritize_pools(char *param, int *pid)
  5431. {
  5432. char *ptr, *next;
  5433. int i, pr, prio = 0;
  5434. if (total_pools == 0) {
  5435. return MSG_NOPOOL;
  5436. }
  5437. if (param == NULL || *param == '\0') {
  5438. return MSG_MISPID;
  5439. }
  5440. bool pools_changed[total_pools];
  5441. int new_prio[total_pools];
  5442. for (i = 0; i < total_pools; ++i)
  5443. pools_changed[i] = false;
  5444. next = param;
  5445. while (next && *next) {
  5446. ptr = next;
  5447. next = strchr(ptr, ',');
  5448. if (next)
  5449. *(next++) = '\0';
  5450. i = atoi(ptr);
  5451. if (i < 0 || i >= total_pools) {
  5452. *pid = i;
  5453. return MSG_INVPID;
  5454. }
  5455. if (pools_changed[i]) {
  5456. *pid = i;
  5457. return MSG_DUPPID;
  5458. }
  5459. pools_changed[i] = true;
  5460. new_prio[i] = prio++;
  5461. }
  5462. // Only change them if no errors
  5463. for (i = 0; i < total_pools; i++) {
  5464. if (pools_changed[i])
  5465. pools[i]->prio = new_prio[i];
  5466. }
  5467. // In priority order, cycle through the unchanged pools and append them
  5468. for (pr = 0; pr < total_pools; pr++)
  5469. for (i = 0; i < total_pools; i++) {
  5470. if (!pools_changed[i] && pools[i]->prio == pr) {
  5471. pools[i]->prio = prio++;
  5472. pools_changed[i] = true;
  5473. break;
  5474. }
  5475. }
  5476. if (current_pool()->prio)
  5477. switch_pools(NULL);
  5478. return MSG_POOLPRIO;
  5479. }
  5480. void validate_pool_priorities(void)
  5481. {
  5482. // TODO: this should probably do some sort of logging
  5483. int i, j;
  5484. bool used[total_pools];
  5485. bool valid[total_pools];
  5486. for (i = 0; i < total_pools; i++)
  5487. used[i] = valid[i] = false;
  5488. for (i = 0; i < total_pools; i++) {
  5489. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  5490. if (!used[pools[i]->prio]) {
  5491. valid[i] = true;
  5492. used[pools[i]->prio] = true;
  5493. }
  5494. }
  5495. }
  5496. for (i = 0; i < total_pools; i++) {
  5497. if (!valid[i]) {
  5498. for (j = 0; j < total_pools; j++) {
  5499. if (!used[j]) {
  5500. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  5501. pools[i]->prio = j;
  5502. used[j] = true;
  5503. break;
  5504. }
  5505. }
  5506. }
  5507. }
  5508. }
  5509. static void clear_pool_work(struct pool *pool);
  5510. /* Specifies whether we can switch to this pool or not. */
  5511. static bool pool_unusable(struct pool *pool)
  5512. {
  5513. if (pool->idle)
  5514. return true;
  5515. if (pool->enabled != POOL_ENABLED)
  5516. return true;
  5517. return false;
  5518. }
  5519. void switch_pools(struct pool *selected)
  5520. {
  5521. struct pool *pool, *last_pool;
  5522. int i, pool_no, next_pool;
  5523. cg_wlock(&control_lock);
  5524. last_pool = currentpool;
  5525. pool_no = currentpool->pool_no;
  5526. /* Switch selected to pool number 0 and move the rest down */
  5527. if (selected) {
  5528. if (selected->prio != 0) {
  5529. for (i = 0; i < total_pools; i++) {
  5530. pool = pools[i];
  5531. if (pool->prio < selected->prio)
  5532. pool->prio++;
  5533. }
  5534. selected->prio = 0;
  5535. }
  5536. }
  5537. switch (pool_strategy) {
  5538. /* All of these set to the master pool */
  5539. case POOL_BALANCE:
  5540. case POOL_FAILOVER:
  5541. case POOL_LOADBALANCE:
  5542. for (i = 0; i < total_pools; i++) {
  5543. pool = priority_pool(i);
  5544. if (pool_unusable(pool))
  5545. continue;
  5546. pool_no = pool->pool_no;
  5547. break;
  5548. }
  5549. break;
  5550. /* Both of these simply increment and cycle */
  5551. case POOL_ROUNDROBIN:
  5552. case POOL_ROTATE:
  5553. if (selected && !selected->idle) {
  5554. pool_no = selected->pool_no;
  5555. break;
  5556. }
  5557. next_pool = pool_no;
  5558. /* Select the next alive pool */
  5559. for (i = 1; i < total_pools; i++) {
  5560. next_pool++;
  5561. if (next_pool >= total_pools)
  5562. next_pool = 0;
  5563. pool = pools[next_pool];
  5564. if (pool_unusable(pool))
  5565. continue;
  5566. pool_no = next_pool;
  5567. break;
  5568. }
  5569. break;
  5570. default:
  5571. break;
  5572. }
  5573. currentpool = pools[pool_no];
  5574. pool = currentpool;
  5575. mutex_lock(&lp_lock);
  5576. pthread_cond_broadcast(&lp_cond);
  5577. mutex_unlock(&lp_lock);
  5578. cg_wunlock(&control_lock);
  5579. /* Set the lagging flag to avoid pool not providing work fast enough
  5580. * messages in failover only mode since we have to get all fresh work
  5581. * as in restart_threads */
  5582. if (opt_fail_only)
  5583. pool_tset(pool, &pool->lagging);
  5584. if (pool != last_pool)
  5585. {
  5586. pool->block_id = 0;
  5587. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5588. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5589. if (pool_localgen(pool) || opt_fail_only)
  5590. clear_pool_work(last_pool);
  5591. }
  5592. }
  5593. mutex_lock(&lp_lock);
  5594. pthread_cond_broadcast(&lp_cond);
  5595. mutex_unlock(&lp_lock);
  5596. }
  5597. static void discard_work(struct work *work)
  5598. {
  5599. if (!work->clone && !work->rolls && !work->mined) {
  5600. if (work->pool) {
  5601. work->pool->discarded_work++;
  5602. work->pool->quota_used--;
  5603. work->pool->works--;
  5604. }
  5605. total_discarded++;
  5606. applog(LOG_DEBUG, "Discarded work");
  5607. } else
  5608. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5609. free_work(work);
  5610. }
  5611. static void wake_gws(void)
  5612. {
  5613. mutex_lock(stgd_lock);
  5614. pthread_cond_signal(&gws_cond);
  5615. mutex_unlock(stgd_lock);
  5616. }
  5617. static void discard_stale(void)
  5618. {
  5619. struct work *work, *tmp;
  5620. int stale = 0;
  5621. mutex_lock(stgd_lock);
  5622. HASH_ITER(hh, staged_work, work, tmp) {
  5623. if (stale_work(work, false)) {
  5624. HASH_DEL(staged_work, work);
  5625. discard_work(work);
  5626. stale++;
  5627. staged_full = false;
  5628. }
  5629. }
  5630. pthread_cond_signal(&gws_cond);
  5631. mutex_unlock(stgd_lock);
  5632. if (stale)
  5633. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5634. }
  5635. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5636. {
  5637. bool rv;
  5638. struct timeval tv, orig;
  5639. ldiv_t d;
  5640. d = ldiv(ustime, 1000000);
  5641. tv = (struct timeval){
  5642. .tv_sec = d.quot,
  5643. .tv_usec = d.rem,
  5644. };
  5645. orig = work->tv_staged;
  5646. timersub(&orig, &tv, &work->tv_staged);
  5647. rv = stale_work(work, share);
  5648. work->tv_staged = orig;
  5649. return rv;
  5650. }
  5651. static
  5652. void pool_update_work_restart_time(struct pool * const pool)
  5653. {
  5654. pool->work_restart_time = time(NULL);
  5655. get_timestamp(pool->work_restart_timestamp, sizeof(pool->work_restart_timestamp), pool->work_restart_time);
  5656. }
  5657. static void restart_threads(void)
  5658. {
  5659. struct pool *cp = current_pool();
  5660. int i;
  5661. struct thr_info *thr;
  5662. /* Artificially set the lagging flag to avoid pool not providing work
  5663. * fast enough messages after every long poll */
  5664. pool_tset(cp, &cp->lagging);
  5665. /* Discard staged work that is now stale */
  5666. discard_stale();
  5667. rd_lock(&mining_thr_lock);
  5668. for (i = 0; i < mining_threads; i++)
  5669. {
  5670. thr = mining_thr[i];
  5671. thr->work_restart = true;
  5672. }
  5673. for (i = 0; i < mining_threads; i++)
  5674. {
  5675. thr = mining_thr[i];
  5676. notifier_wake(thr->work_restart_notifier);
  5677. }
  5678. rd_unlock(&mining_thr_lock);
  5679. }
  5680. static
  5681. void blkhashstr(char *rv, const unsigned char *hash)
  5682. {
  5683. unsigned char hash_swap[32];
  5684. swap256(hash_swap, hash);
  5685. swap32tole(hash_swap, hash_swap, 32 / 4);
  5686. bin2hex(rv, hash_swap, 32);
  5687. }
  5688. static void set_curblock(char *hexstr, unsigned char *hash)
  5689. {
  5690. unsigned char hash_swap[32];
  5691. current_block_id = ((uint32_t*)hash)[0];
  5692. strcpy(current_block, hexstr);
  5693. swap256(hash_swap, hash);
  5694. swap32tole(hash_swap, hash_swap, 32 / 4);
  5695. cg_wlock(&ch_lock);
  5696. block_time = time(NULL);
  5697. __update_block_title(hash_swap);
  5698. free(current_fullhash);
  5699. current_fullhash = malloc(65);
  5700. bin2hex(current_fullhash, hash_swap, 32);
  5701. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5702. cg_wunlock(&ch_lock);
  5703. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5704. }
  5705. /* Search to see if this string is from a block that has been seen before */
  5706. static bool block_exists(char *hexstr)
  5707. {
  5708. struct block *s;
  5709. rd_lock(&blk_lock);
  5710. HASH_FIND_STR(blocks, hexstr, s);
  5711. rd_unlock(&blk_lock);
  5712. if (s)
  5713. return true;
  5714. return false;
  5715. }
  5716. #if 0
  5717. /* Tests if this work is from a block that has been seen before */
  5718. static inline bool from_existing_block(struct work *work)
  5719. {
  5720. char hexstr[37];
  5721. bool ret;
  5722. bin2hex(hexstr, work->data + 8, 18);
  5723. ret = block_exists(hexstr);
  5724. return ret;
  5725. }
  5726. #endif
  5727. static int block_sort(struct block *blocka, struct block *blockb)
  5728. {
  5729. return blocka->block_no - blockb->block_no;
  5730. }
  5731. static void set_blockdiff(const struct work *work)
  5732. {
  5733. unsigned char target[32];
  5734. double diff;
  5735. uint64_t diff64;
  5736. real_block_target(target, work->data);
  5737. diff = target_diff(target);
  5738. diff64 = diff;
  5739. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5740. format_unit2(net_hashrate, sizeof(net_hashrate),
  5741. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5742. if (unlikely(current_diff != diff))
  5743. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5744. current_diff = diff;
  5745. }
  5746. static bool test_work_current(struct work *work)
  5747. {
  5748. bool ret = true;
  5749. char hexstr[65];
  5750. if (work->mandatory)
  5751. return ret;
  5752. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5753. /* Hack to work around dud work sneaking into test */
  5754. bin2hex(hexstr, work->data + 8, 18);
  5755. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5756. goto out_free;
  5757. struct pool * const pool = work->pool;
  5758. /* Search to see if this block exists yet and if not, consider it a
  5759. * new block and set the current block details to this one */
  5760. if (!block_exists(hexstr))
  5761. {
  5762. struct block *s = calloc(sizeof(struct block), 1);
  5763. int deleted_block = 0;
  5764. ret = false;
  5765. if (unlikely(!s))
  5766. quit (1, "test_work_current OOM");
  5767. strcpy(s->hash, hexstr);
  5768. s->block_no = new_blocks++;
  5769. wr_lock(&blk_lock);
  5770. /* Only keep the last hour's worth of blocks in memory since
  5771. * work from blocks before this is virtually impossible and we
  5772. * want to prevent memory usage from continually rising */
  5773. if (HASH_COUNT(blocks) > 6)
  5774. {
  5775. struct block *oldblock;
  5776. HASH_SORT(blocks, block_sort);
  5777. oldblock = blocks;
  5778. deleted_block = oldblock->block_no;
  5779. HASH_DEL(blocks, oldblock);
  5780. free(oldblock);
  5781. }
  5782. HASH_ADD_STR(blocks, hash, s);
  5783. set_blockdiff(work);
  5784. wr_unlock(&blk_lock);
  5785. pool->block_id = block_id;
  5786. pool_update_work_restart_time(pool);
  5787. if (deleted_block)
  5788. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5789. #if BLKMAKER_VERSION > 1
  5790. template_nonce = 0;
  5791. #endif
  5792. set_curblock(hexstr, &work->data[4]);
  5793. if (unlikely(new_blocks == 1))
  5794. goto out_free;
  5795. if (!work->stratum)
  5796. {
  5797. if (work->longpoll)
  5798. {
  5799. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5800. pool->pool_no);
  5801. }
  5802. else
  5803. if (have_longpoll)
  5804. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5805. else
  5806. applog(LOG_NOTICE, "New block detected on network");
  5807. }
  5808. restart_threads();
  5809. }
  5810. else
  5811. {
  5812. bool restart = false;
  5813. if (unlikely(pool->block_id != block_id))
  5814. {
  5815. bool was_active = pool->block_id != 0;
  5816. pool->block_id = block_id;
  5817. pool_update_work_restart_time(pool);
  5818. if (!work->longpoll)
  5819. update_last_work(work);
  5820. if (was_active)
  5821. {
  5822. // Pool actively changed block
  5823. if (pool == current_pool())
  5824. restart = true;
  5825. if (block_id == current_block_id)
  5826. {
  5827. // Caught up, only announce if this pool is the one in use
  5828. if (restart)
  5829. applog(LOG_NOTICE, "%s %d caught up to new block",
  5830. work->longpoll ? "Longpoll from pool" : "Pool",
  5831. pool->pool_no);
  5832. }
  5833. else
  5834. {
  5835. // Switched to a block we know, but not the latest... why?
  5836. // This might detect pools trying to double-spend or 51%,
  5837. // but let's not make any accusations until it's had time
  5838. // in the real world.
  5839. blkhashstr(hexstr, &work->data[4]);
  5840. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5841. work->longpoll ? "Longpoll from pool" : "Pool",
  5842. pool->pool_no,
  5843. hexstr);
  5844. }
  5845. }
  5846. }
  5847. if (work->longpoll)
  5848. {
  5849. struct pool * const cp = current_pool();
  5850. ++pool->work_restart_id;
  5851. if (work->tr && work->tr == pool->swork.tr)
  5852. pool->swork.work_restart_id = pool->work_restart_id;
  5853. update_last_work(work);
  5854. pool_update_work_restart_time(pool);
  5855. applog(
  5856. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  5857. "Longpoll from pool %d requested work update",
  5858. pool->pool_no);
  5859. if ((!restart) && pool == cp)
  5860. restart = true;
  5861. }
  5862. if (restart)
  5863. restart_threads();
  5864. }
  5865. work->longpoll = false;
  5866. out_free:
  5867. return ret;
  5868. }
  5869. static int tv_sort(struct work *worka, struct work *workb)
  5870. {
  5871. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5872. }
  5873. static bool work_rollable(struct work *work)
  5874. {
  5875. return (!work->clone && work->rolltime);
  5876. }
  5877. static bool hash_push(struct work *work)
  5878. {
  5879. bool rc = true;
  5880. mutex_lock(stgd_lock);
  5881. if (work_rollable(work))
  5882. staged_rollable++;
  5883. if (likely(!getq->frozen)) {
  5884. HASH_ADD_INT(staged_work, id, work);
  5885. HASH_SORT(staged_work, tv_sort);
  5886. } else
  5887. rc = false;
  5888. pthread_cond_broadcast(&getq->cond);
  5889. mutex_unlock(stgd_lock);
  5890. return rc;
  5891. }
  5892. static void stage_work(struct work *work)
  5893. {
  5894. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5895. work->id, work->pool->pool_no);
  5896. work->work_restart_id = work->pool->work_restart_id;
  5897. work->pool->last_work_time = time(NULL);
  5898. cgtime(&work->pool->tv_last_work_time);
  5899. test_work_current(work);
  5900. work->pool->works++;
  5901. hash_push(work);
  5902. }
  5903. #ifdef HAVE_CURSES
  5904. int curses_int(const char *query)
  5905. {
  5906. int ret;
  5907. char *cvar;
  5908. cvar = curses_input(query);
  5909. if (unlikely(!cvar))
  5910. return -1;
  5911. ret = atoi(cvar);
  5912. free(cvar);
  5913. return ret;
  5914. }
  5915. #endif
  5916. #ifdef HAVE_CURSES
  5917. static bool input_pool(bool live);
  5918. #endif
  5919. #ifdef HAVE_CURSES
  5920. static void display_pool_summary(struct pool *pool)
  5921. {
  5922. double efficiency = 0.0;
  5923. char xfer[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+4+1], bw[ALLOC_H2B_NOUNIT+ALLOC_H2B_SPACED+6+1];
  5924. int pool_secs;
  5925. if (curses_active_locked()) {
  5926. wlog("Pool: %s\n", pool->rpc_url);
  5927. if (pool->solved)
  5928. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5929. if (!pool->has_stratum)
  5930. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5931. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5932. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5933. wlog(" Accepted shares: %d\n", pool->accepted);
  5934. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5935. pool->rejected, pool->stale_shares,
  5936. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5937. );
  5938. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5939. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5940. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5941. wlog(" Network transfer: %s (%s)\n",
  5942. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5943. (float)pool->cgminer_pool_stats.net_bytes_received,
  5944. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5945. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5946. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5947. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5948. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5949. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5950. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5951. wlog(" Items worked on: %d\n", pool->works);
  5952. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5953. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5954. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5955. unlock_curses();
  5956. }
  5957. }
  5958. #endif
  5959. /* We can't remove the memory used for this struct pool because there may
  5960. * still be work referencing it. We just remove it from the pools list */
  5961. void remove_pool(struct pool *pool)
  5962. {
  5963. int i, last_pool = total_pools - 1;
  5964. struct pool *other;
  5965. /* Boost priority of any lower prio than this one */
  5966. for (i = 0; i < total_pools; i++) {
  5967. other = pools[i];
  5968. if (other->prio > pool->prio)
  5969. other->prio--;
  5970. }
  5971. if (pool->pool_no < last_pool) {
  5972. /* Swap the last pool for this one */
  5973. (pools[last_pool])->pool_no = pool->pool_no;
  5974. pools[pool->pool_no] = pools[last_pool];
  5975. }
  5976. /* Give it an invalid number */
  5977. pool->pool_no = total_pools;
  5978. pool->removed = true;
  5979. pool->has_stratum = false;
  5980. total_pools--;
  5981. }
  5982. /* add a mutex if this needs to be thread safe in the future */
  5983. static struct JE {
  5984. char *buf;
  5985. struct JE *next;
  5986. } *jedata = NULL;
  5987. static void json_escape_free()
  5988. {
  5989. struct JE *jeptr = jedata;
  5990. struct JE *jenext;
  5991. jedata = NULL;
  5992. while (jeptr) {
  5993. jenext = jeptr->next;
  5994. free(jeptr->buf);
  5995. free(jeptr);
  5996. jeptr = jenext;
  5997. }
  5998. }
  5999. static
  6000. char *json_escape(const char *str)
  6001. {
  6002. struct JE *jeptr;
  6003. char *buf, *ptr;
  6004. /* 2x is the max, may as well just allocate that */
  6005. ptr = buf = malloc(strlen(str) * 2 + 1);
  6006. jeptr = malloc(sizeof(*jeptr));
  6007. jeptr->buf = buf;
  6008. jeptr->next = jedata;
  6009. jedata = jeptr;
  6010. while (*str) {
  6011. if (*str == '\\' || *str == '"')
  6012. *(ptr++) = '\\';
  6013. *(ptr++) = *(str++);
  6014. }
  6015. *ptr = '\0';
  6016. return buf;
  6017. }
  6018. static
  6019. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  6020. {
  6021. if (!elist)
  6022. return;
  6023. static struct string_elist *entry;
  6024. fprintf(fcfg, ",\n\"%s\" : [", configname);
  6025. bool first = true;
  6026. DL_FOREACH(elist, entry)
  6027. {
  6028. const char * const s = entry->string;
  6029. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  6030. first = false;
  6031. }
  6032. fprintf(fcfg, "\n]");
  6033. }
  6034. void write_config(FILE *fcfg)
  6035. {
  6036. int i;
  6037. /* Write pool values */
  6038. fputs("{\n\"pools\" : [", fcfg);
  6039. for(i = 0; i < total_pools; i++) {
  6040. struct pool *pool = pools[i];
  6041. if (pool->quota != 1) {
  6042. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  6043. pool->quota,
  6044. json_escape(pool->rpc_url));
  6045. } else {
  6046. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  6047. json_escape(pool->rpc_url));
  6048. }
  6049. if (pool->rpc_proxy)
  6050. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  6051. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  6052. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  6053. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  6054. if (pool->force_rollntime)
  6055. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  6056. fprintf(fcfg, "\n\t}");
  6057. }
  6058. fputs("\n]\n", fcfg);
  6059. #ifdef HAVE_OPENCL
  6060. write_config_opencl(fcfg);
  6061. #endif
  6062. #ifdef WANT_CPUMINE
  6063. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  6064. #endif
  6065. /* Simple bool and int options */
  6066. struct opt_table *opt;
  6067. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  6068. char *p, *name = strdup(opt->names);
  6069. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  6070. if (p[1] != '-')
  6071. continue;
  6072. if (opt->type & OPT_NOARG &&
  6073. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  6074. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  6075. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  6076. if (opt->type & OPT_HASARG &&
  6077. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  6078. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  6079. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  6080. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  6081. opt->desc != opt_hidden &&
  6082. 0 <= *(int *)opt->u.arg)
  6083. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  6084. }
  6085. }
  6086. /* Special case options */
  6087. if (request_target_str)
  6088. {
  6089. if (request_pdiff == (long)request_pdiff)
  6090. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  6091. else
  6092. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  6093. }
  6094. fprintf(fcfg, ",\n\"shares\" : %g", opt_shares);
  6095. if (pool_strategy == POOL_BALANCE)
  6096. fputs(",\n\"balance\" : true", fcfg);
  6097. if (pool_strategy == POOL_LOADBALANCE)
  6098. fputs(",\n\"load-balance\" : true", fcfg);
  6099. if (pool_strategy == POOL_ROUNDROBIN)
  6100. fputs(",\n\"round-robin\" : true", fcfg);
  6101. if (pool_strategy == POOL_ROTATE)
  6102. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  6103. #if defined(unix) || defined(__APPLE__)
  6104. if (opt_stderr_cmd && *opt_stderr_cmd)
  6105. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  6106. #endif // defined(unix)
  6107. if (opt_kernel_path && *opt_kernel_path) {
  6108. char *kpath = strdup(opt_kernel_path);
  6109. if (kpath[strlen(kpath)-1] == '/')
  6110. kpath[strlen(kpath)-1] = 0;
  6111. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  6112. free(kpath);
  6113. }
  6114. if (schedstart.enable)
  6115. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  6116. if (schedstop.enable)
  6117. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  6118. if (opt_socks_proxy && *opt_socks_proxy)
  6119. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  6120. _write_config_string_elist(fcfg, "scan", scan_devices);
  6121. #ifdef USE_LIBMICROHTTPD
  6122. if (httpsrv_port != -1)
  6123. fprintf(fcfg, ",\n\"http-port\" : %d", httpsrv_port);
  6124. #endif
  6125. #ifdef USE_LIBEVENT
  6126. if (stratumsrv_port != -1)
  6127. fprintf(fcfg, ",\n\"stratum-port\" : %d", stratumsrv_port);
  6128. #endif
  6129. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  6130. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  6131. if (opt_api_allow)
  6132. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  6133. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  6134. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  6135. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  6136. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  6137. if (*opt_api_mcast_des)
  6138. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  6139. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  6140. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  6141. if (opt_api_groups)
  6142. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  6143. fputs("\n}\n", fcfg);
  6144. json_escape_free();
  6145. }
  6146. void zero_bestshare(void)
  6147. {
  6148. int i;
  6149. best_diff = 0;
  6150. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  6151. for (i = 0; i < total_pools; i++) {
  6152. struct pool *pool = pools[i];
  6153. pool->best_diff = 0;
  6154. }
  6155. }
  6156. void zero_stats(void)
  6157. {
  6158. int i;
  6159. applog(LOG_DEBUG, "Zeroing stats");
  6160. cgtime(&total_tv_start);
  6161. miner_started = total_tv_start;
  6162. total_rolling = 0;
  6163. total_mhashes_done = 0;
  6164. total_getworks = 0;
  6165. total_accepted = 0;
  6166. total_rejected = 0;
  6167. hw_errors = 0;
  6168. total_stale = 0;
  6169. total_discarded = 0;
  6170. total_bytes_rcvd = total_bytes_sent = 0;
  6171. new_blocks = 0;
  6172. local_work = 0;
  6173. total_go = 0;
  6174. total_ro = 0;
  6175. total_secs = 1.0;
  6176. total_diff1 = 0;
  6177. total_bad_diff1 = 0;
  6178. found_blocks = 0;
  6179. total_diff_accepted = 0;
  6180. total_diff_rejected = 0;
  6181. total_diff_stale = 0;
  6182. #ifdef HAVE_CURSES
  6183. awidth = rwidth = swidth = hwwidth = 1;
  6184. #endif
  6185. for (i = 0; i < total_pools; i++) {
  6186. struct pool *pool = pools[i];
  6187. pool->getwork_requested = 0;
  6188. pool->accepted = 0;
  6189. pool->rejected = 0;
  6190. pool->solved = 0;
  6191. pool->getwork_requested = 0;
  6192. pool->stale_shares = 0;
  6193. pool->discarded_work = 0;
  6194. pool->getfail_occasions = 0;
  6195. pool->remotefail_occasions = 0;
  6196. pool->last_share_time = 0;
  6197. pool->works = 0;
  6198. pool->diff1 = 0;
  6199. pool->diff_accepted = 0;
  6200. pool->diff_rejected = 0;
  6201. pool->diff_stale = 0;
  6202. pool->last_share_diff = 0;
  6203. pool->cgminer_stats.start_tv = total_tv_start;
  6204. pool->cgminer_stats.getwork_calls = 0;
  6205. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6206. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6207. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6208. pool->cgminer_pool_stats.getwork_calls = 0;
  6209. pool->cgminer_pool_stats.getwork_attempts = 0;
  6210. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6211. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  6212. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  6213. pool->cgminer_pool_stats.min_diff = 0;
  6214. pool->cgminer_pool_stats.max_diff = 0;
  6215. pool->cgminer_pool_stats.min_diff_count = 0;
  6216. pool->cgminer_pool_stats.max_diff_count = 0;
  6217. pool->cgminer_pool_stats.times_sent = 0;
  6218. pool->cgminer_pool_stats.bytes_sent = 0;
  6219. pool->cgminer_pool_stats.net_bytes_sent = 0;
  6220. pool->cgminer_pool_stats.times_received = 0;
  6221. pool->cgminer_pool_stats.bytes_received = 0;
  6222. pool->cgminer_pool_stats.net_bytes_received = 0;
  6223. }
  6224. zero_bestshare();
  6225. for (i = 0; i < total_devices; ++i) {
  6226. struct cgpu_info *cgpu = get_devices(i);
  6227. mutex_lock(&hash_lock);
  6228. cgpu->total_mhashes = 0;
  6229. cgpu->accepted = 0;
  6230. cgpu->rejected = 0;
  6231. cgpu->stale = 0;
  6232. cgpu->hw_errors = 0;
  6233. cgpu->utility = 0.0;
  6234. cgpu->utility_diff1 = 0;
  6235. cgpu->last_share_pool_time = 0;
  6236. cgpu->bad_diff1 = 0;
  6237. cgpu->diff1 = 0;
  6238. cgpu->diff_accepted = 0;
  6239. cgpu->diff_rejected = 0;
  6240. cgpu->diff_stale = 0;
  6241. cgpu->last_share_diff = 0;
  6242. cgpu->thread_fail_init_count = 0;
  6243. cgpu->thread_zero_hash_count = 0;
  6244. cgpu->thread_fail_queue_count = 0;
  6245. cgpu->dev_sick_idle_60_count = 0;
  6246. cgpu->dev_dead_idle_600_count = 0;
  6247. cgpu->dev_nostart_count = 0;
  6248. cgpu->dev_over_heat_count = 0;
  6249. cgpu->dev_thermal_cutoff_count = 0;
  6250. cgpu->dev_comms_error_count = 0;
  6251. cgpu->dev_throttle_count = 0;
  6252. cgpu->cgminer_stats.start_tv = total_tv_start;
  6253. cgpu->cgminer_stats.getwork_calls = 0;
  6254. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6255. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  6256. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  6257. mutex_unlock(&hash_lock);
  6258. }
  6259. }
  6260. #ifdef HAVE_CURSES
  6261. static
  6262. void loginput_mode(const int size)
  6263. {
  6264. clear_logwin();
  6265. loginput_size = size;
  6266. check_winsizes();
  6267. }
  6268. static void display_pools(void)
  6269. {
  6270. struct pool *pool;
  6271. int selected, i, j;
  6272. char input;
  6273. loginput_mode(7 + total_pools);
  6274. immedok(logwin, true);
  6275. updated:
  6276. for (j = 0; j < total_pools; j++) {
  6277. for (i = 0; i < total_pools; i++) {
  6278. pool = pools[i];
  6279. if (pool->prio != j)
  6280. continue;
  6281. if (pool == current_pool())
  6282. wattron(logwin, A_BOLD);
  6283. if (pool->enabled != POOL_ENABLED)
  6284. wattron(logwin, A_DIM);
  6285. wlogprint("%d: ", pool->prio);
  6286. switch (pool->enabled) {
  6287. case POOL_ENABLED:
  6288. wlogprint("Enabled ");
  6289. break;
  6290. case POOL_DISABLED:
  6291. wlogprint("Disabled ");
  6292. break;
  6293. case POOL_REJECTING:
  6294. wlogprint("Rejectin ");
  6295. break;
  6296. }
  6297. _wlogprint(pool_proto_str(pool));
  6298. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  6299. pool->quota,
  6300. pool->pool_no,
  6301. pool->rpc_url, pool->rpc_user);
  6302. wattroff(logwin, A_BOLD | A_DIM);
  6303. break; //for (i = 0; i < total_pools; i++)
  6304. }
  6305. }
  6306. retry:
  6307. wlogprint("\nCurrent pool management strategy: %s\n",
  6308. strategies[pool_strategy].s);
  6309. if (pool_strategy == POOL_ROTATE)
  6310. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  6311. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  6312. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  6313. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  6314. wlogprint("Or press any other key to continue\n");
  6315. logwin_update();
  6316. input = getch();
  6317. if (!strncasecmp(&input, "a", 1)) {
  6318. if (opt_benchmark)
  6319. {
  6320. wlogprint("Cannot add pools in benchmark mode");
  6321. goto retry;
  6322. }
  6323. input_pool(true);
  6324. goto updated;
  6325. } else if (!strncasecmp(&input, "r", 1)) {
  6326. if (total_pools <= 1) {
  6327. wlogprint("Cannot remove last pool");
  6328. goto retry;
  6329. }
  6330. selected = curses_int("Select pool number");
  6331. if (selected < 0 || selected >= total_pools) {
  6332. wlogprint("Invalid selection\n");
  6333. goto retry;
  6334. }
  6335. pool = pools[selected];
  6336. if (pool == current_pool())
  6337. switch_pools(NULL);
  6338. if (pool == current_pool()) {
  6339. wlogprint("Unable to remove pool due to activity\n");
  6340. goto retry;
  6341. }
  6342. disable_pool(pool);
  6343. remove_pool(pool);
  6344. goto updated;
  6345. } else if (!strncasecmp(&input, "s", 1)) {
  6346. selected = curses_int("Select pool number");
  6347. if (selected < 0 || selected >= total_pools) {
  6348. wlogprint("Invalid selection\n");
  6349. goto retry;
  6350. }
  6351. pool = pools[selected];
  6352. enable_pool(pool);
  6353. switch_pools(pool);
  6354. goto updated;
  6355. } else if (!strncasecmp(&input, "d", 1)) {
  6356. if (enabled_pools <= 1) {
  6357. wlogprint("Cannot disable last pool");
  6358. goto retry;
  6359. }
  6360. selected = curses_int("Select pool number");
  6361. if (selected < 0 || selected >= total_pools) {
  6362. wlogprint("Invalid selection\n");
  6363. goto retry;
  6364. }
  6365. pool = pools[selected];
  6366. disable_pool(pool);
  6367. if (pool == current_pool())
  6368. switch_pools(NULL);
  6369. goto updated;
  6370. } else if (!strncasecmp(&input, "e", 1)) {
  6371. selected = curses_int("Select pool number");
  6372. if (selected < 0 || selected >= total_pools) {
  6373. wlogprint("Invalid selection\n");
  6374. goto retry;
  6375. }
  6376. pool = pools[selected];
  6377. enable_pool(pool);
  6378. if (pool->prio < current_pool()->prio)
  6379. switch_pools(pool);
  6380. goto updated;
  6381. } else if (!strncasecmp(&input, "c", 1)) {
  6382. for (i = 0; i <= TOP_STRATEGY; i++)
  6383. wlogprint("%d: %s\n", i, strategies[i].s);
  6384. selected = curses_int("Select strategy number type");
  6385. if (selected < 0 || selected > TOP_STRATEGY) {
  6386. wlogprint("Invalid selection\n");
  6387. goto retry;
  6388. }
  6389. if (selected == POOL_ROTATE) {
  6390. opt_rotate_period = curses_int("Select interval in minutes");
  6391. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  6392. opt_rotate_period = 0;
  6393. wlogprint("Invalid selection\n");
  6394. goto retry;
  6395. }
  6396. }
  6397. mutex_lock(&lp_lock);
  6398. pool_strategy = selected;
  6399. pthread_cond_broadcast(&lp_cond);
  6400. mutex_unlock(&lp_lock);
  6401. switch_pools(NULL);
  6402. goto updated;
  6403. } else if (!strncasecmp(&input, "i", 1)) {
  6404. selected = curses_int("Select pool number");
  6405. if (selected < 0 || selected >= total_pools) {
  6406. wlogprint("Invalid selection\n");
  6407. goto retry;
  6408. }
  6409. pool = pools[selected];
  6410. display_pool_summary(pool);
  6411. goto retry;
  6412. } else if (!strncasecmp(&input, "q", 1)) {
  6413. selected = curses_int("Select pool number");
  6414. if (selected < 0 || selected >= total_pools) {
  6415. wlogprint("Invalid selection\n");
  6416. goto retry;
  6417. }
  6418. pool = pools[selected];
  6419. selected = curses_int("Set quota");
  6420. if (selected < 0) {
  6421. wlogprint("Invalid negative quota\n");
  6422. goto retry;
  6423. }
  6424. pool->quota = selected;
  6425. adjust_quota_gcd();
  6426. goto updated;
  6427. } else if (!strncasecmp(&input, "f", 1)) {
  6428. opt_fail_only ^= true;
  6429. goto updated;
  6430. } else if (!strncasecmp(&input, "p", 1)) {
  6431. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6432. if (!prilist)
  6433. {
  6434. wlogprint("Not changing priorities\n");
  6435. goto retry;
  6436. }
  6437. int res = prioritize_pools(prilist, &i);
  6438. free(prilist);
  6439. switch (res) {
  6440. case MSG_NOPOOL:
  6441. wlogprint("No pools\n");
  6442. goto retry;
  6443. case MSG_MISPID:
  6444. wlogprint("Missing pool id parameter\n");
  6445. goto retry;
  6446. case MSG_INVPID:
  6447. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6448. goto retry;
  6449. case MSG_DUPPID:
  6450. wlogprint("Duplicate pool specified %d\n", i);
  6451. goto retry;
  6452. case MSG_POOLPRIO:
  6453. default:
  6454. goto updated;
  6455. }
  6456. }
  6457. immedok(logwin, false);
  6458. loginput_mode(0);
  6459. }
  6460. static const char *summary_detail_level_str(void)
  6461. {
  6462. if (opt_compact)
  6463. return "compact";
  6464. if (opt_show_procs)
  6465. return "processors";
  6466. return "devices";
  6467. }
  6468. static void display_options(void)
  6469. {
  6470. int selected;
  6471. char input;
  6472. immedok(logwin, true);
  6473. loginput_mode(12);
  6474. retry:
  6475. clear_logwin();
  6476. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6477. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6478. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6479. "[L]og interval:%d\nS[T]atistical counts: %s\n[Z]ero statistics\n",
  6480. opt_debug_console ? "on" : "off",
  6481. want_per_device_stats? "on" : "off",
  6482. opt_quiet ? "on" : "off",
  6483. opt_log_output ? "on" : "off",
  6484. opt_protocol ? "on" : "off",
  6485. opt_worktime ? "on" : "off",
  6486. summary_detail_level_str(),
  6487. opt_log_interval,
  6488. opt_weighed_stats ? "weighed" : "absolute");
  6489. wlogprint("Select an option or any other key to return\n");
  6490. logwin_update();
  6491. input = getch();
  6492. if (!strncasecmp(&input, "q", 1)) {
  6493. opt_quiet ^= true;
  6494. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6495. goto retry;
  6496. } else if (!strncasecmp(&input, "v", 1)) {
  6497. opt_log_output ^= true;
  6498. if (opt_log_output)
  6499. opt_quiet = false;
  6500. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6501. goto retry;
  6502. } else if (!strncasecmp(&input, "n", 1)) {
  6503. opt_log_output = false;
  6504. opt_debug_console = false;
  6505. opt_quiet = false;
  6506. opt_protocol = false;
  6507. opt_compact = false;
  6508. opt_show_procs = false;
  6509. devsummaryYOffset = 0;
  6510. want_per_device_stats = false;
  6511. wlogprint("Output mode reset to normal\n");
  6512. switch_logsize();
  6513. goto retry;
  6514. } else if (!strncasecmp(&input, "d", 1)) {
  6515. opt_debug = true;
  6516. opt_debug_console ^= true;
  6517. opt_log_output = opt_debug_console;
  6518. if (opt_debug_console)
  6519. opt_quiet = false;
  6520. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6521. goto retry;
  6522. } else if (!strncasecmp(&input, "m", 1)) {
  6523. if (opt_compact)
  6524. opt_compact = false;
  6525. else
  6526. if (!opt_show_procs)
  6527. opt_show_procs = true;
  6528. else
  6529. {
  6530. opt_compact = true;
  6531. opt_show_procs = false;
  6532. devsummaryYOffset = 0;
  6533. }
  6534. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6535. switch_logsize();
  6536. goto retry;
  6537. } else if (!strncasecmp(&input, "p", 1)) {
  6538. want_per_device_stats ^= true;
  6539. opt_log_output = want_per_device_stats;
  6540. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6541. goto retry;
  6542. } else if (!strncasecmp(&input, "r", 1)) {
  6543. opt_protocol ^= true;
  6544. if (opt_protocol)
  6545. opt_quiet = false;
  6546. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6547. goto retry;
  6548. } else if (!strncasecmp(&input, "c", 1))
  6549. clear_logwin();
  6550. else if (!strncasecmp(&input, "l", 1)) {
  6551. selected = curses_int("Interval in seconds");
  6552. if (selected < 0 || selected > 9999) {
  6553. wlogprint("Invalid selection\n");
  6554. goto retry;
  6555. }
  6556. opt_log_interval = selected;
  6557. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6558. goto retry;
  6559. } else if (!strncasecmp(&input, "s", 1)) {
  6560. opt_realquiet = true;
  6561. } else if (!strncasecmp(&input, "w", 1)) {
  6562. opt_worktime ^= true;
  6563. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6564. goto retry;
  6565. } else if (!strncasecmp(&input, "t", 1)) {
  6566. opt_weighed_stats ^= true;
  6567. wlogprint("Now displaying %s statistics\n", opt_weighed_stats ? "weighed" : "absolute");
  6568. goto retry;
  6569. } else if (!strncasecmp(&input, "z", 1)) {
  6570. zero_stats();
  6571. goto retry;
  6572. }
  6573. immedok(logwin, false);
  6574. loginput_mode(0);
  6575. }
  6576. #endif
  6577. void default_save_file(char *filename)
  6578. {
  6579. #if defined(unix) || defined(__APPLE__)
  6580. if (getenv("HOME") && *getenv("HOME")) {
  6581. strcpy(filename, getenv("HOME"));
  6582. strcat(filename, "/");
  6583. }
  6584. else
  6585. strcpy(filename, "");
  6586. strcat(filename, ".bfgminer/");
  6587. mkdir(filename, 0777);
  6588. #else
  6589. strcpy(filename, "");
  6590. #endif
  6591. strcat(filename, def_conf);
  6592. }
  6593. #ifdef HAVE_CURSES
  6594. static void set_options(void)
  6595. {
  6596. int selected;
  6597. char input;
  6598. immedok(logwin, true);
  6599. loginput_mode(8);
  6600. retry:
  6601. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6602. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6603. "[W]rite config file\n[B]FGMiner restart\n",
  6604. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6605. wlogprint("Select an option or any other key to return\n");
  6606. logwin_update();
  6607. input = getch();
  6608. if (!strncasecmp(&input, "q", 1)) {
  6609. selected = curses_int("Extra work items to queue");
  6610. if (selected < 0 || selected > 9999) {
  6611. wlogprint("Invalid selection\n");
  6612. goto retry;
  6613. }
  6614. opt_queue = selected;
  6615. goto retry;
  6616. } else if (!strncasecmp(&input, "l", 1)) {
  6617. if (want_longpoll)
  6618. stop_longpoll();
  6619. else
  6620. start_longpoll();
  6621. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6622. goto retry;
  6623. } else if (!strncasecmp(&input, "s", 1)) {
  6624. selected = curses_int("Set scantime in seconds");
  6625. if (selected < 0 || selected > 9999) {
  6626. wlogprint("Invalid selection\n");
  6627. goto retry;
  6628. }
  6629. opt_scantime = selected;
  6630. goto retry;
  6631. } else if (!strncasecmp(&input, "e", 1)) {
  6632. selected = curses_int("Set expiry time in seconds");
  6633. if (selected < 0 || selected > 9999) {
  6634. wlogprint("Invalid selection\n");
  6635. goto retry;
  6636. }
  6637. opt_expiry = selected;
  6638. goto retry;
  6639. } else if (!strncasecmp(&input, "r", 1)) {
  6640. selected = curses_int("Retries before failing (-1 infinite)");
  6641. if (selected < -1 || selected > 9999) {
  6642. wlogprint("Invalid selection\n");
  6643. goto retry;
  6644. }
  6645. opt_retries = selected;
  6646. goto retry;
  6647. } else if (!strncasecmp(&input, "w", 1)) {
  6648. FILE *fcfg;
  6649. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6650. default_save_file(filename);
  6651. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6652. str = curses_input(prompt);
  6653. if (str) {
  6654. struct stat statbuf;
  6655. strcpy(filename, str);
  6656. free(str);
  6657. if (!stat(filename, &statbuf)) {
  6658. wlogprint("File exists, overwrite?\n");
  6659. input = getch();
  6660. if (strncasecmp(&input, "y", 1))
  6661. goto retry;
  6662. }
  6663. }
  6664. fcfg = fopen(filename, "w");
  6665. if (!fcfg) {
  6666. wlogprint("Cannot open or create file\n");
  6667. goto retry;
  6668. }
  6669. write_config(fcfg);
  6670. fclose(fcfg);
  6671. goto retry;
  6672. } else if (!strncasecmp(&input, "b", 1)) {
  6673. wlogprint("Are you sure?\n");
  6674. input = getch();
  6675. if (!strncasecmp(&input, "y", 1))
  6676. app_restart();
  6677. else
  6678. clear_logwin();
  6679. } else
  6680. clear_logwin();
  6681. loginput_mode(0);
  6682. immedok(logwin, false);
  6683. }
  6684. int scan_serial(const char *);
  6685. static
  6686. void _managetui_msg(const char *repr, const char **msg)
  6687. {
  6688. if (*msg)
  6689. {
  6690. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6691. wattron(logwin, A_BOLD);
  6692. wlogprint("%s", *msg);
  6693. wattroff(logwin, A_BOLD);
  6694. *msg = NULL;
  6695. }
  6696. logwin_update();
  6697. }
  6698. void manage_device(void)
  6699. {
  6700. char logline[256];
  6701. const char *msg = NULL;
  6702. struct cgpu_info *cgpu;
  6703. const struct device_drv *drv;
  6704. selecting_device = true;
  6705. immedok(logwin, true);
  6706. loginput_mode(12);
  6707. devchange:
  6708. if (unlikely(!total_devices))
  6709. {
  6710. clear_logwin();
  6711. wlogprint("(no devices)\n");
  6712. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6713. _managetui_msg("(none)", &msg);
  6714. int input = getch();
  6715. switch (input)
  6716. {
  6717. case '+': case '=': // add new device
  6718. goto addnew;
  6719. default:
  6720. goto out;
  6721. }
  6722. }
  6723. cgpu = devices[selected_device];
  6724. drv = cgpu->drv;
  6725. refresh_devstatus();
  6726. refresh:
  6727. clear_logwin();
  6728. wlogprint("Select processor to manage using up/down arrow keys\n");
  6729. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6730. wattron(logwin, A_BOLD);
  6731. wlogprint("%s", logline);
  6732. wattroff(logwin, A_BOLD);
  6733. wlogprint("\n");
  6734. if (cgpu->dev_manufacturer)
  6735. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6736. else
  6737. if (cgpu->dev_product)
  6738. wlogprint(" %s\n", cgpu->dev_product);
  6739. if (cgpu->dev_serial)
  6740. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6741. if (cgpu->kname)
  6742. wlogprint("Kernel: %s\n", cgpu->kname);
  6743. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6744. drv->proc_wlogprint_status(cgpu);
  6745. wlogprint("\n");
  6746. // TODO: Last share at TIMESTAMP on pool N
  6747. // TODO: Custom device info/commands
  6748. if (cgpu->deven != DEV_ENABLED)
  6749. wlogprint("[E]nable ");
  6750. if (cgpu->deven != DEV_DISABLED)
  6751. wlogprint("[D]isable ");
  6752. if (drv->identify_device)
  6753. wlogprint("[I]dentify ");
  6754. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6755. drv->proc_tui_wlogprint_choices(cgpu);
  6756. wlogprint("\n");
  6757. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6758. _managetui_msg(cgpu->proc_repr, &msg);
  6759. while (true)
  6760. {
  6761. int input = getch();
  6762. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6763. switch (input) {
  6764. case 'd': case 'D':
  6765. if (cgpu->deven == DEV_DISABLED)
  6766. msg = "Processor already disabled\n";
  6767. else
  6768. {
  6769. cgpu->deven = DEV_DISABLED;
  6770. msg = "Processor being disabled\n";
  6771. }
  6772. goto refresh;
  6773. case 'e': case 'E':
  6774. if (cgpu->deven == DEV_ENABLED)
  6775. msg = "Processor already enabled\n";
  6776. else
  6777. {
  6778. proc_enable(cgpu);
  6779. msg = "Processor being enabled\n";
  6780. }
  6781. goto refresh;
  6782. case 'i': case 'I':
  6783. if (drv->identify_device && drv->identify_device(cgpu))
  6784. msg = "Identify command sent\n";
  6785. else
  6786. goto key_default;
  6787. goto refresh;
  6788. case KEY_DOWN:
  6789. if (selected_device >= total_devices - 1)
  6790. break;
  6791. ++selected_device;
  6792. goto devchange;
  6793. case KEY_UP:
  6794. if (selected_device <= 0)
  6795. break;
  6796. --selected_device;
  6797. goto devchange;
  6798. case KEY_NPAGE:
  6799. {
  6800. if (selected_device >= total_devices - 1)
  6801. break;
  6802. struct cgpu_info *mdev = devices[selected_device]->device;
  6803. do {
  6804. ++selected_device;
  6805. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6806. goto devchange;
  6807. }
  6808. case KEY_PPAGE:
  6809. {
  6810. if (selected_device <= 0)
  6811. break;
  6812. struct cgpu_info *mdev = devices[selected_device]->device;
  6813. do {
  6814. --selected_device;
  6815. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6816. goto devchange;
  6817. }
  6818. case '/': case '?': // find device
  6819. {
  6820. static char *pattern = NULL;
  6821. char *newpattern = curses_input("Enter pattern");
  6822. if (newpattern)
  6823. {
  6824. free(pattern);
  6825. pattern = newpattern;
  6826. }
  6827. else
  6828. if (!pattern)
  6829. pattern = calloc(1, 1);
  6830. int match = cgpu_search(pattern, selected_device + 1);
  6831. if (match == -1)
  6832. {
  6833. msg = "Couldn't find device\n";
  6834. goto refresh;
  6835. }
  6836. selected_device = match;
  6837. goto devchange;
  6838. }
  6839. case '+': case '=': // add new device
  6840. {
  6841. addnew:
  6842. clear_logwin();
  6843. _wlogprint(
  6844. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6845. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6846. "For example: erupter:"
  6847. #ifdef WIN32
  6848. "\\\\.\\COM40"
  6849. #elif defined(__APPLE__)
  6850. "/dev/cu.SLAB_USBtoUART"
  6851. #else
  6852. "/dev/ttyUSB39"
  6853. #endif
  6854. "\n"
  6855. );
  6856. char *scanser = curses_input("Enter target");
  6857. if (scan_serial(scanser))
  6858. {
  6859. selected_device = total_devices - 1;
  6860. msg = "Device scan succeeded\n";
  6861. }
  6862. else
  6863. msg = "No new devices found\n";
  6864. goto devchange;
  6865. }
  6866. case 'Q': case 'q':
  6867. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6868. case '\x1b': // ESC
  6869. case KEY_ENTER:
  6870. case '\r': // Ctrl-M on Windows, with nonl
  6871. #ifdef PADENTER
  6872. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6873. #endif
  6874. case '\n':
  6875. goto out;
  6876. default:
  6877. ;
  6878. key_default:
  6879. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6880. {
  6881. msg = drv->proc_tui_handle_choice(cgpu, input);
  6882. if (msg)
  6883. goto refresh;
  6884. }
  6885. }
  6886. }
  6887. out:
  6888. selecting_device = false;
  6889. loginput_mode(0);
  6890. immedok(logwin, false);
  6891. }
  6892. void show_help(void)
  6893. {
  6894. loginput_mode(11);
  6895. // NOTE: wlogprint is a macro with a buffer limit
  6896. _wlogprint(
  6897. "LU: oldest explicit work update currently being used for new work\n"
  6898. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6899. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6900. "E: # shares * diff per 2kB bw | I: expected income | BS: best share ever found\n"
  6901. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6902. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6903. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6904. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6905. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6906. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6907. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE
  6908. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6909. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6910. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6911. "\n"
  6912. "devices/processors hashing (only for totals line), hottest temperature\n"
  6913. );
  6914. wlogprint(
  6915. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6916. , opt_log_interval);
  6917. _wlogprint(
  6918. "A: accepted shares | R: rejected+discarded(% of total)\n"
  6919. "HW: hardware errors / % nonces invalid\n"
  6920. "\n"
  6921. "Press any key to clear"
  6922. );
  6923. logwin_update();
  6924. getch();
  6925. loginput_mode(0);
  6926. }
  6927. static void *input_thread(void __maybe_unused *userdata)
  6928. {
  6929. RenameThread("input");
  6930. if (!curses_active)
  6931. return NULL;
  6932. while (1) {
  6933. int input;
  6934. input = getch();
  6935. switch (input) {
  6936. case 'h': case 'H': case '?':
  6937. case KEY_F(1):
  6938. show_help();
  6939. break;
  6940. case 'q': case 'Q':
  6941. kill_work();
  6942. return NULL;
  6943. case 'd': case 'D':
  6944. display_options();
  6945. break;
  6946. case 'm': case 'M':
  6947. manage_device();
  6948. break;
  6949. case 'p': case 'P':
  6950. display_pools();
  6951. break;
  6952. case 's': case 'S':
  6953. set_options();
  6954. break;
  6955. #ifdef HAVE_CURSES
  6956. case KEY_DOWN:
  6957. {
  6958. const int visible_lines = logcursor - devcursor;
  6959. const int invisible_lines = total_lines - visible_lines;
  6960. if (devsummaryYOffset <= -invisible_lines)
  6961. break;
  6962. devsummaryYOffset -= 2;
  6963. }
  6964. case KEY_UP:
  6965. if (devsummaryYOffset == 0)
  6966. break;
  6967. ++devsummaryYOffset;
  6968. refresh_devstatus();
  6969. break;
  6970. case KEY_NPAGE:
  6971. {
  6972. const int visible_lines = logcursor - devcursor;
  6973. const int invisible_lines = total_lines - visible_lines;
  6974. if (devsummaryYOffset - visible_lines <= -invisible_lines)
  6975. devsummaryYOffset = -invisible_lines;
  6976. else
  6977. devsummaryYOffset -= visible_lines;
  6978. refresh_devstatus();
  6979. break;
  6980. }
  6981. case KEY_PPAGE:
  6982. {
  6983. const int visible_lines = logcursor - devcursor;
  6984. if (devsummaryYOffset + visible_lines >= 0)
  6985. devsummaryYOffset = 0;
  6986. else
  6987. devsummaryYOffset += visible_lines;
  6988. refresh_devstatus();
  6989. break;
  6990. }
  6991. #endif
  6992. }
  6993. if (opt_realquiet) {
  6994. disable_curses();
  6995. break;
  6996. }
  6997. }
  6998. return NULL;
  6999. }
  7000. #endif
  7001. static void *api_thread(void *userdata)
  7002. {
  7003. struct thr_info *mythr = userdata;
  7004. pthread_detach(pthread_self());
  7005. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7006. RenameThread("rpc");
  7007. api(api_thr_id);
  7008. mythr->has_pth = false;
  7009. return NULL;
  7010. }
  7011. void thread_reportin(struct thr_info *thr)
  7012. {
  7013. cgtime(&thr->last);
  7014. thr->cgpu->status = LIFE_WELL;
  7015. thr->getwork = 0;
  7016. thr->cgpu->device_last_well = time(NULL);
  7017. }
  7018. void thread_reportout(struct thr_info *thr)
  7019. {
  7020. thr->getwork = time(NULL);
  7021. }
  7022. static void hashmeter(int thr_id, struct timeval *diff,
  7023. uint64_t hashes_done)
  7024. {
  7025. char logstatusline[256];
  7026. struct timeval temp_tv_end, total_diff;
  7027. double secs;
  7028. double local_secs;
  7029. static double local_mhashes_done = 0;
  7030. double local_mhashes = (double)hashes_done / 1000000.0;
  7031. bool showlog = false;
  7032. char cHr[ALLOC_H2B_NOUNIT+1], aHr[ALLOC_H2B_NOUNIT+1], uHr[ALLOC_H2B_SPACED+3+1];
  7033. char rejpcbuf[6];
  7034. char bnbuf[6];
  7035. struct thr_info *thr;
  7036. /* Update the last time this thread reported in */
  7037. if (thr_id >= 0) {
  7038. thr = get_thread(thr_id);
  7039. cgtime(&(thr->last));
  7040. thr->cgpu->device_last_well = time(NULL);
  7041. }
  7042. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  7043. /* So we can call hashmeter from a non worker thread */
  7044. if (thr_id >= 0) {
  7045. struct cgpu_info *cgpu = thr->cgpu;
  7046. int threadobj = cgpu->threads ?: 1;
  7047. double thread_rolling = 0.0;
  7048. int i;
  7049. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  7050. thr_id, hashes_done, hashes_done / 1000 / secs);
  7051. /* Rolling average for each thread and each device */
  7052. decay_time(&thr->rolling, local_mhashes / secs, secs);
  7053. for (i = 0; i < threadobj; i++)
  7054. thread_rolling += cgpu->thr[i]->rolling;
  7055. mutex_lock(&hash_lock);
  7056. decay_time(&cgpu->rolling, thread_rolling, secs);
  7057. cgpu->total_mhashes += local_mhashes;
  7058. mutex_unlock(&hash_lock);
  7059. // If needed, output detailed, per-device stats
  7060. if (want_per_device_stats) {
  7061. struct timeval now;
  7062. struct timeval elapsed;
  7063. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  7064. cgtime(&now);
  7065. timersub(&now, last_msg_tv, &elapsed);
  7066. if (opt_log_interval <= elapsed.tv_sec) {
  7067. struct cgpu_info *cgpu = thr->cgpu;
  7068. char logline[255];
  7069. *last_msg_tv = now;
  7070. get_statline(logline, sizeof(logline), cgpu);
  7071. if (!curses_active) {
  7072. printf("%s \r", logline);
  7073. fflush(stdout);
  7074. } else
  7075. applog(LOG_INFO, "%s", logline);
  7076. }
  7077. }
  7078. }
  7079. /* Totals are updated by all threads so can race without locking */
  7080. mutex_lock(&hash_lock);
  7081. cgtime(&temp_tv_end);
  7082. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  7083. total_mhashes_done += local_mhashes;
  7084. local_mhashes_done += local_mhashes;
  7085. /* Only update with opt_log_interval */
  7086. if (total_diff.tv_sec < opt_log_interval)
  7087. goto out_unlock;
  7088. showlog = true;
  7089. cgtime(&total_tv_end);
  7090. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  7091. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  7092. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  7093. timersub(&total_tv_end, &total_tv_start, &total_diff);
  7094. total_secs = (double)total_diff.tv_sec +
  7095. ((double)total_diff.tv_usec / 1000000.0);
  7096. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  7097. multi_format_unit_array2(
  7098. ((char*[]){cHr, aHr, uHr}),
  7099. ((size_t[]){sizeof(cHr), sizeof(aHr), sizeof(uHr)}),
  7100. true, "h/s", H2B_SHORT,
  7101. 3,
  7102. 1e6*total_rolling,
  7103. 1e6*total_mhashes_done / total_secs,
  7104. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  7105. int ui_accepted, ui_rejected, ui_stale;
  7106. if (opt_weighed_stats)
  7107. {
  7108. ui_accepted = total_diff_accepted;
  7109. ui_rejected = total_diff_rejected;
  7110. ui_stale = total_diff_stale;
  7111. }
  7112. else
  7113. {
  7114. ui_accepted = total_accepted;
  7115. ui_rejected = total_rejected;
  7116. ui_stale = total_stale;
  7117. }
  7118. #ifdef HAVE_CURSES
  7119. if (curses_active_locked()) {
  7120. float temp = 0;
  7121. struct cgpu_info *proc, *last_working_dev = NULL;
  7122. int i, working_devs = 0, working_procs = 0;
  7123. int divx;
  7124. bool bad = false;
  7125. // Find the highest temperature of all processors
  7126. for (i = 0; i < total_devices; ++i)
  7127. {
  7128. proc = get_devices(i);
  7129. if (proc->temp > temp)
  7130. temp = proc->temp;
  7131. if (unlikely(proc->deven == DEV_DISABLED))
  7132. ; // Just need to block it off from both conditions
  7133. else
  7134. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  7135. {
  7136. if (proc->rolling > .1)
  7137. {
  7138. ++working_procs;
  7139. if (proc->device != last_working_dev)
  7140. {
  7141. ++working_devs;
  7142. last_working_dev = proc->device;
  7143. }
  7144. }
  7145. }
  7146. else
  7147. bad = true;
  7148. }
  7149. if (working_devs == working_procs)
  7150. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  7151. else
  7152. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  7153. divx = 7;
  7154. if (opt_show_procs && !opt_compact)
  7155. ++divx;
  7156. if (bad)
  7157. {
  7158. divx += sizeof(U8_BAD_START)-1;
  7159. strcpy(&statusline[divx], U8_BAD_END);
  7160. divx += sizeof(U8_BAD_END)-1;
  7161. }
  7162. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  7163. format_statline(statusline, sizeof(statusline),
  7164. cHr, aHr,
  7165. uHr,
  7166. ui_accepted,
  7167. ui_rejected,
  7168. ui_stale,
  7169. total_diff_rejected + total_diff_stale, total_diff_accepted,
  7170. hw_errors,
  7171. total_bad_diff1, total_bad_diff1 + total_diff1);
  7172. unlock_curses();
  7173. }
  7174. #endif
  7175. // Add a space
  7176. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  7177. uHr[5] = ' ';
  7178. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  7179. percentf4(bnbuf, sizeof(bnbuf), total_bad_diff1, total_diff1);
  7180. snprintf(logstatusline, sizeof(logstatusline),
  7181. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  7182. want_per_device_stats ? "ALL " : "",
  7183. opt_log_interval,
  7184. cHr, aHr,
  7185. uHr,
  7186. ui_accepted,
  7187. ui_rejected,
  7188. ui_stale,
  7189. rejpcbuf,
  7190. hw_errors,
  7191. bnbuf
  7192. );
  7193. local_mhashes_done = 0;
  7194. out_unlock:
  7195. mutex_unlock(&hash_lock);
  7196. if (showlog) {
  7197. if (!curses_active) {
  7198. printf("%s \r", logstatusline);
  7199. fflush(stdout);
  7200. } else
  7201. applog(LOG_INFO, "%s", logstatusline);
  7202. }
  7203. }
  7204. void hashmeter2(struct thr_info *thr)
  7205. {
  7206. struct timeval tv_now, tv_elapsed;
  7207. timerclear(&thr->tv_hashes_done);
  7208. cgtime(&tv_now);
  7209. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  7210. /* Update the hashmeter at most 5 times per second */
  7211. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  7212. tv_elapsed.tv_sec >= opt_log_interval) {
  7213. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  7214. thr->hashes_done = 0;
  7215. thr->tv_lastupdate = tv_now;
  7216. }
  7217. }
  7218. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  7219. struct stratum_share *sshare)
  7220. {
  7221. struct work *work = sshare->work;
  7222. share_result(val, res_val, err_val, work, false, "");
  7223. }
  7224. /* Parses stratum json responses and tries to find the id that the request
  7225. * matched to and treat it accordingly. */
  7226. bool parse_stratum_response(struct pool *pool, char *s)
  7227. {
  7228. json_t *val = NULL, *err_val, *res_val, *id_val;
  7229. struct stratum_share *sshare;
  7230. json_error_t err;
  7231. bool ret = false;
  7232. int id;
  7233. val = JSON_LOADS(s, &err);
  7234. if (!val) {
  7235. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  7236. goto out;
  7237. }
  7238. res_val = json_object_get(val, "result");
  7239. err_val = json_object_get(val, "error");
  7240. id_val = json_object_get(val, "id");
  7241. if (json_is_null(id_val) || !id_val) {
  7242. char *ss;
  7243. if (err_val)
  7244. ss = json_dumps(err_val, JSON_INDENT(3));
  7245. else
  7246. ss = strdup("(unknown reason)");
  7247. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  7248. free(ss);
  7249. goto out;
  7250. }
  7251. if (!json_is_integer(id_val)) {
  7252. if (json_is_string(id_val)
  7253. && !strncmp(json_string_value(id_val), "txlist", 6))
  7254. {
  7255. const bool is_array = json_is_array(res_val);
  7256. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  7257. is_array ? "transaction list" : "no-transaction-list response",
  7258. pool->pool_no, &json_string_value(id_val)[6]);
  7259. if (!is_array)
  7260. {
  7261. // No need to wait for a timeout
  7262. timer_unset(&pool->swork.tv_transparency);
  7263. pool_set_opaque(pool, true);
  7264. goto fishy;
  7265. }
  7266. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id))
  7267. // We only care about a transaction list for the current job id
  7268. goto fishy;
  7269. // Check that the transactions actually hash to the merkle links
  7270. {
  7271. unsigned maxtx = 1 << pool->swork.merkles;
  7272. unsigned mintx = maxtx >> 1;
  7273. --maxtx;
  7274. unsigned acttx = (unsigned)json_array_size(res_val);
  7275. if (acttx < mintx || acttx > maxtx) {
  7276. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  7277. pool->pool_no, acttx, mintx, maxtx);
  7278. goto fishy;
  7279. }
  7280. // TODO: Check hashes match actual merkle links
  7281. }
  7282. pool_set_opaque(pool, false);
  7283. timer_unset(&pool->swork.tv_transparency);
  7284. fishy:
  7285. ret = true;
  7286. }
  7287. goto out;
  7288. }
  7289. id = json_integer_value(id_val);
  7290. mutex_lock(&sshare_lock);
  7291. HASH_FIND_INT(stratum_shares, &id, sshare);
  7292. if (sshare)
  7293. HASH_DEL(stratum_shares, sshare);
  7294. mutex_unlock(&sshare_lock);
  7295. if (!sshare) {
  7296. double pool_diff;
  7297. /* Since the share is untracked, we can only guess at what the
  7298. * work difficulty is based on the current pool diff. */
  7299. cg_rlock(&pool->data_lock);
  7300. pool_diff = target_diff(pool->swork.target);
  7301. cg_runlock(&pool->data_lock);
  7302. if (json_is_true(res_val)) {
  7303. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  7304. /* We don't know what device this came from so we can't
  7305. * attribute the work to the relevant cgpu */
  7306. mutex_lock(&stats_lock);
  7307. total_accepted++;
  7308. pool->accepted++;
  7309. total_diff_accepted += pool_diff;
  7310. pool->diff_accepted += pool_diff;
  7311. mutex_unlock(&stats_lock);
  7312. } else {
  7313. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  7314. mutex_lock(&stats_lock);
  7315. total_rejected++;
  7316. pool->rejected++;
  7317. total_diff_rejected += pool_diff;
  7318. pool->diff_rejected += pool_diff;
  7319. mutex_unlock(&stats_lock);
  7320. }
  7321. goto out;
  7322. }
  7323. else {
  7324. mutex_lock(&submitting_lock);
  7325. --total_submitting;
  7326. mutex_unlock(&submitting_lock);
  7327. }
  7328. stratum_share_result(val, res_val, err_val, sshare);
  7329. free_work(sshare->work);
  7330. free(sshare);
  7331. ret = true;
  7332. out:
  7333. if (val)
  7334. json_decref(val);
  7335. return ret;
  7336. }
  7337. static void shutdown_stratum(struct pool *pool)
  7338. {
  7339. // Shut down Stratum as if we never had it
  7340. pool->stratum_active = false;
  7341. pool->stratum_init = false;
  7342. pool->has_stratum = false;
  7343. shutdown(pool->sock, SHUT_RDWR);
  7344. free(pool->stratum_url);
  7345. if (pool->sockaddr_url == pool->stratum_url)
  7346. pool->sockaddr_url = NULL;
  7347. pool->stratum_url = NULL;
  7348. }
  7349. void clear_stratum_shares(struct pool *pool)
  7350. {
  7351. int my_mining_threads = mining_threads; // Cached outside of locking
  7352. struct stratum_share *sshare, *tmpshare;
  7353. struct work *work;
  7354. struct cgpu_info *cgpu;
  7355. double diff_cleared = 0;
  7356. double thr_diff_cleared[my_mining_threads];
  7357. int cleared = 0;
  7358. int thr_cleared[my_mining_threads];
  7359. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  7360. for (int i = 0; i < my_mining_threads; ++i)
  7361. {
  7362. thr_diff_cleared[i] = 0;
  7363. thr_cleared[i] = 0;
  7364. }
  7365. mutex_lock(&sshare_lock);
  7366. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7367. work = sshare->work;
  7368. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  7369. HASH_DEL(stratum_shares, sshare);
  7370. sharelog("disconnect", work);
  7371. diff_cleared += sshare->work->work_difficulty;
  7372. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  7373. ++thr_cleared[work->thr_id];
  7374. free_work(sshare->work);
  7375. free(sshare);
  7376. cleared++;
  7377. }
  7378. }
  7379. mutex_unlock(&sshare_lock);
  7380. if (cleared) {
  7381. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  7382. mutex_lock(&stats_lock);
  7383. pool->stale_shares += cleared;
  7384. total_stale += cleared;
  7385. pool->diff_stale += diff_cleared;
  7386. total_diff_stale += diff_cleared;
  7387. for (int i = 0; i < my_mining_threads; ++i)
  7388. if (thr_cleared[i])
  7389. {
  7390. cgpu = get_thr_cgpu(i);
  7391. cgpu->diff_stale += thr_diff_cleared[i];
  7392. cgpu->stale += thr_cleared[i];
  7393. }
  7394. mutex_unlock(&stats_lock);
  7395. mutex_lock(&submitting_lock);
  7396. total_submitting -= cleared;
  7397. mutex_unlock(&submitting_lock);
  7398. }
  7399. }
  7400. static void resubmit_stratum_shares(struct pool *pool)
  7401. {
  7402. struct stratum_share *sshare, *tmpshare;
  7403. struct work *work;
  7404. unsigned resubmitted = 0;
  7405. mutex_lock(&sshare_lock);
  7406. mutex_lock(&submitting_lock);
  7407. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7408. if (sshare->work->pool != pool)
  7409. continue;
  7410. HASH_DEL(stratum_shares, sshare);
  7411. work = sshare->work;
  7412. DL_APPEND(submit_waiting, work);
  7413. free(sshare);
  7414. ++resubmitted;
  7415. }
  7416. mutex_unlock(&submitting_lock);
  7417. mutex_unlock(&sshare_lock);
  7418. if (resubmitted) {
  7419. notifier_wake(submit_waiting_notifier);
  7420. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  7421. }
  7422. }
  7423. static void clear_pool_work(struct pool *pool)
  7424. {
  7425. struct work *work, *tmp;
  7426. int cleared = 0;
  7427. mutex_lock(stgd_lock);
  7428. HASH_ITER(hh, staged_work, work, tmp) {
  7429. if (work->pool == pool) {
  7430. HASH_DEL(staged_work, work);
  7431. free_work(work);
  7432. cleared++;
  7433. staged_full = false;
  7434. }
  7435. }
  7436. mutex_unlock(stgd_lock);
  7437. }
  7438. static int cp_prio(void)
  7439. {
  7440. int prio;
  7441. cg_rlock(&control_lock);
  7442. prio = currentpool->prio;
  7443. cg_runlock(&control_lock);
  7444. return prio;
  7445. }
  7446. /* We only need to maintain a secondary pool connection when we need the
  7447. * capacity to get work from the backup pools while still on the primary */
  7448. static bool cnx_needed(struct pool *pool)
  7449. {
  7450. struct pool *cp;
  7451. if (pool->enabled != POOL_ENABLED)
  7452. return false;
  7453. /* Idle stratum pool needs something to kick it alive again */
  7454. if (pool->has_stratum && pool->idle)
  7455. return true;
  7456. /* Getwork pools without opt_fail_only need backup pools up to be able
  7457. * to leak shares */
  7458. cp = current_pool();
  7459. if (pool_actively_desired(pool, cp))
  7460. return true;
  7461. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7462. return true;
  7463. /* Keep the connection open to allow any stray shares to be submitted
  7464. * on switching pools for 2 minutes. */
  7465. if (timer_elapsed(&pool->tv_last_work_time, NULL) < 120)
  7466. return true;
  7467. /* If the pool has only just come to life and is higher priority than
  7468. * the current pool keep the connection open so we can fail back to
  7469. * it. */
  7470. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7471. return true;
  7472. if (pool_unworkable(cp))
  7473. return true;
  7474. /* We've run out of work, bring anything back to life. */
  7475. if (no_work)
  7476. return true;
  7477. // If the current pool lacks its own block change detection, see if we are needed for that
  7478. if (pool_active_lp_pool(cp) == pool)
  7479. return true;
  7480. return false;
  7481. }
  7482. static void wait_lpcurrent(struct pool *pool);
  7483. static void pool_resus(struct pool *pool);
  7484. static void gen_stratum_work(struct pool *pool, struct work *work);
  7485. static void stratum_resumed(struct pool *pool)
  7486. {
  7487. if (!pool->stratum_notify)
  7488. return;
  7489. if (pool_tclear(pool, &pool->idle)) {
  7490. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7491. pool_resus(pool);
  7492. }
  7493. }
  7494. static bool supports_resume(struct pool *pool)
  7495. {
  7496. bool ret;
  7497. cg_rlock(&pool->data_lock);
  7498. ret = (pool->sessionid != NULL);
  7499. cg_runlock(&pool->data_lock);
  7500. return ret;
  7501. }
  7502. static bool pools_active;
  7503. /* One stratum thread per pool that has stratum waits on the socket checking
  7504. * for new messages and for the integrity of the socket connection. We reset
  7505. * the connection based on the integrity of the receive side only as the send
  7506. * side will eventually expire data it fails to send. */
  7507. static void *stratum_thread(void *userdata)
  7508. {
  7509. struct pool *pool = (struct pool *)userdata;
  7510. pthread_detach(pthread_self());
  7511. char threadname[20];
  7512. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7513. RenameThread(threadname);
  7514. srand(time(NULL) + (intptr_t)userdata);
  7515. while (42) {
  7516. struct timeval timeout;
  7517. int sel_ret;
  7518. fd_set rd;
  7519. char *s;
  7520. int sock;
  7521. if (unlikely(!pool->has_stratum))
  7522. break;
  7523. /* Check to see whether we need to maintain this connection
  7524. * indefinitely or just bring it up when we switch to this
  7525. * pool */
  7526. while (true)
  7527. {
  7528. sock = pool->sock;
  7529. if (sock == INVSOCK)
  7530. applog(LOG_DEBUG, "Pool %u: Invalid socket, suspending",
  7531. pool->pool_no);
  7532. else
  7533. if (!sock_full(pool) && !cnx_needed(pool) && pools_active)
  7534. applog(LOG_DEBUG, "Pool %u: Connection not needed, suspending",
  7535. pool->pool_no);
  7536. else
  7537. break;
  7538. suspend_stratum(pool);
  7539. clear_stratum_shares(pool);
  7540. clear_pool_work(pool);
  7541. wait_lpcurrent(pool);
  7542. if (!restart_stratum(pool)) {
  7543. pool_died(pool);
  7544. while (!restart_stratum(pool)) {
  7545. if (pool->removed)
  7546. goto out;
  7547. cgsleep_ms(30000);
  7548. }
  7549. }
  7550. }
  7551. FD_ZERO(&rd);
  7552. FD_SET(sock, &rd);
  7553. timeout.tv_sec = 120;
  7554. timeout.tv_usec = 0;
  7555. /* If we fail to receive any notify messages for 2 minutes we
  7556. * assume the connection has been dropped and treat this pool
  7557. * as dead */
  7558. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7559. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7560. s = NULL;
  7561. } else
  7562. s = recv_line(pool);
  7563. if (!s) {
  7564. if (!pool->has_stratum)
  7565. break;
  7566. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7567. pool->getfail_occasions++;
  7568. total_go++;
  7569. mutex_lock(&pool->stratum_lock);
  7570. pool->stratum_active = pool->stratum_notify = false;
  7571. pool->sock = INVSOCK;
  7572. mutex_unlock(&pool->stratum_lock);
  7573. /* If the socket to our stratum pool disconnects, all
  7574. * submissions need to be discarded or resent. */
  7575. if (!supports_resume(pool))
  7576. clear_stratum_shares(pool);
  7577. else
  7578. resubmit_stratum_shares(pool);
  7579. clear_pool_work(pool);
  7580. if (pool == current_pool())
  7581. restart_threads();
  7582. if (restart_stratum(pool))
  7583. continue;
  7584. shutdown_stratum(pool);
  7585. pool_died(pool);
  7586. break;
  7587. }
  7588. /* Check this pool hasn't died while being a backup pool and
  7589. * has not had its idle flag cleared */
  7590. stratum_resumed(pool);
  7591. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7592. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7593. free(s);
  7594. if (pool->swork.clean) {
  7595. struct work *work = make_work();
  7596. /* Generate a single work item to update the current
  7597. * block database */
  7598. pool->swork.clean = false;
  7599. gen_stratum_work(pool, work);
  7600. /* Try to extract block height from coinbase scriptSig */
  7601. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7602. unsigned char cb_height_sz;
  7603. cb_height_sz = bin_height[-1];
  7604. if (cb_height_sz == 3) {
  7605. // FIXME: The block number will overflow this by AD 2173
  7606. uint32_t block_id = ((uint32_t*)work->data)[1];
  7607. uint32_t height = 0;
  7608. memcpy(&height, bin_height, 3);
  7609. height = le32toh(height);
  7610. have_block_height(block_id, height);
  7611. }
  7612. pool->swork.work_restart_id =
  7613. ++pool->work_restart_id;
  7614. pool_update_work_restart_time(pool);
  7615. if (test_work_current(work)) {
  7616. /* Only accept a work update if this stratum
  7617. * connection is from the current pool */
  7618. struct pool * const cp = current_pool();
  7619. if (pool == cp)
  7620. restart_threads();
  7621. applog(
  7622. ((!opt_quiet_work_updates) && pool_actively_in_use(pool, cp) ? LOG_NOTICE : LOG_DEBUG),
  7623. "Stratum from pool %d requested work update", pool->pool_no);
  7624. } else
  7625. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7626. free_work(work);
  7627. }
  7628. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7629. // More than 4 timmills past since requested transactions
  7630. timer_unset(&pool->swork.tv_transparency);
  7631. pool_set_opaque(pool, true);
  7632. }
  7633. }
  7634. out:
  7635. return NULL;
  7636. }
  7637. static void init_stratum_thread(struct pool *pool)
  7638. {
  7639. have_longpoll = true;
  7640. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7641. quit(1, "Failed to create stratum thread");
  7642. }
  7643. static void *longpoll_thread(void *userdata);
  7644. static bool stratum_works(struct pool *pool)
  7645. {
  7646. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7647. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7648. return false;
  7649. if (pool->stratum_active)
  7650. return true;
  7651. if (!initiate_stratum(pool))
  7652. return false;
  7653. return true;
  7654. }
  7655. static
  7656. bool pool_recently_got_work(struct pool * const pool, const struct timeval * const tvp_now)
  7657. {
  7658. return (timer_isset(&pool->tv_last_work_time) && timer_elapsed(&pool->tv_last_work_time, tvp_now) < 60);
  7659. }
  7660. static bool pool_active(struct pool *pool, bool pinging)
  7661. {
  7662. struct timeval tv_now, tv_getwork, tv_getwork_reply;
  7663. bool ret = false;
  7664. json_t *val;
  7665. CURL *curl = NULL;
  7666. int rolltime;
  7667. char *rpc_req;
  7668. struct work *work;
  7669. enum pool_protocol proto;
  7670. if (pool->stratum_init)
  7671. {
  7672. if (pool->stratum_active)
  7673. return true;
  7674. }
  7675. else
  7676. if (!pool->idle)
  7677. {
  7678. timer_set_now(&tv_now);
  7679. if (pool_recently_got_work(pool, &tv_now))
  7680. return true;
  7681. }
  7682. mutex_lock(&pool->pool_test_lock);
  7683. if (pool->stratum_init)
  7684. {
  7685. ret = pool->stratum_active;
  7686. goto out;
  7687. }
  7688. timer_set_now(&tv_now);
  7689. if (pool->idle)
  7690. {
  7691. if (timer_elapsed(&pool->tv_idle, &tv_now) < 30)
  7692. goto out;
  7693. }
  7694. else
  7695. if (pool_recently_got_work(pool, &tv_now))
  7696. {
  7697. ret = true;
  7698. goto out;
  7699. }
  7700. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7701. /* This is the central point we activate stratum when we can */
  7702. curl = curl_easy_init();
  7703. if (unlikely(!curl)) {
  7704. applog(LOG_ERR, "CURL initialisation failed");
  7705. goto out;
  7706. }
  7707. if (!(want_gbt || want_getwork))
  7708. goto nohttp;
  7709. work = make_work();
  7710. /* Probe for GBT support on first pass */
  7711. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7712. tryagain:
  7713. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7714. work->pool = pool;
  7715. if (!rpc_req)
  7716. goto out;
  7717. pool->probed = false;
  7718. cgtime(&tv_getwork);
  7719. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7720. true, false, &rolltime, pool, false);
  7721. cgtime(&tv_getwork_reply);
  7722. free(rpc_req);
  7723. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7724. * and if so, switch to that in preference to getwork if it works */
  7725. if (pool->stratum_url && want_stratum && pool_may_redirect_to(pool, pool->stratum_url) && (pool->has_stratum || stratum_works(pool))) {
  7726. if (!pool->has_stratum) {
  7727. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7728. if (!pool->rpc_url)
  7729. pool_set_uri(pool, strdup(pool->stratum_url));
  7730. pool->has_stratum = true;
  7731. }
  7732. free_work(work);
  7733. if (val)
  7734. json_decref(val);
  7735. retry_stratum:
  7736. ;
  7737. /* We create the stratum thread for each pool just after
  7738. * successful authorisation. Once the init flag has been set
  7739. * we never unset it and the stratum thread is responsible for
  7740. * setting/unsetting the active flag */
  7741. bool init = pool_tset(pool, &pool->stratum_init);
  7742. if (!init) {
  7743. ret = initiate_stratum(pool) && auth_stratum(pool);
  7744. if (ret)
  7745. {
  7746. detect_algo = 2;
  7747. init_stratum_thread(pool);
  7748. }
  7749. else
  7750. {
  7751. pool_tclear(pool, &pool->stratum_init);
  7752. pool->tv_idle = tv_getwork_reply;
  7753. }
  7754. goto out;
  7755. }
  7756. ret = pool->stratum_active;
  7757. goto out;
  7758. }
  7759. else if (pool->has_stratum)
  7760. shutdown_stratum(pool);
  7761. if (val) {
  7762. bool rc;
  7763. json_t *res;
  7764. res = json_object_get(val, "result");
  7765. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7766. goto badwork;
  7767. work->rolltime = rolltime;
  7768. rc = work_decode(pool, work, val);
  7769. if (rc) {
  7770. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7771. pool->pool_no, pool->rpc_url);
  7772. work->pool = pool;
  7773. copy_time(&work->tv_getwork, &tv_getwork);
  7774. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7775. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7776. calc_diff(work, 0);
  7777. update_last_work(work);
  7778. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7779. stage_work(work);
  7780. total_getworks++;
  7781. pool->getwork_requested++;
  7782. ret = true;
  7783. pool->tv_idle = tv_getwork_reply;
  7784. } else {
  7785. badwork:
  7786. json_decref(val);
  7787. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7788. pool->pool_no, pool->rpc_url);
  7789. pool->proto = proto = pool_protocol_fallback(proto);
  7790. if (PLP_NONE != proto)
  7791. goto tryagain;
  7792. pool->tv_idle = tv_getwork_reply;
  7793. free_work(work);
  7794. goto out;
  7795. }
  7796. json_decref(val);
  7797. if (proto != pool->proto) {
  7798. pool->proto = proto;
  7799. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7800. }
  7801. if (pool->lp_url)
  7802. goto out;
  7803. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7804. const struct blktmpl_longpoll_req *lp;
  7805. if (work->tr && (lp = blktmpl_get_longpoll(work->tr->tmpl))) {
  7806. // NOTE: work_decode takes care of lp id
  7807. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7808. if (!pool->lp_url)
  7809. {
  7810. ret = false;
  7811. goto out;
  7812. }
  7813. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7814. }
  7815. else
  7816. if (pool->hdr_path && want_getwork) {
  7817. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7818. if (!pool->lp_url)
  7819. {
  7820. ret = false;
  7821. goto out;
  7822. }
  7823. pool->lp_proto = PLP_GETWORK;
  7824. } else
  7825. pool->lp_url = NULL;
  7826. if (want_longpoll && !pool->lp_started) {
  7827. pool->lp_started = true;
  7828. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7829. quit(1, "Failed to create pool longpoll thread");
  7830. }
  7831. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7832. pool->proto = proto;
  7833. goto tryagain;
  7834. } else {
  7835. pool->tv_idle = tv_getwork_reply;
  7836. free_work(work);
  7837. nohttp:
  7838. /* If we failed to parse a getwork, this could be a stratum
  7839. * url without the prefix stratum+tcp:// so let's check it */
  7840. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7841. pool->has_stratum = true;
  7842. goto retry_stratum;
  7843. }
  7844. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7845. pool->pool_no, pool->rpc_url);
  7846. if (!pinging)
  7847. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7848. }
  7849. out:
  7850. if (curl)
  7851. curl_easy_cleanup(curl);
  7852. mutex_unlock(&pool->pool_test_lock);
  7853. return ret;
  7854. }
  7855. static void pool_resus(struct pool *pool)
  7856. {
  7857. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7858. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7859. else
  7860. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7861. }
  7862. static struct work *hash_pop(void)
  7863. {
  7864. struct work *work = NULL, *tmp;
  7865. int hc;
  7866. struct timespec ts;
  7867. retry:
  7868. mutex_lock(stgd_lock);
  7869. while (!HASH_COUNT(staged_work))
  7870. {
  7871. if (unlikely(staged_full))
  7872. {
  7873. if (likely(opt_queue < 10 + mining_threads))
  7874. {
  7875. ++opt_queue;
  7876. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7877. }
  7878. else
  7879. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7880. staged_full = false; // Let it fill up before triggering an underrun again
  7881. no_work = true;
  7882. }
  7883. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7884. pthread_cond_signal(&gws_cond);
  7885. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7886. {
  7887. run_cmd(cmd_idle);
  7888. pthread_cond_signal(&gws_cond);
  7889. pthread_cond_wait(&getq->cond, stgd_lock);
  7890. }
  7891. }
  7892. no_work = false;
  7893. hc = HASH_COUNT(staged_work);
  7894. /* Find clone work if possible, to allow masters to be reused */
  7895. if (hc > staged_rollable) {
  7896. HASH_ITER(hh, staged_work, work, tmp) {
  7897. if (!work_rollable(work))
  7898. break;
  7899. }
  7900. } else
  7901. work = staged_work;
  7902. if (can_roll(work) && should_roll(work))
  7903. {
  7904. // Instead of consuming it, force it to be cloned and grab the clone
  7905. mutex_unlock(stgd_lock);
  7906. clone_available();
  7907. goto retry;
  7908. }
  7909. HASH_DEL(staged_work, work);
  7910. if (work_rollable(work))
  7911. staged_rollable--;
  7912. /* Signal the getwork scheduler to look for more work */
  7913. pthread_cond_signal(&gws_cond);
  7914. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7915. pthread_cond_signal(&getq->cond);
  7916. mutex_unlock(stgd_lock);
  7917. work->pool->last_work_time = time(NULL);
  7918. cgtime(&work->pool->tv_last_work_time);
  7919. return work;
  7920. }
  7921. /* Clones work by rolling it if possible, and returning a clone instead of the
  7922. * original work item which gets staged again to possibly be rolled again in
  7923. * the future */
  7924. static struct work *clone_work(struct work *work)
  7925. {
  7926. int mrs = mining_threads + opt_queue - total_staged();
  7927. struct work *work_clone;
  7928. bool cloned;
  7929. if (mrs < 1)
  7930. return work;
  7931. cloned = false;
  7932. work_clone = make_clone(work);
  7933. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7934. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7935. stage_work(work_clone);
  7936. roll_work(work);
  7937. work_clone = make_clone(work);
  7938. /* Roll it again to prevent duplicates should this be used
  7939. * directly later on */
  7940. roll_work(work);
  7941. cloned = true;
  7942. }
  7943. if (cloned) {
  7944. stage_work(work);
  7945. return work_clone;
  7946. }
  7947. free_work(work_clone);
  7948. return work;
  7949. }
  7950. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7951. {
  7952. unsigned char hash1[32];
  7953. sha256(data, len, hash1);
  7954. sha256(hash1, 32, hash);
  7955. }
  7956. /* PDiff 1 is a 256 bit unsigned integer of
  7957. * 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff
  7958. * so we use a big endian 32 bit unsigned integer positioned at the Nth byte to
  7959. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7960. static void pdiff_target_leadzero(void * const target_p, double diff)
  7961. {
  7962. uint8_t *target = target_p;
  7963. diff *= 0x100000000;
  7964. int skip = log2(diff) / 8;
  7965. if (skip)
  7966. {
  7967. if (skip > 0x1c)
  7968. skip = 0x1c;
  7969. diff /= pow(0x100, skip);
  7970. memset(target, 0, skip);
  7971. }
  7972. uint32_t n = 0xffffffff;
  7973. n = (double)n / diff;
  7974. n = htobe32(n);
  7975. memcpy(&target[skip], &n, sizeof(n));
  7976. memset(&target[skip + sizeof(n)], 0xff, 32 - (skip + sizeof(n)));
  7977. }
  7978. void set_target_to_pdiff(void * const dest_target, const double pdiff)
  7979. {
  7980. unsigned char rtarget[32];
  7981. pdiff_target_leadzero(rtarget, pdiff);
  7982. swab256(dest_target, rtarget);
  7983. if (opt_debug) {
  7984. char htarget[65];
  7985. bin2hex(htarget, rtarget, 32);
  7986. applog(LOG_DEBUG, "Generated target %s", htarget);
  7987. }
  7988. }
  7989. void set_target_to_bdiff(void * const dest_target, const double bdiff)
  7990. {
  7991. set_target_to_pdiff(dest_target, bdiff_to_pdiff(bdiff));
  7992. }
  7993. void _test_target(void * const funcp, const char * const funcname, const bool little_endian, const void * const expectp, const double diff)
  7994. {
  7995. uint8_t bufr[32], buf[32], expectr[32], expect[32];
  7996. int off;
  7997. void (*func)(void *, double) = funcp;
  7998. func(little_endian ? bufr : buf, diff);
  7999. if (little_endian)
  8000. swab256(buf, bufr);
  8001. swap32tobe(expect, expectp, 256/32);
  8002. // Fuzzy comparison: the first 32 bits set must match, and the actual target must be >= the expected
  8003. for (off = 0; off < 28 && !buf[off]; ++off)
  8004. {}
  8005. if (memcmp(&buf[off], &expect[off], 4))
  8006. {
  8007. testfail: ;
  8008. char hexbuf[65], expectbuf[65];
  8009. bin2hex(hexbuf, buf, 32);
  8010. bin2hex(expectbuf, expect, 32);
  8011. applogr(, LOG_WARNING, "%s test failed: diff %g got %s (expected %s)",
  8012. funcname, diff, hexbuf, expectbuf);
  8013. }
  8014. if (!little_endian)
  8015. swab256(bufr, buf);
  8016. swab256(expectr, expect);
  8017. if (!hash_target_check(expectr, bufr))
  8018. goto testfail;
  8019. }
  8020. #define TEST_TARGET(func, le, expect, diff) \
  8021. _test_target(func, #func, le, expect, diff)
  8022. void test_target()
  8023. {
  8024. uint32_t expect[8] = {0};
  8025. // bdiff 1 should be exactly 00000000ffff0000000006f29cfd29510a6caee84634e86a57257cf03152537f due to floating-point imprecision (pdiff1 / 1.0000152590218966)
  8026. expect[0] = 0x0000ffff;
  8027. TEST_TARGET(set_target_to_bdiff, true, expect, 1./0x10000);
  8028. expect[0] = 0;
  8029. expect[1] = 0xffff0000;
  8030. TEST_TARGET(set_target_to_bdiff, true, expect, 1);
  8031. expect[1] >>= 1;
  8032. TEST_TARGET(set_target_to_bdiff, true, expect, 2);
  8033. expect[1] >>= 3;
  8034. TEST_TARGET(set_target_to_bdiff, true, expect, 0x10);
  8035. expect[1] >>= 4;
  8036. TEST_TARGET(set_target_to_bdiff, true, expect, 0x100);
  8037. memset(&expect[1], '\xff', 28);
  8038. expect[0] = 0x0000ffff;
  8039. TEST_TARGET(set_target_to_pdiff, true, expect, 1./0x10000);
  8040. expect[0] = 0;
  8041. TEST_TARGET(set_target_to_pdiff, true, expect, 1);
  8042. expect[1] >>= 1;
  8043. TEST_TARGET(set_target_to_pdiff, true, expect, 2);
  8044. expect[1] >>= 3;
  8045. TEST_TARGET(set_target_to_pdiff, true, expect, 0x10);
  8046. expect[1] >>= 4;
  8047. TEST_TARGET(set_target_to_pdiff, true, expect, 0x100);
  8048. }
  8049. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  8050. {
  8051. *dst = *src;
  8052. if (dst->tr)
  8053. tmpl_incref(dst->tr);
  8054. dst->nonce1 = maybe_strdup(src->nonce1);
  8055. dst->job_id = maybe_strdup(src->job_id);
  8056. bytes_cpy(&dst->coinbase, &src->coinbase);
  8057. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  8058. }
  8059. void stratum_work_clean(struct stratum_work * const swork)
  8060. {
  8061. if (swork->tr)
  8062. tmpl_decref(swork->tr);
  8063. free(swork->nonce1);
  8064. free(swork->job_id);
  8065. bytes_free(&swork->coinbase);
  8066. bytes_free(&swork->merkle_bin);
  8067. }
  8068. bool pool_has_usable_swork(const struct pool * const pool)
  8069. {
  8070. if (opt_benchmark)
  8071. return true;
  8072. if (pool->swork.tr)
  8073. {
  8074. // GBT
  8075. struct timeval tv_now;
  8076. timer_set_now(&tv_now);
  8077. return blkmk_time_left(pool->swork.tr->tmpl, tv_now.tv_sec);
  8078. }
  8079. return pool->stratum_notify;
  8080. }
  8081. /* Generates stratum based work based on the most recent notify information
  8082. * from the pool. This will keep generating work while a pool is down so we use
  8083. * other means to detect when the pool has died in stratum_thread */
  8084. static void gen_stratum_work(struct pool *pool, struct work *work)
  8085. {
  8086. clean_work(work);
  8087. cg_wlock(&pool->data_lock);
  8088. pool->swork.data_lock_p = &pool->data_lock;
  8089. const int n2size = pool->swork.n2size;
  8090. bytes_resize(&work->nonce2, n2size);
  8091. if (pool->nonce2sz < n2size)
  8092. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, n2size - pool->nonce2sz);
  8093. memcpy(bytes_buf(&work->nonce2),
  8094. #ifdef WORDS_BIGENDIAN
  8095. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  8096. &((char*)&pool->nonce2)[pool->nonce2off],
  8097. #else
  8098. &pool->nonce2,
  8099. #endif
  8100. pool->nonce2sz);
  8101. pool->nonce2++;
  8102. work->pool = pool;
  8103. work->work_restart_id = pool->swork.work_restart_id;
  8104. gen_stratum_work2(work, &pool->swork);
  8105. cgtime(&work->tv_staged);
  8106. }
  8107. void gen_stratum_work2(struct work *work, struct stratum_work *swork)
  8108. {
  8109. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  8110. uint8_t *merkle_bin;
  8111. uint32_t *data32, *swap32;
  8112. int i;
  8113. /* Generate coinbase */
  8114. coinbase = bytes_buf(&swork->coinbase);
  8115. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8116. /* Downgrade to a read lock to read off the variables */
  8117. if (swork->data_lock_p)
  8118. cg_dwlock(swork->data_lock_p);
  8119. /* Generate merkle root */
  8120. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  8121. memcpy(merkle_sha, merkle_root, 32);
  8122. merkle_bin = bytes_buf(&swork->merkle_bin);
  8123. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  8124. memcpy(merkle_sha + 32, merkle_bin, 32);
  8125. gen_hash(merkle_sha, merkle_root, 64);
  8126. memcpy(merkle_sha, merkle_root, 32);
  8127. }
  8128. data32 = (uint32_t *)merkle_sha;
  8129. swap32 = (uint32_t *)merkle_root;
  8130. flip32(swap32, data32);
  8131. memcpy(&work->data[0], swork->header1, 36);
  8132. memcpy(&work->data[36], merkle_root, 32);
  8133. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  8134. memcpy(&work->data[72], swork->diffbits, 4);
  8135. memset(&work->data[76], 0, 4); // nonce
  8136. memcpy(&work->data[80], workpadding_bin, 48);
  8137. work->ntime_roll_limits = swork->ntime_roll_limits;
  8138. /* Copy parameters required for share submission */
  8139. memcpy(work->target, swork->target, sizeof(work->target));
  8140. work->job_id = maybe_strdup(swork->job_id);
  8141. work->nonce1 = maybe_strdup(swork->nonce1);
  8142. if (swork->data_lock_p)
  8143. cg_runlock(swork->data_lock_p);
  8144. if (opt_debug)
  8145. {
  8146. char header[161];
  8147. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  8148. bin2hex(header, work->data, 80);
  8149. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  8150. applog(LOG_DEBUG, "Generated stratum header %s", header);
  8151. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  8152. }
  8153. calc_midstate(work);
  8154. local_work++;
  8155. work->stratum = true;
  8156. work->blk.nonce = 0;
  8157. work->id = total_work++;
  8158. work->longpoll = false;
  8159. work->getwork_mode = GETWORK_MODE_STRATUM;
  8160. calc_diff(work, 0);
  8161. }
  8162. void request_work(struct thr_info *thr)
  8163. {
  8164. struct cgpu_info *cgpu = thr->cgpu;
  8165. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8166. /* Tell the watchdog thread this thread is waiting on getwork and
  8167. * should not be restarted */
  8168. thread_reportout(thr);
  8169. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  8170. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8171. {
  8172. if (proc->threads)
  8173. break;
  8174. thread_reportout(proc->thr[0]);
  8175. }
  8176. cgtime(&dev_stats->_get_start);
  8177. }
  8178. // FIXME: Make this non-blocking (and remove HACK above)
  8179. struct work *get_work(struct thr_info *thr)
  8180. {
  8181. const int thr_id = thr->id;
  8182. struct cgpu_info *cgpu = thr->cgpu;
  8183. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  8184. struct cgminer_stats *pool_stats;
  8185. struct timeval tv_get;
  8186. struct work *work = NULL;
  8187. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  8188. while (!work) {
  8189. work = hash_pop();
  8190. if (stale_work(work, false)) {
  8191. staged_full = false; // It wasn't really full, since it was stale :(
  8192. discard_work(work);
  8193. work = NULL;
  8194. wake_gws();
  8195. }
  8196. }
  8197. last_getwork = time(NULL);
  8198. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  8199. cgpu->proc_repr, work->id, thr_id);
  8200. work->thr_id = thr_id;
  8201. thread_reportin(thr);
  8202. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  8203. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  8204. {
  8205. if (proc->threads)
  8206. break;
  8207. thread_reportin(proc->thr[0]);
  8208. }
  8209. work->mined = true;
  8210. work->blk.nonce = 0;
  8211. cgtime(&tv_get);
  8212. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  8213. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  8214. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  8215. dev_stats->getwork_wait_max = tv_get;
  8216. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  8217. dev_stats->getwork_wait_min = tv_get;
  8218. ++dev_stats->getwork_calls;
  8219. pool_stats = &(work->pool->cgminer_stats);
  8220. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  8221. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  8222. pool_stats->getwork_wait_max = tv_get;
  8223. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  8224. pool_stats->getwork_wait_min = tv_get;
  8225. ++pool_stats->getwork_calls;
  8226. if (work->work_difficulty < 1)
  8227. {
  8228. if (unlikely(work->work_difficulty < cgpu->min_nonce_diff))
  8229. {
  8230. if (cgpu->min_nonce_diff - work->work_difficulty > 1./0x10000000)
  8231. applog(LOG_WARNING, "%"PRIpreprv": Using work with lower difficulty than device supports",
  8232. cgpu->proc_repr);
  8233. work->nonce_diff = cgpu->min_nonce_diff;
  8234. }
  8235. else
  8236. work->nonce_diff = work->work_difficulty;
  8237. }
  8238. else
  8239. work->nonce_diff = 1;
  8240. return work;
  8241. }
  8242. static
  8243. void _submit_work_async(struct work *work)
  8244. {
  8245. applog(LOG_DEBUG, "Pushing submit work to work thread");
  8246. if (opt_benchmark)
  8247. {
  8248. json_t * const jn = json_null();
  8249. work_check_for_block(work);
  8250. share_result(jn, jn, jn, work, false, "");
  8251. free_work(work);
  8252. return;
  8253. }
  8254. mutex_lock(&submitting_lock);
  8255. ++total_submitting;
  8256. DL_APPEND(submit_waiting, work);
  8257. mutex_unlock(&submitting_lock);
  8258. notifier_wake(submit_waiting_notifier);
  8259. }
  8260. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  8261. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  8262. {
  8263. if (tv_work_found)
  8264. copy_time(&work->tv_work_found, tv_work_found);
  8265. _submit_work_async(work);
  8266. }
  8267. void inc_hw_errors3(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p, float nonce_diff)
  8268. {
  8269. struct cgpu_info * const cgpu = thr->cgpu;
  8270. if (bad_nonce_p)
  8271. {
  8272. if (bad_nonce_p == UNKNOWN_NONCE)
  8273. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  8274. cgpu->proc_repr);
  8275. else
  8276. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  8277. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  8278. }
  8279. mutex_lock(&stats_lock);
  8280. hw_errors++;
  8281. ++cgpu->hw_errors;
  8282. if (bad_nonce_p)
  8283. {
  8284. total_bad_diff1 += nonce_diff;
  8285. cgpu->bad_diff1 += nonce_diff;
  8286. }
  8287. mutex_unlock(&stats_lock);
  8288. if (thr->cgpu->drv->hw_error)
  8289. thr->cgpu->drv->hw_error(thr);
  8290. }
  8291. void work_hash(struct work * const work)
  8292. {
  8293. #ifdef USE_SCRYPT
  8294. if (opt_scrypt)
  8295. scrypt_hash_data(work->hash, work->data);
  8296. else
  8297. #endif
  8298. hash_data(work->hash, work->data);
  8299. }
  8300. static
  8301. bool test_hash(const void * const phash, const float diff)
  8302. {
  8303. const uint32_t * const hash = phash;
  8304. if (diff >= 1.)
  8305. // FIXME: > 1 should check more
  8306. return !hash[7];
  8307. const uint32_t Htarg = (uint32_t)(0x100000000 * diff) - 1;
  8308. const uint32_t tmp_hash7 = le32toh(hash[7]);
  8309. applog(LOG_DEBUG, "htarget %08lx hash %08lx",
  8310. (long unsigned int)Htarg,
  8311. (long unsigned int)tmp_hash7);
  8312. return (tmp_hash7 <= Htarg);
  8313. }
  8314. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  8315. {
  8316. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8317. *work_nonce = htole32(nonce);
  8318. work_hash(work);
  8319. if (!test_hash(work->hash, work->nonce_diff))
  8320. return TNR_BAD;
  8321. if (checktarget && !hash_target_check_v(work->hash, work->target))
  8322. {
  8323. bool high_hash = true;
  8324. struct pool * const pool = work->pool;
  8325. if (pool->stratum_active)
  8326. {
  8327. // 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
  8328. if (memcmp(pool->swork.target, work->target, sizeof(work->target)))
  8329. {
  8330. applog(LOG_DEBUG, "Stratum pool %u target has changed since work job issued, checking that too",
  8331. pool->pool_no);
  8332. if (hash_target_check_v(work->hash, pool->swork.target))
  8333. high_hash = false;
  8334. }
  8335. }
  8336. if (high_hash)
  8337. return TNR_HIGH;
  8338. }
  8339. return TNR_GOOD;
  8340. }
  8341. /* Returns true if nonce for work was a valid share */
  8342. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  8343. {
  8344. return submit_noffset_nonce(thr, work, nonce, 0);
  8345. }
  8346. /* Allows drivers to submit work items where the driver has changed the ntime
  8347. * value by noffset. Must be only used with a work protocol that does not ntime
  8348. * roll itself intrinsically to generate work (eg stratum). We do not touch
  8349. * the original work struct, but the copy of it only. */
  8350. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  8351. int noffset)
  8352. {
  8353. struct work *work = make_work();
  8354. _copy_work(work, work_in, noffset);
  8355. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  8356. struct timeval tv_work_found;
  8357. enum test_nonce2_result res;
  8358. bool ret = true;
  8359. thread_reportout(thr);
  8360. cgtime(&tv_work_found);
  8361. *work_nonce = htole32(nonce);
  8362. work->thr_id = thr->id;
  8363. /* Do one last check before attempting to submit the work */
  8364. /* Side effect: sets work->data and work->hash for us */
  8365. res = test_nonce2(work, nonce);
  8366. if (unlikely(res == TNR_BAD))
  8367. {
  8368. inc_hw_errors(thr, work, nonce);
  8369. ret = false;
  8370. goto out;
  8371. }
  8372. mutex_lock(&stats_lock);
  8373. total_diff1 += work->nonce_diff;
  8374. thr ->cgpu->diff1 += work->nonce_diff;
  8375. work->pool->diff1 += work->nonce_diff;
  8376. thr->cgpu->last_device_valid_work = time(NULL);
  8377. mutex_unlock(&stats_lock);
  8378. if (noncelog_file)
  8379. noncelog(work);
  8380. if (res == TNR_HIGH)
  8381. {
  8382. // Share above target, normal
  8383. /* Check the diff of the share, even if it didn't reach the
  8384. * target, just to set the best share value if it's higher. */
  8385. share_diff(work);
  8386. goto out;
  8387. }
  8388. submit_work_async2(work, &tv_work_found);
  8389. work = NULL; // Taken by submit_work_async2
  8390. out:
  8391. if (work)
  8392. free_work(work);
  8393. thread_reportin(thr);
  8394. return ret;
  8395. }
  8396. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  8397. {
  8398. if (wdiff->tv_sec > opt_scantime ||
  8399. work->blk.nonce >= 0xfffffffe - hashes ||
  8400. hashes >= 0xfffffffe ||
  8401. stale_work(work, false))
  8402. return true;
  8403. return false;
  8404. }
  8405. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  8406. {
  8407. struct cgpu_info *proc = thr->cgpu;
  8408. if (proc->threads > 1)
  8409. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  8410. else
  8411. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  8412. }
  8413. // Called by asynchronous minerloops, when they find their processor should be disabled
  8414. void mt_disable_start(struct thr_info *mythr)
  8415. {
  8416. struct cgpu_info *cgpu = mythr->cgpu;
  8417. struct device_drv *drv = cgpu->drv;
  8418. if (drv->thread_disable)
  8419. drv->thread_disable(mythr);
  8420. hashmeter2(mythr);
  8421. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  8422. mythr->rolling = mythr->cgpu->rolling = 0;
  8423. thread_reportout(mythr);
  8424. mythr->_mt_disable_called = true;
  8425. }
  8426. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  8427. * the driver tells us it's full so that it may extract the work item using
  8428. * the get_queued() function which adds it to the hashtable on
  8429. * cgpu->queued_work. */
  8430. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  8431. {
  8432. thread_reportout(mythr);
  8433. do {
  8434. bool need_work;
  8435. /* Do this lockless just to know if we need more unqueued work. */
  8436. need_work = (!cgpu->unqueued_work);
  8437. /* get_work is a blocking function so do it outside of lock
  8438. * to prevent deadlocks with other locks. */
  8439. if (need_work) {
  8440. struct work *work = get_work(mythr);
  8441. wr_lock(&cgpu->qlock);
  8442. /* Check we haven't grabbed work somehow between
  8443. * checking and picking up the lock. */
  8444. if (likely(!cgpu->unqueued_work))
  8445. cgpu->unqueued_work = work;
  8446. else
  8447. need_work = false;
  8448. wr_unlock(&cgpu->qlock);
  8449. if (unlikely(!need_work))
  8450. discard_work(work);
  8451. }
  8452. /* The queue_full function should be used by the driver to
  8453. * actually place work items on the physical device if it
  8454. * does have a queue. */
  8455. } while (drv->queue_full && !drv->queue_full(cgpu));
  8456. }
  8457. /* Add a work item to a cgpu's queued hashlist */
  8458. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  8459. {
  8460. cgpu->queued_count++;
  8461. HASH_ADD_INT(cgpu->queued_work, id, work);
  8462. }
  8463. /* This function is for retrieving one work item from the unqueued pointer and
  8464. * adding it to the hashtable of queued work. Code using this function must be
  8465. * able to handle NULL as a return which implies there is no work available. */
  8466. struct work *get_queued(struct cgpu_info *cgpu)
  8467. {
  8468. struct work *work = NULL;
  8469. wr_lock(&cgpu->qlock);
  8470. if (cgpu->unqueued_work) {
  8471. work = cgpu->unqueued_work;
  8472. if (unlikely(stale_work(work, false))) {
  8473. discard_work(work);
  8474. work = NULL;
  8475. wake_gws();
  8476. } else
  8477. __add_queued(cgpu, work);
  8478. cgpu->unqueued_work = NULL;
  8479. }
  8480. wr_unlock(&cgpu->qlock);
  8481. return work;
  8482. }
  8483. void add_queued(struct cgpu_info *cgpu, struct work *work)
  8484. {
  8485. wr_lock(&cgpu->qlock);
  8486. __add_queued(cgpu, work);
  8487. wr_unlock(&cgpu->qlock);
  8488. }
  8489. /* Get fresh work and add it to cgpu's queued hashlist */
  8490. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  8491. {
  8492. struct work *work = get_work(thr);
  8493. add_queued(cgpu, work);
  8494. return work;
  8495. }
  8496. /* This function is for finding an already queued work item in the
  8497. * given que hashtable. Code using this function must be able
  8498. * to handle NULL as a return which implies there is no matching work.
  8499. * The calling function must lock access to the que if it is required.
  8500. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8501. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8502. {
  8503. struct work *work, *tmp, *ret = NULL;
  8504. HASH_ITER(hh, que, work, tmp) {
  8505. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  8506. memcmp(work->data + offset, data, datalen) == 0) {
  8507. ret = work;
  8508. break;
  8509. }
  8510. }
  8511. return ret;
  8512. }
  8513. /* This function is for finding an already queued work item in the
  8514. * device's queued_work hashtable. Code using this function must be able
  8515. * to handle NULL as a return which implies there is no matching work.
  8516. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  8517. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8518. {
  8519. struct work *ret;
  8520. rd_lock(&cgpu->qlock);
  8521. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8522. rd_unlock(&cgpu->qlock);
  8523. return ret;
  8524. }
  8525. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8526. {
  8527. struct work *work, *ret = NULL;
  8528. rd_lock(&cgpu->qlock);
  8529. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8530. if (work)
  8531. ret = copy_work(work);
  8532. rd_unlock(&cgpu->qlock);
  8533. return ret;
  8534. }
  8535. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  8536. {
  8537. cgpu->queued_count--;
  8538. HASH_DEL(cgpu->queued_work, work);
  8539. }
  8540. /* This function should be used by queued device drivers when they're sure
  8541. * the work struct is no longer in use. */
  8542. void work_completed(struct cgpu_info *cgpu, struct work *work)
  8543. {
  8544. wr_lock(&cgpu->qlock);
  8545. __work_completed(cgpu, work);
  8546. wr_unlock(&cgpu->qlock);
  8547. free_work(work);
  8548. }
  8549. /* Combines find_queued_work_bymidstate and work_completed in one function
  8550. * withOUT destroying the work so the driver must free it. */
  8551. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  8552. {
  8553. struct work *work;
  8554. wr_lock(&cgpu->qlock);
  8555. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  8556. if (work)
  8557. __work_completed(cgpu, work);
  8558. wr_unlock(&cgpu->qlock);
  8559. return work;
  8560. }
  8561. static void flush_queue(struct cgpu_info *cgpu)
  8562. {
  8563. struct work *work = NULL;
  8564. wr_lock(&cgpu->qlock);
  8565. work = cgpu->unqueued_work;
  8566. cgpu->unqueued_work = NULL;
  8567. wr_unlock(&cgpu->qlock);
  8568. if (work) {
  8569. free_work(work);
  8570. applog(LOG_DEBUG, "Discarded queued work item");
  8571. }
  8572. }
  8573. /* This version of hash work is for devices that are fast enough to always
  8574. * perform a full nonce range and need a queue to maintain the device busy.
  8575. * Work creation and destruction is not done from within this function
  8576. * directly. */
  8577. void hash_queued_work(struct thr_info *mythr)
  8578. {
  8579. const long cycle = opt_log_interval / 5 ? : 1;
  8580. struct timeval tv_start = {0, 0}, tv_end;
  8581. struct cgpu_info *cgpu = mythr->cgpu;
  8582. struct device_drv *drv = cgpu->drv;
  8583. const int thr_id = mythr->id;
  8584. int64_t hashes_done = 0;
  8585. if (unlikely(cgpu->deven != DEV_ENABLED))
  8586. mt_disable(mythr);
  8587. while (likely(!cgpu->shutdown)) {
  8588. struct timeval diff;
  8589. int64_t hashes;
  8590. fill_queue(mythr, cgpu, drv, thr_id);
  8591. thread_reportin(mythr);
  8592. hashes = drv->scanwork(mythr);
  8593. /* Reset the bool here in case the driver looks for it
  8594. * synchronously in the scanwork loop. */
  8595. mythr->work_restart = false;
  8596. if (unlikely(hashes == -1 )) {
  8597. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  8598. cgpu->deven = DEV_DISABLED;
  8599. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  8600. mt_disable(mythr);
  8601. }
  8602. hashes_done += hashes;
  8603. cgtime(&tv_end);
  8604. timersub(&tv_end, &tv_start, &diff);
  8605. if (diff.tv_sec >= cycle) {
  8606. hashmeter(thr_id, &diff, hashes_done);
  8607. hashes_done = 0;
  8608. copy_time(&tv_start, &tv_end);
  8609. }
  8610. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  8611. mt_disable(mythr);
  8612. if (unlikely(mythr->work_restart)) {
  8613. flush_queue(cgpu);
  8614. if (drv->flush_work)
  8615. drv->flush_work(cgpu);
  8616. }
  8617. }
  8618. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8619. }
  8620. // Called by minerloop, when it is re-enabling a processor
  8621. void mt_disable_finish(struct thr_info *mythr)
  8622. {
  8623. struct device_drv *drv = mythr->cgpu->drv;
  8624. thread_reportin(mythr);
  8625. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8626. if (drv->thread_enable)
  8627. drv->thread_enable(mythr);
  8628. mythr->_mt_disable_called = false;
  8629. }
  8630. // Called by synchronous minerloops, when they find their processor should be disabled
  8631. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8632. void mt_disable(struct thr_info *mythr)
  8633. {
  8634. const struct cgpu_info * const cgpu = mythr->cgpu;
  8635. mt_disable_start(mythr);
  8636. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8637. do {
  8638. notifier_read(mythr->notifier);
  8639. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8640. mt_disable_finish(mythr);
  8641. }
  8642. enum {
  8643. STAT_SLEEP_INTERVAL = 1,
  8644. STAT_CTR_INTERVAL = 10000000,
  8645. FAILURE_INTERVAL = 30,
  8646. };
  8647. /* Stage another work item from the work returned in a longpoll */
  8648. 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)
  8649. {
  8650. bool rc;
  8651. work->rolltime = rolltime;
  8652. rc = work_decode(pool, work, val);
  8653. if (unlikely(!rc)) {
  8654. applog(LOG_ERR, "Could not convert longpoll data to work");
  8655. free_work(work);
  8656. return;
  8657. }
  8658. total_getworks++;
  8659. pool->getwork_requested++;
  8660. work->pool = pool;
  8661. copy_time(&work->tv_getwork, tv_lp);
  8662. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8663. calc_diff(work, 0);
  8664. if (pool->enabled == POOL_REJECTING)
  8665. work->mandatory = true;
  8666. work->longpoll = true;
  8667. work->getwork_mode = GETWORK_MODE_LP;
  8668. update_last_work(work);
  8669. /* We'll be checking this work item twice, but we already know it's
  8670. * from a new block so explicitly force the new block detection now
  8671. * rather than waiting for it to hit the stage thread. This also
  8672. * allows testwork to know whether LP discovered the block or not. */
  8673. test_work_current(work);
  8674. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8675. * the longpoll work from a pool that has been rejecting shares as a
  8676. * way to detect when the pool has recovered.
  8677. */
  8678. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8679. free_work(work);
  8680. return;
  8681. }
  8682. work = clone_work(work);
  8683. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8684. stage_work(work);
  8685. applog(LOG_DEBUG, "Converted longpoll data to work");
  8686. }
  8687. /* If we want longpoll, enable it for the chosen default pool, or, if
  8688. * the pool does not support longpoll, find the first one that does
  8689. * and use its longpoll support */
  8690. static
  8691. struct pool *_select_longpoll_pool(struct pool *cp, bool(*func)(struct pool *))
  8692. {
  8693. int i;
  8694. if (func(cp))
  8695. return cp;
  8696. for (i = 0; i < total_pools; i++) {
  8697. struct pool *pool = pools[i];
  8698. if (func(pool))
  8699. return pool;
  8700. }
  8701. return NULL;
  8702. }
  8703. /* This will make the longpoll thread wait till it's the current pool, or it
  8704. * has been flagged as rejecting, before attempting to open any connections.
  8705. */
  8706. static void wait_lpcurrent(struct pool *pool)
  8707. {
  8708. mutex_lock(&lp_lock);
  8709. while (!cnx_needed(pool))
  8710. {
  8711. pool->lp_active = false;
  8712. pthread_cond_wait(&lp_cond, &lp_lock);
  8713. }
  8714. mutex_unlock(&lp_lock);
  8715. }
  8716. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8717. struct pool *pool = vpool;
  8718. curl_socket_t sock = bfg_socket(addr->family, addr->socktype, addr->protocol);
  8719. pool->lp_socket = sock;
  8720. return sock;
  8721. }
  8722. static void *longpoll_thread(void *userdata)
  8723. {
  8724. struct pool *cp = (struct pool *)userdata;
  8725. /* This *pool is the source of the actual longpoll, not the pool we've
  8726. * tied it to */
  8727. struct timeval start, reply, end;
  8728. struct pool *pool = NULL;
  8729. char threadname[20];
  8730. CURL *curl = NULL;
  8731. int failures = 0;
  8732. char *lp_url;
  8733. int rolltime;
  8734. #ifndef HAVE_PTHREAD_CANCEL
  8735. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8736. #endif
  8737. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8738. RenameThread(threadname);
  8739. curl = curl_easy_init();
  8740. if (unlikely(!curl)) {
  8741. applog(LOG_ERR, "CURL initialisation failed");
  8742. return NULL;
  8743. }
  8744. retry_pool:
  8745. pool = select_longpoll_pool(cp);
  8746. if (!pool) {
  8747. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8748. while (!pool) {
  8749. cgsleep_ms(60000);
  8750. pool = select_longpoll_pool(cp);
  8751. }
  8752. }
  8753. if (pool->has_stratum) {
  8754. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8755. cp->rpc_url, pool->rpc_url);
  8756. goto out;
  8757. }
  8758. /* Any longpoll from any pool is enough for this to be true */
  8759. have_longpoll = true;
  8760. wait_lpcurrent(cp);
  8761. {
  8762. lp_url = pool->lp_url;
  8763. if (cp == pool)
  8764. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8765. else
  8766. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8767. }
  8768. while (42) {
  8769. json_t *val, *soval;
  8770. struct work *work = make_work();
  8771. char *lpreq;
  8772. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8773. work->pool = pool;
  8774. if (!lpreq)
  8775. {
  8776. free_work(work);
  8777. goto lpfail;
  8778. }
  8779. wait_lpcurrent(cp);
  8780. cgtime(&start);
  8781. /* Longpoll connections can be persistent for a very long time
  8782. * and any number of issues could have come up in the meantime
  8783. * so always establish a fresh connection instead of relying on
  8784. * a persistent one. */
  8785. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8786. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8787. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8788. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8789. lpreq, false, true, &rolltime, pool, false);
  8790. pool->lp_socket = CURL_SOCKET_BAD;
  8791. cgtime(&reply);
  8792. free(lpreq);
  8793. if (likely(val)) {
  8794. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8795. if (soval)
  8796. pool->submit_old = json_is_true(soval);
  8797. else
  8798. pool->submit_old = false;
  8799. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8800. failures = 0;
  8801. json_decref(val);
  8802. } else {
  8803. /* Some pools regularly drop the longpoll request so
  8804. * only see this as longpoll failure if it happens
  8805. * immediately and just restart it the rest of the
  8806. * time. */
  8807. cgtime(&end);
  8808. free_work(work);
  8809. if (end.tv_sec - start.tv_sec <= 30)
  8810. {
  8811. if (failures == 1)
  8812. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8813. lpfail:
  8814. cgsleep_ms(30000);
  8815. }
  8816. }
  8817. if (pool != cp) {
  8818. pool = select_longpoll_pool(cp);
  8819. if (pool->has_stratum) {
  8820. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8821. cp->rpc_url, pool->rpc_url);
  8822. break;
  8823. }
  8824. if (unlikely(!pool))
  8825. goto retry_pool;
  8826. }
  8827. if (unlikely(pool->removed))
  8828. break;
  8829. }
  8830. out:
  8831. pool->lp_active = false;
  8832. curl_easy_cleanup(curl);
  8833. return NULL;
  8834. }
  8835. static void stop_longpoll(void)
  8836. {
  8837. int i;
  8838. want_longpoll = false;
  8839. for (i = 0; i < total_pools; ++i)
  8840. {
  8841. struct pool *pool = pools[i];
  8842. if (unlikely(!pool->lp_started))
  8843. continue;
  8844. pool->lp_started = false;
  8845. pthread_cancel(pool->longpoll_thread);
  8846. }
  8847. have_longpoll = false;
  8848. }
  8849. static void start_longpoll(void)
  8850. {
  8851. int i;
  8852. want_longpoll = true;
  8853. for (i = 0; i < total_pools; ++i)
  8854. {
  8855. struct pool *pool = pools[i];
  8856. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8857. continue;
  8858. pool->lp_started = true;
  8859. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8860. quit(1, "Failed to create pool longpoll thread");
  8861. }
  8862. }
  8863. void reinit_device(struct cgpu_info *cgpu)
  8864. {
  8865. if (cgpu->drv->reinit_device)
  8866. cgpu->drv->reinit_device(cgpu);
  8867. }
  8868. static struct timeval rotate_tv;
  8869. /* We reap curls if they are unused for over a minute */
  8870. static void reap_curl(struct pool *pool)
  8871. {
  8872. struct curl_ent *ent, *iter;
  8873. struct timeval now;
  8874. int reaped = 0;
  8875. cgtime(&now);
  8876. mutex_lock(&pool->pool_lock);
  8877. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8878. if (pool->curls < 2)
  8879. break;
  8880. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8881. reaped++;
  8882. pool->curls--;
  8883. LL_DELETE(pool->curllist, ent);
  8884. curl_easy_cleanup(ent->curl);
  8885. free(ent);
  8886. }
  8887. }
  8888. mutex_unlock(&pool->pool_lock);
  8889. if (reaped)
  8890. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8891. }
  8892. static void *watchpool_thread(void __maybe_unused *userdata)
  8893. {
  8894. int intervals = 0;
  8895. #ifndef HAVE_PTHREAD_CANCEL
  8896. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8897. #endif
  8898. RenameThread("watchpool");
  8899. while (42) {
  8900. struct timeval now;
  8901. int i;
  8902. if (++intervals > 20)
  8903. intervals = 0;
  8904. cgtime(&now);
  8905. for (i = 0; i < total_pools; i++) {
  8906. struct pool *pool = pools[i];
  8907. if (!opt_benchmark)
  8908. reap_curl(pool);
  8909. /* Get a rolling utility per pool over 10 mins */
  8910. if (intervals > 19) {
  8911. int shares = pool->diff1 - pool->last_shares;
  8912. pool->last_shares = pool->diff1;
  8913. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8914. pool->shares = pool->utility;
  8915. }
  8916. if (pool->enabled == POOL_DISABLED)
  8917. continue;
  8918. /* Don't start testing any pools if the test threads
  8919. * from startup are still doing their first attempt. */
  8920. if (unlikely(pool->testing)) {
  8921. pthread_join(pool->test_thread, NULL);
  8922. }
  8923. /* Test pool is idle once every minute */
  8924. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8925. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8926. pool_resus(pool);
  8927. }
  8928. /* Only switch pools if the failback pool has been
  8929. * alive for more than 5 minutes (default) to prevent
  8930. * intermittently failing pools from being used. */
  8931. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8932. now.tv_sec - pool->tv_idle.tv_sec > opt_fail_switch_delay) {
  8933. if (opt_fail_switch_delay % 60)
  8934. applog(LOG_WARNING, "Pool %d %s stable for %d second%s",
  8935. pool->pool_no, pool->rpc_url,
  8936. opt_fail_switch_delay,
  8937. (opt_fail_switch_delay == 1 ? "" : "s"));
  8938. else
  8939. applog(LOG_WARNING, "Pool %d %s stable for %d minute%s",
  8940. pool->pool_no, pool->rpc_url,
  8941. opt_fail_switch_delay / 60,
  8942. (opt_fail_switch_delay == 60 ? "" : "s"));
  8943. switch_pools(NULL);
  8944. }
  8945. }
  8946. if (current_pool()->idle)
  8947. switch_pools(NULL);
  8948. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8949. cgtime(&rotate_tv);
  8950. switch_pools(NULL);
  8951. }
  8952. cgsleep_ms(30000);
  8953. }
  8954. return NULL;
  8955. }
  8956. void mt_enable(struct thr_info *thr)
  8957. {
  8958. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8959. notifier_wake(thr->notifier);
  8960. }
  8961. void proc_enable(struct cgpu_info *cgpu)
  8962. {
  8963. int j;
  8964. cgpu->deven = DEV_ENABLED;
  8965. for (j = cgpu->threads ?: 1; j--; )
  8966. mt_enable(cgpu->thr[j]);
  8967. }
  8968. #define device_recovered(cgpu) proc_enable(cgpu)
  8969. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8970. {
  8971. struct string_elist *setstr_elist;
  8972. const char *p, *p2;
  8973. char replybuf[0x2000];
  8974. size_t L;
  8975. DL_FOREACH(opt_set_device_list, setstr_elist)
  8976. {
  8977. const char * const setstr = setstr_elist->string;
  8978. p = strchr(setstr, ':');
  8979. if (!p)
  8980. p = setstr;
  8981. {
  8982. L = p - setstr;
  8983. char pattern[L + 1];
  8984. if (L)
  8985. memcpy(pattern, setstr, L);
  8986. pattern[L] = '\0';
  8987. if (!cgpu_match(pattern, cgpu))
  8988. continue;
  8989. }
  8990. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8991. cgpu->proc_repr, __func__, setstr);
  8992. if (p[0] == ':')
  8993. ++p;
  8994. p2 = strchr(p, '=');
  8995. if (!p2)
  8996. {
  8997. L = strlen(p);
  8998. p2 = "";
  8999. }
  9000. else
  9001. {
  9002. L = p2 - p;
  9003. ++p2;
  9004. }
  9005. char opt[L + 1];
  9006. if (L)
  9007. memcpy(opt, p, L);
  9008. opt[L] = '\0';
  9009. L = strlen(p2);
  9010. char setval[L + 1];
  9011. if (L)
  9012. memcpy(setval, p2, L);
  9013. setval[L] = '\0';
  9014. enum bfg_set_device_replytype success;
  9015. p = proc_set_device(cgpu, opt, setval, replybuf, &success);
  9016. switch (success)
  9017. {
  9018. case SDR_OK:
  9019. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s%s%s",
  9020. cgpu->proc_repr, setstr,
  9021. p ? ": " : "", p ?: "");
  9022. break;
  9023. case SDR_ERR:
  9024. case SDR_HELP:
  9025. case SDR_UNKNOWN:
  9026. applog(LOG_DEBUG, "%"PRIpreprv": Applying rule %s: %s",
  9027. cgpu->proc_repr, setstr, p);
  9028. break;
  9029. case SDR_AUTO:
  9030. case SDR_NOSUPP:
  9031. applog(LOG_DEBUG, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  9032. cgpu->proc_repr, setstr);
  9033. }
  9034. }
  9035. cgpu->already_set_defaults = true;
  9036. }
  9037. 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)
  9038. {
  9039. struct device_drv dummy_drv = *drv;
  9040. struct cgpu_info dummy_cgpu = {
  9041. .drv = &dummy_drv,
  9042. .device = &dummy_cgpu,
  9043. .device_id = -1,
  9044. .proc_id = -1,
  9045. .device_data = userp,
  9046. .device_path = devpath,
  9047. .dev_serial = serial,
  9048. };
  9049. strcpy(dummy_cgpu.proc_repr, drv->name);
  9050. switch (mode)
  9051. {
  9052. case 0:
  9053. dummy_drv.set_device = datap;
  9054. break;
  9055. case 1:
  9056. dummy_drv.set_device = NULL;
  9057. dummy_cgpu.set_device_funcs = datap;
  9058. break;
  9059. }
  9060. cgpu_set_defaults(&dummy_cgpu);
  9061. }
  9062. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  9063. * the screen at regular intervals, and restarts threads if they appear to have
  9064. * died. */
  9065. #define WATCHDOG_SICK_TIME 60
  9066. #define WATCHDOG_DEAD_TIME 600
  9067. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  9068. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  9069. static void *watchdog_thread(void __maybe_unused *userdata)
  9070. {
  9071. const unsigned int interval = WATCHDOG_INTERVAL;
  9072. struct timeval zero_tv;
  9073. #ifndef HAVE_PTHREAD_CANCEL
  9074. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  9075. #endif
  9076. RenameThread("watchdog");
  9077. memset(&zero_tv, 0, sizeof(struct timeval));
  9078. cgtime(&rotate_tv);
  9079. while (1) {
  9080. int i;
  9081. struct timeval now;
  9082. sleep(interval);
  9083. discard_stale();
  9084. hashmeter(-1, &zero_tv, 0);
  9085. #ifdef HAVE_CURSES
  9086. const int ts = total_staged();
  9087. if (curses_active_locked()) {
  9088. change_logwinsize();
  9089. curses_print_status(ts);
  9090. _refresh_devstatus(true);
  9091. touchwin(logwin);
  9092. wrefresh(logwin);
  9093. unlock_curses();
  9094. }
  9095. #endif
  9096. cgtime(&now);
  9097. if (!sched_paused && !should_run()) {
  9098. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  9099. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9100. if (!schedstart.enable) {
  9101. quit(0, "Terminating execution as planned");
  9102. break;
  9103. }
  9104. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  9105. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9106. sched_paused = true;
  9107. rd_lock(&mining_thr_lock);
  9108. for (i = 0; i < mining_threads; i++)
  9109. mining_thr[i]->pause = true;
  9110. rd_unlock(&mining_thr_lock);
  9111. } else if (sched_paused && should_run()) {
  9112. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  9113. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  9114. if (schedstop.enable)
  9115. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  9116. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  9117. sched_paused = false;
  9118. for (i = 0; i < mining_threads; i++) {
  9119. struct thr_info *thr;
  9120. thr = get_thread(i);
  9121. thr->pause = false;
  9122. }
  9123. for (i = 0; i < total_devices; ++i)
  9124. {
  9125. struct cgpu_info *cgpu = get_devices(i);
  9126. /* Don't touch disabled devices */
  9127. if (cgpu->deven == DEV_DISABLED)
  9128. continue;
  9129. proc_enable(cgpu);
  9130. }
  9131. }
  9132. for (i = 0; i < total_devices; ++i) {
  9133. struct cgpu_info *cgpu = get_devices(i);
  9134. if (!cgpu->disable_watchdog)
  9135. bfg_watchdog(cgpu, &now);
  9136. }
  9137. }
  9138. return NULL;
  9139. }
  9140. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  9141. {
  9142. struct thr_info *thr = cgpu->thr[0];
  9143. enum dev_enable *denable;
  9144. char *dev_str = cgpu->proc_repr;
  9145. if (likely(drv_ready(cgpu)))
  9146. {
  9147. if (unlikely(!cgpu->already_set_defaults))
  9148. cgpu_set_defaults(cgpu);
  9149. if (cgpu->drv->get_stats)
  9150. cgpu->drv->get_stats(cgpu);
  9151. }
  9152. denable = &cgpu->deven;
  9153. if (cgpu->drv->watchdog)
  9154. cgpu->drv->watchdog(cgpu, tvp_now);
  9155. /* Thread is disabled */
  9156. if (*denable == DEV_DISABLED)
  9157. return;
  9158. else
  9159. if (*denable == DEV_RECOVER_ERR) {
  9160. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  9161. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  9162. dev_str);
  9163. if (cgpu->reinit_backoff < 300)
  9164. cgpu->reinit_backoff *= 2;
  9165. device_recovered(cgpu);
  9166. }
  9167. return;
  9168. }
  9169. else
  9170. if (*denable == DEV_RECOVER) {
  9171. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  9172. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  9173. dev_str);
  9174. device_recovered(cgpu);
  9175. }
  9176. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9177. return;
  9178. }
  9179. else
  9180. if (cgpu->temp > cgpu->cutofftemp)
  9181. {
  9182. applog(LOG_WARNING, "%s hit thermal cutoff limit at %dC, disabling!",
  9183. dev_str, (int)cgpu->temp);
  9184. *denable = DEV_RECOVER;
  9185. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  9186. run_cmd(cmd_idle);
  9187. }
  9188. if (thr->getwork) {
  9189. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  9190. int thrid;
  9191. bool cgpu_idle = true;
  9192. thr->rolling = 0;
  9193. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  9194. if (!cgpu->thr[thrid]->getwork)
  9195. cgpu_idle = false;
  9196. if (cgpu_idle) {
  9197. cgpu->rolling = 0;
  9198. cgpu->status = LIFE_WAIT;
  9199. }
  9200. }
  9201. return;
  9202. }
  9203. else if (cgpu->status == LIFE_WAIT)
  9204. cgpu->status = LIFE_WELL;
  9205. #ifdef WANT_CPUMINE
  9206. if (!strcmp(cgpu->drv->dname, "cpu"))
  9207. return;
  9208. #endif
  9209. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  9210. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  9211. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  9212. cgpu->status = LIFE_WELL;
  9213. cgpu->device_last_well = time(NULL);
  9214. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  9215. thr->rolling = cgpu->rolling = 0;
  9216. cgpu->status = LIFE_SICK;
  9217. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  9218. cgtime(&thr->sick);
  9219. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  9220. run_cmd(cmd_sick);
  9221. if (opt_restart && cgpu->drv->reinit_device) {
  9222. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  9223. reinit_device(cgpu);
  9224. }
  9225. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  9226. cgpu->status = LIFE_DEAD;
  9227. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  9228. cgtime(&thr->sick);
  9229. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  9230. run_cmd(cmd_dead);
  9231. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  9232. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  9233. /* Attempt to restart a GPU that's sick or dead once every minute */
  9234. cgtime(&thr->sick);
  9235. if (opt_restart)
  9236. reinit_device(cgpu);
  9237. }
  9238. }
  9239. static void log_print_status(struct cgpu_info *cgpu)
  9240. {
  9241. char logline[255];
  9242. get_statline(logline, sizeof(logline), cgpu);
  9243. applog(LOG_WARNING, "%s", logline);
  9244. }
  9245. void print_summary(void)
  9246. {
  9247. struct timeval diff;
  9248. int hours, mins, secs, i;
  9249. double utility, efficiency = 0.0;
  9250. char xfer[(ALLOC_H2B_SPACED*2)+4+1], bw[(ALLOC_H2B_SPACED*2)+6+1];
  9251. int pool_secs;
  9252. timersub(&total_tv_end, &total_tv_start, &diff);
  9253. hours = diff.tv_sec / 3600;
  9254. mins = (diff.tv_sec % 3600) / 60;
  9255. secs = diff.tv_sec % 60;
  9256. utility = total_accepted / total_secs * 60;
  9257. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  9258. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  9259. applog(LOG_WARNING, "Started at %s", datestamp);
  9260. if (total_pools == 1)
  9261. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  9262. #ifdef WANT_CPUMINE
  9263. if (opt_n_threads > 0)
  9264. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  9265. #endif
  9266. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  9267. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  9268. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  9269. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  9270. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  9271. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  9272. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  9273. total_rejected, total_stale,
  9274. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  9275. );
  9276. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  9277. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  9278. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  9279. applog(LOG_WARNING, "Network transfer: %s (%s)",
  9280. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9281. (float)total_bytes_rcvd,
  9282. (float)total_bytes_sent),
  9283. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9284. (float)(total_bytes_rcvd / total_secs),
  9285. (float)(total_bytes_sent / total_secs)));
  9286. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  9287. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  9288. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  9289. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  9290. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  9291. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  9292. if (total_pools > 1) {
  9293. for (i = 0; i < total_pools; i++) {
  9294. struct pool *pool = pools[i];
  9295. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  9296. if (pool->solved)
  9297. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  9298. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  9299. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  9300. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  9301. pool->rejected, pool->stale_shares,
  9302. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  9303. );
  9304. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  9305. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  9306. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  9307. applog(LOG_WARNING, " Network transfer: %s (%s)",
  9308. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  9309. (float)pool->cgminer_pool_stats.net_bytes_received,
  9310. (float)pool->cgminer_pool_stats.net_bytes_sent),
  9311. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  9312. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  9313. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  9314. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  9315. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  9316. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  9317. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  9318. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  9319. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  9320. }
  9321. }
  9322. if (opt_quit_summary != BQS_NONE)
  9323. {
  9324. if (opt_quit_summary == BQS_DEFAULT)
  9325. {
  9326. if (total_devices < 25)
  9327. opt_quit_summary = BQS_PROCS;
  9328. else
  9329. opt_quit_summary = BQS_DEVS;
  9330. }
  9331. if (opt_quit_summary == BQS_DETAILED)
  9332. include_serial_in_statline = true;
  9333. applog(LOG_WARNING, "Summary of per device statistics:\n");
  9334. for (i = 0; i < total_devices; ++i) {
  9335. struct cgpu_info *cgpu = get_devices(i);
  9336. if (!cgpu->proc_id)
  9337. {
  9338. // Device summary line
  9339. opt_show_procs = false;
  9340. log_print_status(cgpu);
  9341. opt_show_procs = true;
  9342. }
  9343. if ((opt_quit_summary == BQS_PROCS || opt_quit_summary == BQS_DETAILED) && cgpu->procs > 1)
  9344. log_print_status(cgpu);
  9345. }
  9346. }
  9347. if (opt_shares) {
  9348. applog(LOG_WARNING, "Mined %g accepted shares of %g requested\n", total_diff_accepted, opt_shares);
  9349. if (opt_shares > total_diff_accepted)
  9350. applog(LOG_WARNING, "WARNING - Mined only %g shares of %g requested.", total_diff_accepted, opt_shares);
  9351. }
  9352. applog(LOG_WARNING, " ");
  9353. fflush(stderr);
  9354. fflush(stdout);
  9355. }
  9356. void _bfg_clean_up(bool restarting)
  9357. {
  9358. #ifdef HAVE_OPENCL
  9359. clear_adl(nDevs);
  9360. #endif
  9361. #ifdef HAVE_LIBUSB
  9362. if (likely(have_libusb))
  9363. libusb_exit(NULL);
  9364. #endif
  9365. cgtime(&total_tv_end);
  9366. #ifdef WIN32
  9367. timeEndPeriod(1);
  9368. #endif
  9369. if (!restarting) {
  9370. /* Attempting to disable curses or print a summary during a
  9371. * restart can lead to a deadlock. */
  9372. #ifdef HAVE_CURSES
  9373. disable_curses();
  9374. #endif
  9375. if (!opt_realquiet && successful_connect)
  9376. print_summary();
  9377. }
  9378. if (opt_n_threads > 0)
  9379. free(cpus);
  9380. curl_global_cleanup();
  9381. #ifdef WIN32
  9382. WSACleanup();
  9383. #endif
  9384. }
  9385. void _quit(int status)
  9386. {
  9387. if (status) {
  9388. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  9389. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  9390. int *p = NULL;
  9391. // NOTE debugger can bypass with: p = &p
  9392. *p = status; // Segfault, hopefully dumping core
  9393. }
  9394. }
  9395. #if defined(unix) || defined(__APPLE__)
  9396. if (forkpid > 0) {
  9397. kill(forkpid, SIGTERM);
  9398. forkpid = 0;
  9399. }
  9400. #endif
  9401. exit(status);
  9402. }
  9403. #ifdef HAVE_CURSES
  9404. char *curses_input(const char *query)
  9405. {
  9406. char *input;
  9407. echo();
  9408. input = malloc(255);
  9409. if (!input)
  9410. quit(1, "Failed to malloc input");
  9411. leaveok(logwin, false);
  9412. wlogprint("%s:\n", query);
  9413. wgetnstr(logwin, input, 255);
  9414. if (!strlen(input))
  9415. {
  9416. free(input);
  9417. input = NULL;
  9418. }
  9419. leaveok(logwin, true);
  9420. noecho();
  9421. return input;
  9422. }
  9423. #endif
  9424. static void *test_pool_thread(void *arg)
  9425. {
  9426. struct pool *pool = (struct pool *)arg;
  9427. if (pool_active(pool, false)) {
  9428. pool_tset(pool, &pool->lagging);
  9429. pool_tclear(pool, &pool->idle);
  9430. bool first_pool = false;
  9431. cg_wlock(&control_lock);
  9432. if (!pools_active) {
  9433. currentpool = pool;
  9434. if (pool->pool_no != 0)
  9435. first_pool = true;
  9436. pools_active = true;
  9437. }
  9438. cg_wunlock(&control_lock);
  9439. if (unlikely(first_pool))
  9440. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  9441. else
  9442. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  9443. switch_pools(NULL);
  9444. } else
  9445. pool_died(pool);
  9446. pool->testing = false;
  9447. return NULL;
  9448. }
  9449. /* Always returns true that the pool details were added unless we are not
  9450. * live, implying this is the only pool being added, so if no pools are
  9451. * active it returns false. */
  9452. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  9453. {
  9454. size_t siz;
  9455. pool_set_uri(pool, url);
  9456. pool->rpc_user = user;
  9457. pool->rpc_pass = pass;
  9458. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9459. pool->rpc_userpass = malloc(siz);
  9460. if (!pool->rpc_userpass)
  9461. quit(1, "Failed to malloc userpass");
  9462. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9463. pool->testing = true;
  9464. pool->idle = true;
  9465. enable_pool(pool);
  9466. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9467. if (!live) {
  9468. pthread_join(pool->test_thread, NULL);
  9469. return pools_active;
  9470. }
  9471. return true;
  9472. }
  9473. #ifdef HAVE_CURSES
  9474. static bool input_pool(bool live)
  9475. {
  9476. char *url = NULL, *user = NULL, *pass = NULL;
  9477. struct pool *pool;
  9478. bool ret = false;
  9479. immedok(logwin, true);
  9480. wlogprint("Input server details.\n");
  9481. url = curses_input("URL");
  9482. if (!url)
  9483. goto out;
  9484. user = curses_input("Username");
  9485. if (!user)
  9486. goto out;
  9487. pass = curses_input("Password");
  9488. if (!pass)
  9489. pass = calloc(1, 1);
  9490. pool = add_pool();
  9491. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  9492. strncmp(url, "https://", 8)) {
  9493. char *httpinput;
  9494. httpinput = malloc(256);
  9495. if (!httpinput)
  9496. quit(1, "Failed to malloc httpinput");
  9497. strcpy(httpinput, "http://");
  9498. strncat(httpinput, url, 248);
  9499. free(url);
  9500. url = httpinput;
  9501. }
  9502. ret = add_pool_details(pool, live, url, user, pass);
  9503. out:
  9504. immedok(logwin, false);
  9505. if (!ret) {
  9506. if (url)
  9507. free(url);
  9508. if (user)
  9509. free(user);
  9510. if (pass)
  9511. free(pass);
  9512. }
  9513. return ret;
  9514. }
  9515. #endif
  9516. #if defined(unix) || defined(__APPLE__)
  9517. static void fork_monitor()
  9518. {
  9519. // Make a pipe: [readFD, writeFD]
  9520. int pfd[2];
  9521. int r = pipe(pfd);
  9522. if (r < 0) {
  9523. perror("pipe - failed to create pipe for --monitor");
  9524. exit(1);
  9525. }
  9526. // Make stderr write end of pipe
  9527. fflush(stderr);
  9528. r = dup2(pfd[1], 2);
  9529. if (r < 0) {
  9530. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  9531. exit(1);
  9532. }
  9533. r = close(pfd[1]);
  9534. if (r < 0) {
  9535. perror("close - failed to close write end of pipe for --monitor");
  9536. exit(1);
  9537. }
  9538. // Don't allow a dying monitor to kill the main process
  9539. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  9540. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  9541. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  9542. perror("signal - failed to edit signal mask for --monitor");
  9543. exit(1);
  9544. }
  9545. // Fork a child process
  9546. forkpid = fork();
  9547. if (forkpid < 0) {
  9548. perror("fork - failed to fork child process for --monitor");
  9549. exit(1);
  9550. }
  9551. // Child: launch monitor command
  9552. if (0 == forkpid) {
  9553. // Make stdin read end of pipe
  9554. r = dup2(pfd[0], 0);
  9555. if (r < 0) {
  9556. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  9557. exit(1);
  9558. }
  9559. close(pfd[0]);
  9560. if (r < 0) {
  9561. perror("close - in child, failed to close read end of pipe for --monitor");
  9562. exit(1);
  9563. }
  9564. // Launch user specified command
  9565. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  9566. perror("execl - in child failed to exec user specified command for --monitor");
  9567. exit(1);
  9568. }
  9569. // Parent: clean up unused fds and bail
  9570. r = close(pfd[0]);
  9571. if (r < 0) {
  9572. perror("close - failed to close read end of pipe for --monitor");
  9573. exit(1);
  9574. }
  9575. }
  9576. #endif // defined(unix)
  9577. #ifdef HAVE_CURSES
  9578. #ifdef USE_UNICODE
  9579. static
  9580. wchar_t select_unicode_char(const wchar_t *opt)
  9581. {
  9582. for ( ; *opt; ++opt)
  9583. if (iswprint(*opt))
  9584. return *opt;
  9585. return '?';
  9586. }
  9587. #endif
  9588. void enable_curses(void) {
  9589. int x;
  9590. __maybe_unused int y;
  9591. lock_curses();
  9592. if (curses_active) {
  9593. unlock_curses();
  9594. return;
  9595. }
  9596. #ifdef USE_UNICODE
  9597. if (use_unicode)
  9598. {
  9599. setlocale(LC_CTYPE, "");
  9600. if (iswprint(0xb0))
  9601. have_unicode_degrees = true;
  9602. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  9603. }
  9604. #endif
  9605. mainwin = initscr();
  9606. start_color();
  9607. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  9608. if (ERR != use_default_colors())
  9609. default_bgcolor = -1;
  9610. #endif
  9611. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  9612. {
  9613. menu_attr = COLOR_PAIR(1);
  9614. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  9615. attr_bad |= COLOR_PAIR(2);
  9616. }
  9617. keypad(mainwin, true);
  9618. getmaxyx(mainwin, y, x);
  9619. statuswin = newwin(logstart, x, 0, 0);
  9620. leaveok(statuswin, true);
  9621. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  9622. // We resize the window later anyway, so just start it off at 1 :)
  9623. logwin = newwin(1, 0, logcursor, 0);
  9624. idlok(logwin, true);
  9625. scrollok(logwin, true);
  9626. leaveok(logwin, true);
  9627. cbreak();
  9628. noecho();
  9629. nonl();
  9630. curses_active = true;
  9631. statusy = logstart;
  9632. unlock_curses();
  9633. }
  9634. #endif
  9635. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  9636. #ifndef WANT_CPUMINE
  9637. struct device_drv cpu_drv;
  9638. struct device_drv cpu_drv = {
  9639. .name = "CPU",
  9640. };
  9641. #endif
  9642. static int cgminer_id_count = 0;
  9643. static int device_line_id_count;
  9644. void register_device(struct cgpu_info *cgpu)
  9645. {
  9646. cgpu->deven = DEV_ENABLED;
  9647. wr_lock(&devices_lock);
  9648. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9649. wr_unlock(&devices_lock);
  9650. if (!cgpu->proc_id)
  9651. cgpu->device_line_id = device_line_id_count++;
  9652. mining_threads += cgpu->threads ?: 1;
  9653. #ifdef HAVE_CURSES
  9654. adj_width(mining_threads, &dev_width);
  9655. #endif
  9656. rwlock_init(&cgpu->qlock);
  9657. cgpu->queued_work = NULL;
  9658. }
  9659. struct _cgpu_devid_counter {
  9660. char name[4];
  9661. int lastid;
  9662. UT_hash_handle hh;
  9663. };
  9664. void renumber_cgpu(struct cgpu_info *cgpu)
  9665. {
  9666. static struct _cgpu_devid_counter *devids = NULL;
  9667. struct _cgpu_devid_counter *d;
  9668. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9669. if (d)
  9670. cgpu->device_id = ++d->lastid;
  9671. else {
  9672. d = malloc(sizeof(*d));
  9673. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9674. cgpu->device_id = d->lastid = 0;
  9675. HASH_ADD_STR(devids, name, d);
  9676. }
  9677. // Build repr strings
  9678. sprintf(cgpu->dev_repr, "%s%2u", cgpu->drv->name, cgpu->device_id % 100);
  9679. sprintf(cgpu->dev_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id % 100);
  9680. strcpy(cgpu->proc_repr, cgpu->dev_repr);
  9681. sprintf(cgpu->proc_repr_ns, "%s%u", cgpu->drv->name, cgpu->device_id);
  9682. const int lpcount = cgpu->procs;
  9683. if (lpcount > 1)
  9684. {
  9685. int ns;
  9686. struct cgpu_info *slave;
  9687. int lpdigits = 1;
  9688. for (int i = lpcount; i > 26 && lpdigits < 3; i /= 26)
  9689. ++lpdigits;
  9690. memset(&cgpu->proc_repr[5], 'a', lpdigits);
  9691. cgpu->proc_repr[5 + lpdigits] = '\0';
  9692. ns = strlen(cgpu->proc_repr_ns);
  9693. strcpy(&cgpu->proc_repr_ns[ns], &cgpu->proc_repr[5]);
  9694. slave = cgpu;
  9695. for (int i = 1; i < lpcount; ++i)
  9696. {
  9697. slave = slave->next_proc;
  9698. strcpy(slave->proc_repr, cgpu->proc_repr);
  9699. strcpy(slave->proc_repr_ns, cgpu->proc_repr_ns);
  9700. for (int x = i, y = lpdigits; --y, x; x /= 26)
  9701. {
  9702. slave->proc_repr_ns[ns + y] =
  9703. slave->proc_repr[5 + y] += (x % 26);
  9704. }
  9705. }
  9706. }
  9707. }
  9708. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9709. {
  9710. sha256(buffer, length, digest);
  9711. return true;
  9712. }
  9713. static
  9714. int drv_algo_check(const struct device_drv * const drv)
  9715. {
  9716. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9717. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9718. return (algos & algomatch);
  9719. }
  9720. #ifndef HAVE_PTHREAD_CANCEL
  9721. extern void setup_pthread_cancel_workaround();
  9722. extern struct sigaction pcwm_orig_term_handler;
  9723. #endif
  9724. bool bfg_need_detect_rescan;
  9725. extern void probe_device(struct lowlevel_device_info *);
  9726. static void schedule_rescan(const struct timeval *);
  9727. static
  9728. void drv_detect_all()
  9729. {
  9730. bool rescanning = false;
  9731. rescan:
  9732. bfg_need_detect_rescan = false;
  9733. #ifdef HAVE_BFG_LOWLEVEL
  9734. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9735. LL_FOREACH_SAFE(infolist, info, infotmp)
  9736. probe_device(info);
  9737. LL_FOREACH_SAFE(infolist, info, infotmp)
  9738. pthread_join(info->probe_pth, NULL);
  9739. #endif
  9740. struct driver_registration *reg, *tmp;
  9741. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9742. {
  9743. const struct device_drv * const drv = reg->drv;
  9744. if (!(drv_algo_check(drv) && drv->drv_detect))
  9745. continue;
  9746. drv->drv_detect();
  9747. }
  9748. #ifdef HAVE_BFG_LOWLEVEL
  9749. lowlevel_scan_free();
  9750. #endif
  9751. if (bfg_need_detect_rescan)
  9752. {
  9753. if (rescanning)
  9754. {
  9755. applog(LOG_DEBUG, "Device rescan requested a second time, delaying");
  9756. struct timeval tv_when;
  9757. timer_set_delay_from_now(&tv_when, rescan_delay_ms * 1000);
  9758. schedule_rescan(&tv_when);
  9759. }
  9760. else
  9761. {
  9762. rescanning = true;
  9763. applog(LOG_DEBUG, "Device rescan requested");
  9764. goto rescan;
  9765. }
  9766. }
  9767. }
  9768. static
  9769. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9770. {
  9771. struct thr_info *thr;
  9772. int j;
  9773. struct device_drv *api = cgpu->drv;
  9774. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9775. int threadobj = cgpu->threads;
  9776. if (!threadobj)
  9777. // Create a fake thread object to handle hashmeter etc
  9778. threadobj = 1;
  9779. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9780. cgpu->thr[threadobj] = NULL;
  9781. cgpu->status = LIFE_INIT;
  9782. if (opt_devices_enabled_list)
  9783. {
  9784. struct string_elist *enablestr_elist;
  9785. cgpu->deven = DEV_DISABLED;
  9786. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9787. {
  9788. const char * const enablestr = enablestr_elist->string;
  9789. if (cgpu_match(enablestr, cgpu))
  9790. {
  9791. cgpu->deven = DEV_ENABLED;
  9792. break;
  9793. }
  9794. }
  9795. }
  9796. cgpu->max_hashes = 0;
  9797. BFGINIT(cgpu->min_nonce_diff, 1);
  9798. BFGINIT(cgpu->cutofftemp, opt_cutofftemp);
  9799. BFGINIT(cgpu->targettemp, cgpu->cutofftemp - 6);
  9800. // Setup thread structs before starting any of the threads, in case they try to interact
  9801. for (j = 0; j < threadobj; ++j, ++*kp) {
  9802. thr = get_thread(*kp);
  9803. thr->id = *kp;
  9804. thr->cgpu = cgpu;
  9805. thr->device_thread = j;
  9806. thr->work_restart_notifier[1] = INVSOCK;
  9807. thr->mutex_request[1] = INVSOCK;
  9808. thr->_job_transition_in_progress = true;
  9809. timerclear(&thr->tv_morework);
  9810. thr->scanhash_working = true;
  9811. thr->hashes_done = 0;
  9812. timerclear(&thr->tv_hashes_done);
  9813. cgtime(&thr->tv_lastupdate);
  9814. thr->tv_poll.tv_sec = -1;
  9815. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9816. cgpu->thr[j] = thr;
  9817. }
  9818. if (!cgpu->device->threads)
  9819. notifier_init_invalid(cgpu->thr[0]->notifier);
  9820. else
  9821. if (!cgpu->threads)
  9822. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9823. else
  9824. for (j = 0; j < cgpu->threads; ++j)
  9825. {
  9826. thr = cgpu->thr[j];
  9827. notifier_init(thr->notifier);
  9828. }
  9829. }
  9830. static
  9831. void start_cgpu(struct cgpu_info *cgpu)
  9832. {
  9833. struct thr_info *thr;
  9834. int j;
  9835. for (j = 0; j < cgpu->threads; ++j) {
  9836. thr = cgpu->thr[j];
  9837. /* Enable threads for devices set not to mine but disable
  9838. * their queue in case we wish to enable them later */
  9839. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9840. continue;
  9841. thread_reportout(thr);
  9842. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9843. quit(1, "thread %d create failed", thr->id);
  9844. notifier_wake(thr->notifier);
  9845. }
  9846. if (cgpu->deven == DEV_ENABLED)
  9847. proc_enable(cgpu);
  9848. }
  9849. static
  9850. void _scan_serial(void *p)
  9851. {
  9852. const char *s = p;
  9853. struct string_elist *iter, *tmp;
  9854. struct string_elist *orig_scan_devices = scan_devices;
  9855. if (s)
  9856. {
  9857. // Make temporary scan_devices list
  9858. scan_devices = NULL;
  9859. string_elist_add("noauto", &scan_devices);
  9860. add_serial(s);
  9861. }
  9862. drv_detect_all();
  9863. if (s)
  9864. {
  9865. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9866. {
  9867. string_elist_del(&scan_devices, iter);
  9868. }
  9869. scan_devices = orig_scan_devices;
  9870. }
  9871. }
  9872. #ifdef HAVE_BFG_LOWLEVEL
  9873. static
  9874. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9875. {
  9876. if (!(false
  9877. || (info->serial && !strcasecmp(ser, info->serial))
  9878. || (info->path && !strcasecmp(ser, info->path ))
  9879. || (info->devid && !strcasecmp(ser, info->devid ))
  9880. ))
  9881. {
  9882. char *devid = devpath_to_devid(ser);
  9883. if (!devid)
  9884. return false;
  9885. const bool different = strcmp(info->devid, devid);
  9886. free(devid);
  9887. if (different)
  9888. return false;
  9889. }
  9890. return true;
  9891. }
  9892. static
  9893. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9894. {
  9895. struct driver_registration *dreg;
  9896. char dname[dnamelen];
  9897. int i;
  9898. for (i = 0; i < dnamelen; ++i)
  9899. dname[i] = tolower(_dname[i]);
  9900. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9901. if (!dreg)
  9902. {
  9903. for (i = 0; i < dnamelen; ++i)
  9904. dname[i] = toupper(_dname[i]);
  9905. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9906. if (!dreg)
  9907. return NULL;
  9908. }
  9909. if (!drv_algo_check(dreg->drv))
  9910. return NULL;
  9911. return dreg->drv;
  9912. }
  9913. static
  9914. bool _probe_device_do_probe(const struct device_drv * const drv, const struct lowlevel_device_info * const info, bool * const request_rescan_p)
  9915. {
  9916. bfg_probe_result_flags = 0;
  9917. if (drv->lowl_probe(info))
  9918. {
  9919. if (!(bfg_probe_result_flags & BPR_CONTINUE_PROBES))
  9920. return true;
  9921. }
  9922. else
  9923. if (request_rescan_p && opt_hotplug && !(bfg_probe_result_flags & BPR_DONT_RESCAN))
  9924. *request_rescan_p = true;
  9925. return false;
  9926. }
  9927. bool dummy_check_never_true = false;
  9928. static
  9929. void *probe_device_thread(void *p)
  9930. {
  9931. struct lowlevel_device_info * const infolist = p;
  9932. struct lowlevel_device_info *info = infolist;
  9933. bool request_rescan = false;
  9934. {
  9935. char threadname[5 + strlen(info->devid) + 1];
  9936. sprintf(threadname, "probe_%s", info->devid);
  9937. RenameThread(threadname);
  9938. }
  9939. // If already in use, ignore
  9940. if (bfg_claim_any(NULL, NULL, info->devid))
  9941. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9942. __func__, info->product);
  9943. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9944. struct string_elist *sd_iter, *sd_tmp;
  9945. struct driver_registration *dreg, *dreg_tmp;
  9946. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9947. {
  9948. const char * const dname = sd_iter->string;
  9949. const char * const colon = strpbrk(dname, ":@");
  9950. if (!(colon && colon != dname))
  9951. continue;
  9952. const char * const ser = &colon[1];
  9953. LL_FOREACH2(infolist, info, same_devid_next)
  9954. {
  9955. if (!_probe_device_match(info, ser))
  9956. continue;
  9957. const size_t dnamelen = (colon - dname);
  9958. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9959. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  9960. continue;
  9961. if (_probe_device_do_probe(drv, info, &request_rescan))
  9962. return NULL;
  9963. }
  9964. }
  9965. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9966. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9967. {
  9968. const struct device_drv * const drv = dreg->drv;
  9969. if (!drv_algo_check(drv))
  9970. continue;
  9971. // Check for "noauto" flag
  9972. // NOTE: driver-specific configuration overrides general
  9973. bool doauto = true;
  9974. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9975. {
  9976. const char * const dname = sd_iter->string;
  9977. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9978. const char *colon = strchr(dname, ':');
  9979. if (!colon)
  9980. colon = &dname[-1];
  9981. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9982. continue;
  9983. const ssize_t dnamelen = (colon - dname);
  9984. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9985. continue;
  9986. doauto = (tolower(colon[1]) == 'a');
  9987. if (dnamelen != -1)
  9988. break;
  9989. }
  9990. if (doauto && drv->lowl_match)
  9991. {
  9992. LL_FOREACH2(infolist, info, same_devid_next)
  9993. {
  9994. /*
  9995. The below call to applog is absolutely necessary
  9996. Starting with commit 76d0cc183b1c9ddcc0ef34d2e43bc696ef9de92e installing BFGMiner on
  9997. Mac OS X using Homebrew results in a binary that segfaults on startup
  9998. There are two unresolved issues:
  9999. 1) The BFGMiner authors cannot find a way to install BFGMiner with Homebrew that results
  10000. in debug symbols being available to help troubleshoot the issue
  10001. 2) The issue disappears when unrelated code changes are made, such as adding the following
  10002. call to applog with infolist and / or p
  10003. We would encourage revisiting this in the future to come up with a more concrete solution
  10004. Reproducing should only require commenting / removing the following line and installing
  10005. BFGMiner using "brew install bfgminer --HEAD"
  10006. */
  10007. if (dummy_check_never_true)
  10008. applog(LOG_DEBUG, "lowl_match: %p(%s) %p %p %p", drv, drv->dname, info, infolist, p);
  10009. if (!drv->lowl_match(info))
  10010. continue;
  10011. if (_probe_device_do_probe(drv, info, &request_rescan))
  10012. return NULL;
  10013. }
  10014. }
  10015. }
  10016. // probe driver(s) with 'all' enabled
  10017. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  10018. {
  10019. const char * const dname = sd_iter->string;
  10020. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  10021. const char * const colon = strchr(dname, ':');
  10022. if (!colon)
  10023. {
  10024. LL_FOREACH2(infolist, info, same_devid_next)
  10025. {
  10026. if (
  10027. #ifdef NEED_BFG_LOWL_VCOM
  10028. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  10029. #endif
  10030. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  10031. {
  10032. bool dont_rescan = false;
  10033. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  10034. {
  10035. const struct device_drv * const drv = dreg->drv;
  10036. if (!drv_algo_check(drv))
  10037. continue;
  10038. if (drv->lowl_probe_by_name_only)
  10039. continue;
  10040. if (!drv->lowl_probe)
  10041. continue;
  10042. if (_probe_device_do_probe(drv, info, NULL))
  10043. return NULL;
  10044. if (bfg_probe_result_flags & BPR_DONT_RESCAN)
  10045. dont_rescan = true;
  10046. }
  10047. if (opt_hotplug && !dont_rescan)
  10048. request_rescan = true;
  10049. break;
  10050. }
  10051. }
  10052. continue;
  10053. }
  10054. if (strcasecmp(&colon[1], "all"))
  10055. continue;
  10056. const size_t dnamelen = (colon - dname);
  10057. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  10058. if (!(drv && drv->lowl_probe && drv_algo_check(drv)))
  10059. continue;
  10060. LL_FOREACH2(infolist, info, same_devid_next)
  10061. {
  10062. if (info->lowl->exclude_from_all)
  10063. continue;
  10064. if (_probe_device_do_probe(drv, info, NULL))
  10065. return NULL;
  10066. }
  10067. }
  10068. // Only actually request a rescan if we never found any cgpu
  10069. if (request_rescan)
  10070. bfg_need_detect_rescan = true;
  10071. return NULL;
  10072. }
  10073. void probe_device(struct lowlevel_device_info * const info)
  10074. {
  10075. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  10076. }
  10077. #endif
  10078. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  10079. {
  10080. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10081. int devcount, i, mining_threads_new = 0;
  10082. unsigned int k;
  10083. struct cgpu_info *cgpu;
  10084. struct thr_info *thr;
  10085. void *p;
  10086. mutex_lock(&mutex);
  10087. devcount = total_devices;
  10088. addfunc(arg);
  10089. if (!total_devices_new)
  10090. goto out;
  10091. wr_lock(&devices_lock);
  10092. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  10093. if (unlikely(!p))
  10094. {
  10095. wr_unlock(&devices_lock);
  10096. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  10097. goto out;
  10098. }
  10099. devices = p;
  10100. wr_unlock(&devices_lock);
  10101. for (i = 0; i < total_devices_new; ++i)
  10102. {
  10103. cgpu = devices_new[i];
  10104. mining_threads_new += cgpu->threads ?: 1;
  10105. }
  10106. wr_lock(&mining_thr_lock);
  10107. mining_threads_new += mining_threads;
  10108. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  10109. if (unlikely(!p))
  10110. {
  10111. wr_unlock(&mining_thr_lock);
  10112. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  10113. goto out;
  10114. }
  10115. mining_thr = p;
  10116. wr_unlock(&mining_thr_lock);
  10117. for (i = mining_threads; i < mining_threads_new; ++i) {
  10118. mining_thr[i] = calloc(1, sizeof(*thr));
  10119. if (!mining_thr[i])
  10120. {
  10121. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  10122. for ( ; --i >= mining_threads; )
  10123. free(mining_thr[i]);
  10124. goto out;
  10125. }
  10126. }
  10127. k = mining_threads;
  10128. for (i = 0; i < total_devices_new; ++i)
  10129. {
  10130. cgpu = devices_new[i];
  10131. allocate_cgpu(cgpu, &k);
  10132. }
  10133. for (i = 0; i < total_devices_new; ++i)
  10134. {
  10135. cgpu = devices_new[i];
  10136. start_cgpu(cgpu);
  10137. register_device(cgpu);
  10138. ++total_devices;
  10139. }
  10140. #ifdef HAVE_CURSES
  10141. switch_logsize();
  10142. #endif
  10143. out:
  10144. total_devices_new = 0;
  10145. devcount = total_devices - devcount;
  10146. mutex_unlock(&mutex);
  10147. return devcount;
  10148. }
  10149. int scan_serial(const char *s)
  10150. {
  10151. return create_new_cgpus(_scan_serial, (void*)s);
  10152. }
  10153. static pthread_mutex_t rescan_mutex = PTHREAD_MUTEX_INITIALIZER;
  10154. static bool rescan_active;
  10155. static struct timeval tv_rescan;
  10156. static notifier_t rescan_notifier;
  10157. static
  10158. void *rescan_thread(__maybe_unused void *p)
  10159. {
  10160. pthread_detach(pthread_self());
  10161. RenameThread("rescan");
  10162. struct timeval tv_timeout, tv_now;
  10163. fd_set rfds;
  10164. while (true)
  10165. {
  10166. mutex_lock(&rescan_mutex);
  10167. tv_timeout = tv_rescan;
  10168. if (!timer_isset(&tv_timeout))
  10169. {
  10170. rescan_active = false;
  10171. mutex_unlock(&rescan_mutex);
  10172. break;
  10173. }
  10174. mutex_unlock(&rescan_mutex);
  10175. FD_ZERO(&rfds);
  10176. FD_SET(rescan_notifier[0], &rfds);
  10177. const int maxfd = rescan_notifier[0];
  10178. timer_set_now(&tv_now);
  10179. if (select(maxfd+1, &rfds, NULL, NULL, select_timeout(&tv_timeout, &tv_now)) > 0)
  10180. notifier_read(rescan_notifier);
  10181. mutex_lock(&rescan_mutex);
  10182. if (timer_passed(&tv_rescan, NULL))
  10183. {
  10184. timer_unset(&tv_rescan);
  10185. mutex_unlock(&rescan_mutex);
  10186. applog(LOG_DEBUG, "Rescan timer expired, triggering");
  10187. scan_serial(NULL);
  10188. }
  10189. else
  10190. mutex_unlock(&rescan_mutex);
  10191. }
  10192. return NULL;
  10193. }
  10194. static
  10195. void _schedule_rescan(const struct timeval * const tvp_when)
  10196. {
  10197. if (rescan_active)
  10198. {
  10199. if (timercmp(tvp_when, &tv_rescan, <))
  10200. applog(LOG_DEBUG, "schedule_rescan: New schedule is before current, waiting it out");
  10201. else
  10202. {
  10203. applog(LOG_DEBUG, "schedule_rescan: New schedule is after current, delaying rescan");
  10204. tv_rescan = *tvp_when;
  10205. }
  10206. return;
  10207. }
  10208. applog(LOG_DEBUG, "schedule_rescan: Scheduling rescan (no rescans currently pending)");
  10209. tv_rescan = *tvp_when;
  10210. rescan_active = true;
  10211. static pthread_t pth;
  10212. if (unlikely(pthread_create(&pth, NULL, rescan_thread, NULL)))
  10213. applog(LOG_ERR, "Failed to start rescan thread");
  10214. }
  10215. static
  10216. void schedule_rescan(const struct timeval * const tvp_when)
  10217. {
  10218. mutex_lock(&rescan_mutex);
  10219. _schedule_rescan(tvp_when);
  10220. mutex_unlock(&rescan_mutex);
  10221. }
  10222. #ifdef HAVE_BFG_HOTPLUG
  10223. static
  10224. void hotplug_trigger()
  10225. {
  10226. applog(LOG_DEBUG, "%s: Scheduling rescan immediately", __func__);
  10227. struct timeval tv_now;
  10228. timer_set_now(&tv_now);
  10229. schedule_rescan(&tv_now);
  10230. }
  10231. #endif
  10232. #if defined(HAVE_LIBUDEV) && defined(HAVE_SYS_EPOLL_H)
  10233. static
  10234. void *hotplug_thread(__maybe_unused void *p)
  10235. {
  10236. pthread_detach(pthread_self());
  10237. RenameThread("hotplug");
  10238. struct udev * const udev = udev_new();
  10239. if (unlikely(!udev))
  10240. applogfailr(NULL, LOG_ERR, "udev_new");
  10241. struct udev_monitor * const mon = udev_monitor_new_from_netlink(udev, "udev");
  10242. if (unlikely(!mon))
  10243. applogfailr(NULL, LOG_ERR, "udev_monitor_new_from_netlink");
  10244. if (unlikely(udev_monitor_enable_receiving(mon)))
  10245. applogfailr(NULL, LOG_ERR, "udev_monitor_enable_receiving");
  10246. const int epfd = epoll_create(1);
  10247. if (unlikely(epfd == -1))
  10248. applogfailr(NULL, LOG_ERR, "epoll_create");
  10249. {
  10250. const int fd = udev_monitor_get_fd(mon);
  10251. struct epoll_event ev = {
  10252. .events = EPOLLIN | EPOLLPRI,
  10253. .data.fd = fd,
  10254. };
  10255. if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev))
  10256. applogfailr(NULL, LOG_ERR, "epoll_ctl");
  10257. }
  10258. struct epoll_event ev;
  10259. int rv;
  10260. bool pending = false;
  10261. while (true)
  10262. {
  10263. rv = epoll_wait(epfd, &ev, 1, pending ? hotplug_delay_ms : -1);
  10264. if (rv == -1)
  10265. {
  10266. if (errno == EAGAIN || errno == EINTR)
  10267. continue;
  10268. break;
  10269. }
  10270. if (!rv)
  10271. {
  10272. hotplug_trigger();
  10273. pending = false;
  10274. continue;
  10275. }
  10276. struct udev_device * const device = udev_monitor_receive_device(mon);
  10277. if (!device)
  10278. continue;
  10279. const char * const action = udev_device_get_action(device);
  10280. applog(LOG_DEBUG, "%s: Received %s event", __func__, action);
  10281. if (!strcmp(action, "add"))
  10282. pending = true;
  10283. udev_device_unref(device);
  10284. }
  10285. applogfailr(NULL, LOG_ERR, "epoll_wait");
  10286. }
  10287. #elif defined(WIN32)
  10288. static UINT_PTR _hotplug_wintimer_id;
  10289. VOID CALLBACK hotplug_win_timer(HWND hwnd, UINT msg, UINT_PTR idEvent, DWORD dwTime)
  10290. {
  10291. KillTimer(NULL, _hotplug_wintimer_id);
  10292. _hotplug_wintimer_id = 0;
  10293. hotplug_trigger();
  10294. }
  10295. LRESULT CALLBACK hotplug_win_callback(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  10296. {
  10297. if (msg == WM_DEVICECHANGE && wParam == DBT_DEVNODES_CHANGED)
  10298. {
  10299. applog(LOG_DEBUG, "%s: Received DBT_DEVNODES_CHANGED event", __func__);
  10300. _hotplug_wintimer_id = SetTimer(NULL, _hotplug_wintimer_id, hotplug_delay_ms, hotplug_win_timer);
  10301. }
  10302. return DefWindowProc(hwnd, msg, wParam, lParam);
  10303. }
  10304. static
  10305. void *hotplug_thread(__maybe_unused void *p)
  10306. {
  10307. pthread_detach(pthread_self());
  10308. WNDCLASS DummyWinCls = {
  10309. .lpszClassName = "BFGDummyWinCls",
  10310. .lpfnWndProc = hotplug_win_callback,
  10311. };
  10312. ATOM a = RegisterClass(&DummyWinCls);
  10313. if (unlikely(!a))
  10314. applogfailinfor(NULL, LOG_ERR, "RegisterClass", "%d", (int)GetLastError());
  10315. HWND hwnd = CreateWindow((void*)(intptr_t)a, NULL, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL);
  10316. if (unlikely(!hwnd))
  10317. applogfailinfor(NULL, LOG_ERR, "CreateWindow", "%d", (int)GetLastError());
  10318. MSG msg;
  10319. while (GetMessage(&msg, NULL, 0, 0))
  10320. {
  10321. TranslateMessage(&msg);
  10322. DispatchMessage(&msg);
  10323. }
  10324. quit(0, "WM_QUIT received");
  10325. return NULL;
  10326. }
  10327. #endif
  10328. #ifdef HAVE_BFG_HOTPLUG
  10329. static
  10330. void hotplug_start()
  10331. {
  10332. pthread_t pth;
  10333. if (unlikely(pthread_create(&pth, NULL, hotplug_thread, NULL)))
  10334. applog(LOG_ERR, "Failed to start hotplug thread");
  10335. }
  10336. #endif
  10337. static void probe_pools(void)
  10338. {
  10339. int i;
  10340. for (i = 0; i < total_pools; i++) {
  10341. struct pool *pool = pools[i];
  10342. pool->testing = true;
  10343. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  10344. }
  10345. }
  10346. static void raise_fd_limits(void)
  10347. {
  10348. #ifdef HAVE_SETRLIMIT
  10349. struct rlimit fdlimit;
  10350. rlim_t old_soft_limit;
  10351. char frombuf[0x10] = "unlimited";
  10352. char hardbuf[0x10] = "unlimited";
  10353. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  10354. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  10355. old_soft_limit = fdlimit.rlim_cur;
  10356. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  10357. fdlimit.rlim_cur = FD_SETSIZE;
  10358. else
  10359. fdlimit.rlim_cur = fdlimit.rlim_max;
  10360. if (fdlimit.rlim_max != RLIM_INFINITY)
  10361. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  10362. if (old_soft_limit != RLIM_INFINITY)
  10363. snprintf(frombuf, sizeof(frombuf), "%lu", (unsigned long)old_soft_limit);
  10364. if (fdlimit.rlim_cur == old_soft_limit)
  10365. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10366. (unsigned long)old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  10367. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  10368. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10369. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10370. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  10371. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  10372. #else
  10373. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  10374. #endif
  10375. }
  10376. extern void bfg_init_threadlocal();
  10377. extern void stratumsrv_start();
  10378. int main(int argc, char *argv[])
  10379. {
  10380. struct sigaction handler;
  10381. struct thr_info *thr;
  10382. struct block *block;
  10383. unsigned int k;
  10384. int i;
  10385. int rearrange_pools = 0;
  10386. char *s;
  10387. #ifdef WIN32
  10388. LoadLibrary("backtrace.dll");
  10389. #endif
  10390. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  10391. bfg_init_threadlocal();
  10392. #ifndef HAVE_PTHREAD_CANCEL
  10393. setup_pthread_cancel_workaround();
  10394. #endif
  10395. bfg_init_checksums();
  10396. #ifdef WIN32
  10397. {
  10398. WSADATA wsa;
  10399. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  10400. if (i)
  10401. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  10402. }
  10403. #endif
  10404. /* This dangerous functions tramples random dynamically allocated
  10405. * variables so do it before anything at all */
  10406. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  10407. quit(1, "Failed to curl_global_init");
  10408. initial_args = malloc(sizeof(char *) * (argc + 1));
  10409. for (i = 0; i < argc; i++)
  10410. initial_args[i] = strdup(argv[i]);
  10411. initial_args[argc] = NULL;
  10412. mutex_init(&hash_lock);
  10413. mutex_init(&console_lock);
  10414. cglock_init(&control_lock);
  10415. mutex_init(&stats_lock);
  10416. mutex_init(&sharelog_lock);
  10417. cglock_init(&ch_lock);
  10418. mutex_init(&sshare_lock);
  10419. rwlock_init(&blk_lock);
  10420. rwlock_init(&netacc_lock);
  10421. rwlock_init(&mining_thr_lock);
  10422. rwlock_init(&devices_lock);
  10423. mutex_init(&lp_lock);
  10424. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  10425. quit(1, "Failed to pthread_cond_init lp_cond");
  10426. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  10427. quit(1, "Failed to pthread_cond_init gws_cond");
  10428. notifier_init(submit_waiting_notifier);
  10429. timer_unset(&tv_rescan);
  10430. notifier_init(rescan_notifier);
  10431. /* Create a unique get work queue */
  10432. getq = tq_new();
  10433. if (!getq)
  10434. quit(1, "Failed to create getq");
  10435. /* We use the getq mutex as the staged lock */
  10436. stgd_lock = &getq->mutex;
  10437. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  10438. #ifdef WANT_CPUMINE
  10439. init_max_name_len();
  10440. #endif
  10441. handler.sa_handler = &sighandler;
  10442. handler.sa_flags = 0;
  10443. sigemptyset(&handler.sa_mask);
  10444. #ifdef HAVE_PTHREAD_CANCEL
  10445. sigaction(SIGTERM, &handler, &termhandler);
  10446. #else
  10447. // Need to let pthread_cancel emulation handle SIGTERM first
  10448. termhandler = pcwm_orig_term_handler;
  10449. pcwm_orig_term_handler = handler;
  10450. #endif
  10451. sigaction(SIGINT, &handler, &inthandler);
  10452. #ifndef WIN32
  10453. signal(SIGPIPE, SIG_IGN);
  10454. #else
  10455. timeBeginPeriod(1);
  10456. #endif
  10457. opt_kernel_path = CGMINER_PREFIX;
  10458. cgminer_path = alloca(PATH_MAX);
  10459. s = strdup(argv[0]);
  10460. strcpy(cgminer_path, dirname(s));
  10461. free(s);
  10462. strcat(cgminer_path, "/");
  10463. #if defined(WANT_CPUMINE) && defined(WIN32)
  10464. {
  10465. char buf[32];
  10466. int gev = GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, sizeof(buf));
  10467. if (gev > 0 && gev < sizeof(buf))
  10468. {
  10469. setup_benchmark_pool();
  10470. double rate = bench_algo_stage3(atoi(buf));
  10471. // Write result to shared memory for parent
  10472. char unique_name[64];
  10473. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32))
  10474. {
  10475. HANDLE map_handle = CreateFileMapping(
  10476. INVALID_HANDLE_VALUE, // use paging file
  10477. NULL, // default security attributes
  10478. PAGE_READWRITE, // read/write access
  10479. 0, // size: high 32-bits
  10480. 4096, // size: low 32-bits
  10481. unique_name // name of map object
  10482. );
  10483. if (NULL != map_handle) {
  10484. void *shared_mem = MapViewOfFile(
  10485. map_handle, // object to map view of
  10486. FILE_MAP_WRITE, // read/write access
  10487. 0, // high offset: map from
  10488. 0, // low offset: beginning
  10489. 0 // default: map entire file
  10490. );
  10491. if (NULL != shared_mem)
  10492. CopyMemory(shared_mem, &rate, sizeof(rate));
  10493. (void)UnmapViewOfFile(shared_mem);
  10494. }
  10495. (void)CloseHandle(map_handle);
  10496. }
  10497. exit(0);
  10498. }
  10499. }
  10500. #endif
  10501. devcursor = 8;
  10502. logstart = devcursor;
  10503. logcursor = logstart;
  10504. block = calloc(sizeof(struct block), 1);
  10505. if (unlikely(!block))
  10506. quit (1, "main OOM");
  10507. for (i = 0; i < 36; i++)
  10508. strcat(block->hash, "0");
  10509. HASH_ADD_STR(blocks, hash, block);
  10510. strcpy(current_block, block->hash);
  10511. mutex_init(&submitting_lock);
  10512. #ifdef HAVE_OPENCL
  10513. opencl_early_init();
  10514. #endif
  10515. schedstart.tm.tm_sec = 1;
  10516. schedstop .tm.tm_sec = 1;
  10517. opt_register_table(opt_early_table, NULL);
  10518. opt_register_table(opt_config_table, NULL);
  10519. opt_register_table(opt_cmdline_table, NULL);
  10520. opt_early_parse(argc, argv, applog_and_exit);
  10521. if (!config_loaded)
  10522. {
  10523. load_default_config();
  10524. rearrange_pools = total_pools;
  10525. }
  10526. opt_free_table();
  10527. /* parse command line */
  10528. opt_register_table(opt_config_table,
  10529. "Options for both config file and command line");
  10530. opt_register_table(opt_cmdline_table,
  10531. "Options for command line only");
  10532. opt_parse(&argc, argv, applog_and_exit);
  10533. if (argc != 1)
  10534. quit(1, "Unexpected extra commandline arguments");
  10535. if (rearrange_pools && rearrange_pools < total_pools)
  10536. {
  10537. // Prioritise commandline pools before default-config pools
  10538. for (i = 0; i < rearrange_pools; ++i)
  10539. pools[i]->prio += rearrange_pools;
  10540. for ( ; i < total_pools; ++i)
  10541. pools[i]->prio -= rearrange_pools;
  10542. }
  10543. #ifndef HAVE_PTHREAD_CANCEL
  10544. // Can't do this any earlier, or config isn't loaded
  10545. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  10546. #endif
  10547. #ifdef HAVE_PWD_H
  10548. struct passwd *user_info = NULL;
  10549. if (opt_setuid != NULL) {
  10550. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  10551. quit(1, "Unable to find setuid user information");
  10552. }
  10553. }
  10554. #endif
  10555. #ifdef HAVE_CHROOT
  10556. if (chroot_dir != NULL) {
  10557. #ifdef HAVE_PWD_H
  10558. if (user_info == NULL && getuid() == 0) {
  10559. applog(LOG_WARNING, "Running as root inside chroot");
  10560. }
  10561. #endif
  10562. if (chroot(chroot_dir) != 0) {
  10563. quit(1, "Unable to chroot");
  10564. }
  10565. if (chdir("/"))
  10566. quit(1, "Unable to chdir to chroot");
  10567. }
  10568. #endif
  10569. #ifdef HAVE_PWD_H
  10570. if (user_info != NULL) {
  10571. if (setgid((*user_info).pw_gid) != 0)
  10572. quit(1, "Unable to setgid");
  10573. if (setuid((*user_info).pw_uid) != 0)
  10574. quit(1, "Unable to setuid");
  10575. }
  10576. #endif
  10577. raise_fd_limits();
  10578. if (opt_benchmark) {
  10579. while (total_pools)
  10580. remove_pool(pools[0]);
  10581. setup_benchmark_pool();
  10582. }
  10583. if (opt_unittest) {
  10584. test_cgpu_match();
  10585. test_intrange();
  10586. test_decimal_width();
  10587. test_domain_funcs();
  10588. test_target();
  10589. test_uri_get_param();
  10590. utf8_test();
  10591. }
  10592. #ifdef HAVE_CURSES
  10593. if (opt_realquiet || opt_display_devs)
  10594. use_curses = false;
  10595. setlocale(LC_ALL, "C");
  10596. if (use_curses)
  10597. enable_curses();
  10598. #endif
  10599. #ifdef HAVE_LIBUSB
  10600. int err = libusb_init(NULL);
  10601. if (err)
  10602. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  10603. else
  10604. have_libusb = true;
  10605. #endif
  10606. applog(LOG_WARNING, "Started %s", packagename);
  10607. {
  10608. struct bfg_loaded_configfile *configfile;
  10609. LL_FOREACH(bfg_loaded_configfiles, configfile)
  10610. {
  10611. char * const cnfbuf = configfile->filename;
  10612. int fileconf_load = configfile->fileconf_load;
  10613. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  10614. switch (fileconf_load) {
  10615. case 0:
  10616. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  10617. applog(LOG_WARNING, "Configuration file could not be used.");
  10618. break;
  10619. case -1:
  10620. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  10621. if (use_curses)
  10622. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  10623. break;
  10624. default:
  10625. break;
  10626. }
  10627. }
  10628. }
  10629. i = strlen(opt_kernel_path) + 2;
  10630. char __kernel_path[i];
  10631. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  10632. opt_kernel_path = __kernel_path;
  10633. if (want_per_device_stats)
  10634. opt_log_output = true;
  10635. #ifdef WANT_CPUMINE
  10636. #ifdef USE_SCRYPT
  10637. if (opt_scrypt)
  10638. set_scrypt_algo(&opt_algo);
  10639. #endif
  10640. #endif
  10641. bfg_devapi_init();
  10642. drv_detect_all();
  10643. total_devices = total_devices_new;
  10644. devices = devices_new;
  10645. total_devices_new = 0;
  10646. devices_new = NULL;
  10647. if (opt_display_devs) {
  10648. int devcount = 0;
  10649. applog(LOG_ERR, "Devices detected:");
  10650. for (i = 0; i < total_devices; ++i) {
  10651. struct cgpu_info *cgpu = devices[i];
  10652. char buf[0x100];
  10653. if (cgpu->device != cgpu)
  10654. continue;
  10655. if (cgpu->name)
  10656. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  10657. else
  10658. if (cgpu->dev_manufacturer)
  10659. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  10660. else
  10661. if (cgpu->dev_product)
  10662. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  10663. else
  10664. strcpy(buf, " Device");
  10665. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  10666. if (cgpu->dev_serial)
  10667. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  10668. if (cgpu->device_path)
  10669. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  10670. tailsprintf(buf, sizeof(buf), ")");
  10671. _applog(LOG_NOTICE, buf);
  10672. ++devcount;
  10673. }
  10674. quit(0, "%d devices listed", devcount);
  10675. }
  10676. mining_threads = 0;
  10677. for (i = 0; i < total_devices; ++i)
  10678. register_device(devices[i]);
  10679. if (!total_devices) {
  10680. applog(LOG_WARNING, "No devices detected!");
  10681. if (use_curses)
  10682. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  10683. else
  10684. applog(LOG_WARNING, "Waiting for devices");
  10685. }
  10686. #ifdef HAVE_CURSES
  10687. switch_logsize();
  10688. #endif
  10689. if (!total_pools) {
  10690. applog(LOG_WARNING, "Need to specify at least one pool server.");
  10691. #ifdef HAVE_CURSES
  10692. if (!use_curses || !input_pool(false))
  10693. #endif
  10694. quit(1, "Pool setup failed");
  10695. }
  10696. for (i = 0; i < total_pools; i++) {
  10697. struct pool *pool = pools[i];
  10698. size_t siz;
  10699. if (!pool->rpc_url)
  10700. quit(1, "No URI supplied for pool %u", i);
  10701. if (!pool->rpc_userpass) {
  10702. if (!pool->rpc_user || !pool->rpc_pass)
  10703. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  10704. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  10705. pool->rpc_userpass = malloc(siz);
  10706. if (!pool->rpc_userpass)
  10707. quit(1, "Failed to malloc userpass");
  10708. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  10709. }
  10710. }
  10711. /* Set the currentpool to pool with priority 0 */
  10712. validate_pool_priorities();
  10713. for (i = 0; i < total_pools; i++) {
  10714. struct pool *pool = pools[i];
  10715. if (!pool->prio)
  10716. currentpool = pool;
  10717. }
  10718. #ifdef HAVE_SYSLOG_H
  10719. if (use_syslog)
  10720. openlog(PACKAGE, LOG_PID, LOG_USER);
  10721. #endif
  10722. #if defined(unix) || defined(__APPLE__)
  10723. if (opt_stderr_cmd)
  10724. fork_monitor();
  10725. #endif // defined(unix)
  10726. mining_thr = calloc(mining_threads, sizeof(thr));
  10727. if (!mining_thr)
  10728. quit(1, "Failed to calloc mining_thr");
  10729. for (i = 0; i < mining_threads; i++) {
  10730. mining_thr[i] = calloc(1, sizeof(*thr));
  10731. if (!mining_thr[i])
  10732. quit(1, "Failed to calloc mining_thr[%d]", i);
  10733. }
  10734. total_control_threads = 6;
  10735. control_thr = calloc(total_control_threads, sizeof(*thr));
  10736. if (!control_thr)
  10737. quit(1, "Failed to calloc control_thr");
  10738. if (opt_benchmark)
  10739. goto begin_bench;
  10740. applog(LOG_NOTICE, "Probing for an alive pool");
  10741. do {
  10742. bool still_testing;
  10743. int i;
  10744. /* Look for at least one active pool before starting */
  10745. probe_pools();
  10746. do {
  10747. sleep(1);
  10748. if (pools_active)
  10749. break;
  10750. still_testing = false;
  10751. for (int i = 0; i < total_pools; ++i)
  10752. if (pools[i]->testing)
  10753. still_testing = true;
  10754. } while (still_testing);
  10755. if (!pools_active) {
  10756. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  10757. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  10758. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  10759. for (i = 0; i < total_pools; i++) {
  10760. struct pool *pool;
  10761. pool = pools[i];
  10762. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  10763. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  10764. }
  10765. #ifdef HAVE_CURSES
  10766. if (use_curses) {
  10767. halfdelay(150);
  10768. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  10769. if (getch() != ERR)
  10770. quit(0, "No servers could be used! Exiting.");
  10771. cbreak();
  10772. } else
  10773. #endif
  10774. quit(0, "No servers could be used! Exiting.");
  10775. }
  10776. } while (!pools_active);
  10777. #ifdef USE_SCRYPT
  10778. if (detect_algo == 1 && !opt_scrypt) {
  10779. applog(LOG_NOTICE, "Detected scrypt algorithm");
  10780. opt_scrypt = true;
  10781. }
  10782. #endif
  10783. detect_algo = 0;
  10784. begin_bench:
  10785. total_mhashes_done = 0;
  10786. for (i = 0; i < total_devices; i++) {
  10787. struct cgpu_info *cgpu = devices[i];
  10788. cgpu->rolling = cgpu->total_mhashes = 0;
  10789. }
  10790. cgtime(&total_tv_start);
  10791. cgtime(&total_tv_end);
  10792. miner_started = total_tv_start;
  10793. time_t miner_start_ts = time(NULL);
  10794. if (schedstart.tm.tm_sec)
  10795. localtime_r(&miner_start_ts, &schedstart.tm);
  10796. if (schedstop.tm.tm_sec)
  10797. localtime_r(&miner_start_ts, &schedstop .tm);
  10798. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  10799. // Initialise processors and threads
  10800. k = 0;
  10801. for (i = 0; i < total_devices; ++i) {
  10802. struct cgpu_info *cgpu = devices[i];
  10803. allocate_cgpu(cgpu, &k);
  10804. }
  10805. // Start threads
  10806. for (i = 0; i < total_devices; ++i) {
  10807. struct cgpu_info *cgpu = devices[i];
  10808. start_cgpu(cgpu);
  10809. }
  10810. #ifdef HAVE_OPENCL
  10811. for (i = 0; i < nDevs; i++)
  10812. pause_dynamic_threads(i);
  10813. #endif
  10814. #ifdef WANT_CPUMINE
  10815. if (opt_n_threads > 0)
  10816. applog(LOG_INFO, "%d cpu miner threads started, using '%s' algorithm.",
  10817. opt_n_threads, algo_names[opt_algo]);
  10818. #endif
  10819. cgtime(&total_tv_start);
  10820. cgtime(&total_tv_end);
  10821. if (!opt_benchmark)
  10822. {
  10823. pthread_t submit_thread;
  10824. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  10825. quit(1, "submit_work thread create failed");
  10826. }
  10827. watchpool_thr_id = 1;
  10828. thr = &control_thr[watchpool_thr_id];
  10829. /* start watchpool thread */
  10830. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  10831. quit(1, "watchpool thread create failed");
  10832. pthread_detach(thr->pth);
  10833. watchdog_thr_id = 2;
  10834. thr = &control_thr[watchdog_thr_id];
  10835. /* start watchdog thread */
  10836. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  10837. quit(1, "watchdog thread create failed");
  10838. pthread_detach(thr->pth);
  10839. #ifdef HAVE_OPENCL
  10840. /* Create reinit gpu thread */
  10841. gpur_thr_id = 3;
  10842. thr = &control_thr[gpur_thr_id];
  10843. thr->q = tq_new();
  10844. if (!thr->q)
  10845. quit(1, "tq_new failed for gpur_thr_id");
  10846. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  10847. quit(1, "reinit_gpu thread create failed");
  10848. #endif
  10849. /* Create API socket thread */
  10850. api_thr_id = 4;
  10851. thr = &control_thr[api_thr_id];
  10852. if (thr_info_create(thr, NULL, api_thread, thr))
  10853. quit(1, "API thread create failed");
  10854. #ifdef USE_LIBMICROHTTPD
  10855. if (httpsrv_port != -1)
  10856. httpsrv_start(httpsrv_port);
  10857. #endif
  10858. #ifdef USE_LIBEVENT
  10859. if (stratumsrv_port != -1)
  10860. stratumsrv_start();
  10861. #endif
  10862. #ifdef HAVE_BFG_HOTPLUG
  10863. if (opt_hotplug)
  10864. hotplug_start();
  10865. #endif
  10866. #ifdef HAVE_CURSES
  10867. /* Create curses input thread for keyboard input. Create this last so
  10868. * that we know all threads are created since this can call kill_work
  10869. * to try and shut down ll previous threads. */
  10870. input_thr_id = 5;
  10871. thr = &control_thr[input_thr_id];
  10872. if (thr_info_create(thr, NULL, input_thread, thr))
  10873. quit(1, "input thread create failed");
  10874. pthread_detach(thr->pth);
  10875. #endif
  10876. /* Just to be sure */
  10877. if (total_control_threads != 6)
  10878. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  10879. /* Once everything is set up, main() becomes the getwork scheduler */
  10880. while (42) {
  10881. int ts, max_staged = opt_queue;
  10882. struct pool *pool, *cp;
  10883. bool lagging = false;
  10884. struct curl_ent *ce;
  10885. struct work *work;
  10886. cp = current_pool();
  10887. // Generally, each processor needs a new work, and all at once during work restarts
  10888. max_staged += mining_threads;
  10889. mutex_lock(stgd_lock);
  10890. ts = __total_staged();
  10891. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  10892. lagging = true;
  10893. /* Wait until hash_pop tells us we need to create more work */
  10894. if (ts > max_staged) {
  10895. staged_full = true;
  10896. pthread_cond_wait(&gws_cond, stgd_lock);
  10897. ts = __total_staged();
  10898. }
  10899. mutex_unlock(stgd_lock);
  10900. if (ts > max_staged)
  10901. continue;
  10902. work = make_work();
  10903. if (lagging && !pool_tset(cp, &cp->lagging)) {
  10904. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  10905. cp->getfail_occasions++;
  10906. total_go++;
  10907. }
  10908. pool = select_pool(lagging);
  10909. retry:
  10910. if (pool->has_stratum) {
  10911. while (!pool->stratum_active || !pool->stratum_notify) {
  10912. struct pool *altpool = select_pool(true);
  10913. if (altpool == pool && pool->has_stratum)
  10914. cgsleep_ms(5000);
  10915. pool = altpool;
  10916. goto retry;
  10917. }
  10918. gen_stratum_work(pool, work);
  10919. applog(LOG_DEBUG, "Generated stratum work");
  10920. stage_work(work);
  10921. continue;
  10922. }
  10923. if (pool->last_work_copy) {
  10924. mutex_lock(&pool->last_work_lock);
  10925. struct work *last_work = pool->last_work_copy;
  10926. if (!last_work)
  10927. {}
  10928. else
  10929. if (can_roll(last_work) && should_roll(last_work)) {
  10930. struct timeval tv_now;
  10931. cgtime(&tv_now);
  10932. free_work(work);
  10933. work = make_clone(pool->last_work_copy);
  10934. mutex_unlock(&pool->last_work_lock);
  10935. roll_work(work);
  10936. 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));
  10937. stage_work(work);
  10938. continue;
  10939. } else if (last_work->tr && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tr->tmpl) > (unsigned long)mining_threads) {
  10940. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10941. } else {
  10942. free_work(last_work);
  10943. pool->last_work_copy = NULL;
  10944. }
  10945. mutex_unlock(&pool->last_work_lock);
  10946. }
  10947. if (clone_available()) {
  10948. applog(LOG_DEBUG, "Cloned getwork work");
  10949. free_work(work);
  10950. continue;
  10951. }
  10952. if (opt_benchmark) {
  10953. get_benchmark_work(work);
  10954. applog(LOG_DEBUG, "Generated benchmark work");
  10955. stage_work(work);
  10956. continue;
  10957. }
  10958. work->pool = pool;
  10959. ce = pop_curl_entry3(pool, 2);
  10960. /* obtain new work from bitcoin via JSON-RPC */
  10961. if (!get_upstream_work(work, ce->curl)) {
  10962. struct pool *next_pool;
  10963. /* Make sure the pool just hasn't stopped serving
  10964. * requests but is up as we'll keep hammering it */
  10965. push_curl_entry(ce, pool);
  10966. ++pool->seq_getfails;
  10967. pool_died(pool);
  10968. next_pool = select_pool(!opt_fail_only);
  10969. if (pool == next_pool) {
  10970. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10971. cgsleep_ms(5000);
  10972. } else {
  10973. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10974. pool = next_pool;
  10975. }
  10976. goto retry;
  10977. }
  10978. if (ts >= max_staged)
  10979. pool_tclear(pool, &pool->lagging);
  10980. if (pool_tclear(pool, &pool->idle))
  10981. pool_resus(pool);
  10982. applog(LOG_DEBUG, "Generated getwork work");
  10983. stage_work(work);
  10984. push_curl_entry(ce, pool);
  10985. }
  10986. return 0;
  10987. }