miner.c 297 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579
  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 <limits.h>
  22. #include <locale.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <time.h>
  31. #include <math.h>
  32. #include <stdarg.h>
  33. #include <assert.h>
  34. #include <signal.h>
  35. #include <wctype.h>
  36. #include <sys/stat.h>
  37. #include <sys/types.h>
  38. #include <dirent.h>
  39. #ifdef HAVE_PWD_H
  40. #include <pwd.h>
  41. #endif
  42. #ifndef WIN32
  43. #include <sys/resource.h>
  44. #include <sys/socket.h>
  45. #else
  46. #include <winsock2.h>
  47. #include <windows.h>
  48. #endif
  49. #include <ccan/opt/opt.h>
  50. #include <jansson.h>
  51. #include <curl/curl.h>
  52. #include <libgen.h>
  53. #include <sha2.h>
  54. #include <utlist.h>
  55. #include <blkmaker.h>
  56. #include <blkmaker_jansson.h>
  57. #include <blktemplate.h>
  58. #include "compat.h"
  59. #include "deviceapi.h"
  60. #include "logging.h"
  61. #include "miner.h"
  62. #include "findnonce.h"
  63. #include "adl.h"
  64. #include "driver-cpu.h"
  65. #include "driver-opencl.h"
  66. #include "bench_block.h"
  67. #include "scrypt.h"
  68. #ifdef USE_AVALON
  69. #include "driver-avalon.h"
  70. #endif
  71. #ifdef HAVE_BFG_LOWLEVEL
  72. #include "lowlevel.h"
  73. #endif
  74. #if defined(unix) || defined(__APPLE__)
  75. #include <errno.h>
  76. #include <fcntl.h>
  77. #include <sys/wait.h>
  78. #endif
  79. #ifdef USE_SCRYPT
  80. #include "scrypt.h"
  81. #endif
  82. #if defined(USE_AVALON) || defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER) || defined(USE_NANOFURY) || defined(USE_X6500) || defined(USE_ZTEX)
  83. # define USE_FPGA
  84. #endif
  85. struct strategies strategies[] = {
  86. { "Failover" },
  87. { "Round Robin" },
  88. { "Rotate" },
  89. { "Load Balance" },
  90. { "Balance" },
  91. };
  92. static char packagename[256];
  93. bool opt_protocol;
  94. bool opt_dev_protocol;
  95. static bool opt_benchmark;
  96. static bool want_longpoll = true;
  97. static bool want_gbt = true;
  98. static bool want_getwork = true;
  99. #if BLKMAKER_VERSION > 1
  100. struct _cbscript_t {
  101. char *data;
  102. size_t sz;
  103. };
  104. static struct _cbscript_t opt_coinbase_script;
  105. static uint32_t template_nonce;
  106. #endif
  107. #if BLKMAKER_VERSION > 0
  108. char *opt_coinbase_sig;
  109. #endif
  110. char *request_target_str;
  111. float request_pdiff = 1.0;
  112. double request_bdiff;
  113. static bool want_stratum = true;
  114. bool have_longpoll;
  115. int opt_skip_checks;
  116. bool want_per_device_stats;
  117. bool use_syslog;
  118. bool opt_quiet_work_updates;
  119. bool opt_quiet;
  120. bool opt_realquiet;
  121. bool opt_loginput;
  122. bool opt_compact;
  123. bool opt_show_procs;
  124. const int opt_cutofftemp = 95;
  125. int opt_hysteresis = 3;
  126. static int opt_retries = -1;
  127. int opt_fail_pause = 5;
  128. int opt_log_interval = 5;
  129. int opt_queue = 1;
  130. int opt_scantime = 60;
  131. int opt_expiry = 120;
  132. int opt_expiry_lp = 3600;
  133. int opt_bench_algo = -1;
  134. unsigned long long global_hashrate;
  135. static bool opt_unittest = false;
  136. unsigned long global_quota_gcd = 1;
  137. #ifdef HAVE_OPENCL
  138. int opt_dynamic_interval = 7;
  139. int nDevs;
  140. int opt_g_threads = -1;
  141. #endif
  142. #ifdef USE_SCRYPT
  143. static char detect_algo = 1;
  144. bool opt_scrypt;
  145. #else
  146. static char detect_algo;
  147. #endif
  148. bool opt_restart = true;
  149. #ifdef USE_LIBMICROHTTPD
  150. #include "httpsrv.h"
  151. int httpsrv_port = -1;
  152. #endif
  153. #ifdef USE_LIBEVENT
  154. int stratumsrv_port = -1;
  155. #endif
  156. struct string_elist *scan_devices;
  157. static struct string_elist *opt_set_device_list;
  158. bool opt_force_dev_init;
  159. static struct string_elist *opt_devices_enabled_list;
  160. static bool opt_display_devs;
  161. int total_devices;
  162. struct cgpu_info **devices;
  163. int total_devices_new;
  164. struct cgpu_info **devices_new;
  165. bool have_opencl;
  166. int opt_n_threads = -1;
  167. int mining_threads;
  168. int num_processors;
  169. #ifdef HAVE_CURSES
  170. bool use_curses = true;
  171. #else
  172. bool use_curses;
  173. #endif
  174. #ifdef HAVE_LIBUSB
  175. bool have_libusb;
  176. #endif
  177. static bool opt_submit_stale = true;
  178. static int opt_shares;
  179. static int opt_submit_threads = 0x40;
  180. bool opt_fail_only;
  181. bool opt_autofan;
  182. bool opt_autoengine;
  183. bool opt_noadl;
  184. char *opt_api_allow = NULL;
  185. char *opt_api_groups;
  186. char *opt_api_description = PACKAGE_STRING;
  187. int opt_api_port = 4028;
  188. bool opt_api_listen;
  189. bool opt_api_mcast;
  190. char *opt_api_mcast_addr = API_MCAST_ADDR;
  191. char *opt_api_mcast_code = API_MCAST_CODE;
  192. char *opt_api_mcast_des = "";
  193. int opt_api_mcast_port = 4028;
  194. bool opt_api_network;
  195. bool opt_delaynet;
  196. bool opt_disable_pool;
  197. static bool no_work;
  198. char *opt_icarus_options = NULL;
  199. char *opt_icarus_timing = NULL;
  200. bool opt_worktime;
  201. #ifdef USE_AVALON
  202. char *opt_avalon_options = NULL;
  203. #endif
  204. #ifdef USE_KLONDIKE
  205. char *opt_klondike_options = NULL;
  206. #endif
  207. char *opt_kernel_path;
  208. char *cgminer_path;
  209. #if defined(USE_BITFORCE)
  210. bool opt_bfl_noncerange;
  211. #endif
  212. #define QUIET (opt_quiet || opt_realquiet)
  213. struct thr_info *control_thr;
  214. struct thr_info **mining_thr;
  215. static int gwsched_thr_id;
  216. static int watchpool_thr_id;
  217. static int watchdog_thr_id;
  218. #ifdef HAVE_CURSES
  219. static int input_thr_id;
  220. #endif
  221. int gpur_thr_id;
  222. static int api_thr_id;
  223. static int total_control_threads;
  224. pthread_mutex_t hash_lock;
  225. static pthread_mutex_t *stgd_lock;
  226. pthread_mutex_t console_lock;
  227. cglock_t ch_lock;
  228. static pthread_rwlock_t blk_lock;
  229. static pthread_mutex_t sshare_lock;
  230. pthread_rwlock_t netacc_lock;
  231. pthread_rwlock_t mining_thr_lock;
  232. pthread_rwlock_t devices_lock;
  233. static pthread_mutex_t lp_lock;
  234. static pthread_cond_t lp_cond;
  235. pthread_cond_t gws_cond;
  236. bool shutting_down;
  237. double total_rolling;
  238. double total_mhashes_done;
  239. static struct timeval total_tv_start, total_tv_end;
  240. static struct timeval miner_started;
  241. cglock_t control_lock;
  242. pthread_mutex_t stats_lock;
  243. static pthread_mutex_t submitting_lock;
  244. static int total_submitting;
  245. static struct work *submit_waiting;
  246. notifier_t submit_waiting_notifier;
  247. int hw_errors;
  248. int total_accepted, total_rejected, total_diff1;
  249. int total_bad_nonces;
  250. int total_getworks, total_stale, total_discarded;
  251. uint64_t total_bytes_rcvd, total_bytes_sent;
  252. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  253. static int staged_rollable;
  254. unsigned int new_blocks;
  255. unsigned int found_blocks;
  256. unsigned int local_work;
  257. unsigned int total_go, total_ro;
  258. struct pool **pools;
  259. static struct pool *currentpool = NULL;
  260. int total_pools, enabled_pools;
  261. enum pool_strategy pool_strategy = POOL_FAILOVER;
  262. int opt_rotate_period;
  263. static int total_urls, total_users, total_passes;
  264. static
  265. #ifndef HAVE_CURSES
  266. const
  267. #endif
  268. bool curses_active;
  269. #ifdef HAVE_CURSES
  270. #if !(defined(PDCURSES) || defined(NCURSES_VERSION))
  271. const
  272. #endif
  273. short default_bgcolor = COLOR_BLACK;
  274. #endif
  275. static
  276. #if defined(HAVE_CURSES) && defined(USE_UNICODE)
  277. bool use_unicode;
  278. static
  279. bool have_unicode_degrees;
  280. static
  281. wchar_t unicode_micro = 'u';
  282. #else
  283. const bool use_unicode;
  284. static
  285. const bool have_unicode_degrees;
  286. static
  287. const char unicode_micro = 'u';
  288. #endif
  289. #ifdef HAVE_CURSES
  290. #define U8_BAD_START "\xef\x80\x81"
  291. #define U8_BAD_END "\xef\x80\x80"
  292. #define AS_BAD(x) U8_BAD_START x U8_BAD_END
  293. bool selecting_device;
  294. unsigned selected_device;
  295. #endif
  296. static char current_block[40];
  297. /* Protected by ch_lock */
  298. static char *current_hash;
  299. static uint32_t current_block_id;
  300. char *current_fullhash;
  301. static char datestamp[40];
  302. static char blocktime[32];
  303. time_t block_time;
  304. static char best_share[8] = "0";
  305. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  306. static char block_diff[8];
  307. static char net_hashrate[10];
  308. uint64_t best_diff = 0;
  309. static bool known_blkheight_current;
  310. static uint32_t known_blkheight;
  311. static uint32_t known_blkheight_blkid;
  312. static uint64_t block_subsidy;
  313. struct block {
  314. char hash[40];
  315. UT_hash_handle hh;
  316. int block_no;
  317. };
  318. static struct block *blocks = NULL;
  319. int swork_id;
  320. /* For creating a hash database of stratum shares submitted that have not had
  321. * a response yet */
  322. struct stratum_share {
  323. UT_hash_handle hh;
  324. bool block;
  325. struct work *work;
  326. int id;
  327. };
  328. static struct stratum_share *stratum_shares = NULL;
  329. char *opt_socks_proxy = NULL;
  330. static const char def_conf[] = "bfgminer.conf";
  331. static bool config_loaded;
  332. static int include_count;
  333. #define JSON_INCLUDE_CONF "include"
  334. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  335. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  336. #define JSON_MAX_DEPTH 10
  337. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  338. char *cmd_idle, *cmd_sick, *cmd_dead;
  339. #if defined(unix) || defined(__APPLE__)
  340. static char *opt_stderr_cmd = NULL;
  341. static int forkpid;
  342. #endif // defined(unix)
  343. #ifdef HAVE_CHROOT
  344. char *chroot_dir;
  345. #endif
  346. #ifdef HAVE_PWD_H
  347. char *opt_setuid;
  348. #endif
  349. struct sigaction termhandler, inthandler;
  350. struct thread_q *getq;
  351. static int total_work;
  352. static bool staged_full;
  353. struct work *staged_work = NULL;
  354. struct schedtime {
  355. bool enable;
  356. struct tm tm;
  357. };
  358. struct schedtime schedstart;
  359. struct schedtime schedstop;
  360. bool sched_paused;
  361. static bool time_before(struct tm *tm1, struct tm *tm2)
  362. {
  363. if (tm1->tm_hour < tm2->tm_hour)
  364. return true;
  365. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  366. return true;
  367. return false;
  368. }
  369. static bool should_run(void)
  370. {
  371. struct tm tm;
  372. time_t tt;
  373. bool within_range;
  374. if (!schedstart.enable && !schedstop.enable)
  375. return true;
  376. tt = time(NULL);
  377. localtime_r(&tt, &tm);
  378. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  379. if (time_before(&schedstop.tm, &schedstart.tm))
  380. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  381. else
  382. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  383. if (within_range && !schedstop.enable)
  384. /* This is a once off event with no stop time set */
  385. schedstart.enable = false;
  386. return within_range;
  387. }
  388. void get_datestamp(char *f, size_t fsiz, time_t tt)
  389. {
  390. struct tm _tm;
  391. struct tm *tm = &_tm;
  392. if (tt == INVALID_TIMESTAMP)
  393. tt = time(NULL);
  394. localtime_r(&tt, tm);
  395. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  396. tm->tm_year + 1900,
  397. tm->tm_mon + 1,
  398. tm->tm_mday,
  399. tm->tm_hour,
  400. tm->tm_min,
  401. tm->tm_sec);
  402. }
  403. static
  404. void get_timestamp(char *f, size_t fsiz, time_t tt)
  405. {
  406. struct tm _tm;
  407. struct tm *tm = &_tm;
  408. localtime_r(&tt, tm);
  409. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  410. tm->tm_hour,
  411. tm->tm_min,
  412. tm->tm_sec);
  413. }
  414. static void applog_and_exit(const char *fmt, ...) FORMAT_SYNTAX_CHECK(printf, 1, 2);
  415. static char exit_buf[512];
  416. static void applog_and_exit(const char *fmt, ...)
  417. {
  418. va_list ap;
  419. va_start(ap, fmt);
  420. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  421. va_end(ap);
  422. _applog(LOG_ERR, exit_buf);
  423. exit(1);
  424. }
  425. char *devpath_to_devid(const char *devpath)
  426. {
  427. #ifndef WIN32
  428. struct stat my_stat;
  429. if (stat(devpath, &my_stat))
  430. return NULL;
  431. char *devs = malloc(6 + (sizeof(dev_t) * 2) + 1);
  432. memcpy(devs, "dev_t:", 6);
  433. bin2hex(&devs[6], &my_stat.st_rdev, sizeof(dev_t));
  434. #else
  435. if (!strncmp(devpath, "\\\\.\\", 4))
  436. devpath += 4;
  437. if (strncasecmp(devpath, "COM", 3) || !devpath[3])
  438. return NULL;
  439. devpath += 3;
  440. char *p;
  441. strtol(devpath, &p, 10);
  442. if (p[0])
  443. return NULL;
  444. const int sz = (p - devpath);
  445. char *devs = malloc(4 + sz + 1);
  446. sprintf(devs, "com:%s", devpath);
  447. #endif
  448. return devs;
  449. }
  450. static
  451. bool devpaths_match(const char * const ap, const char * const bp)
  452. {
  453. char * const a = devpath_to_devid(ap);
  454. if (!a)
  455. return false;
  456. char * const b = devpath_to_devid(bp);
  457. bool rv = false;
  458. if (b)
  459. {
  460. rv = !strcmp(a, b);
  461. free(b);
  462. }
  463. free(a);
  464. return rv;
  465. }
  466. static
  467. int proc_letter_to_number(const char *s, const char ** const rem)
  468. {
  469. int n = 0, c;
  470. for ( ; s[0]; ++s)
  471. {
  472. if (unlikely(n > INT_MAX / 26))
  473. break;
  474. c = tolower(s[0]) - 'a';
  475. if (unlikely(c < 0 || c > 25))
  476. break;
  477. if (unlikely(INT_MAX - c < n))
  478. break;
  479. n = (n * 26) + c;
  480. }
  481. *rem = s;
  482. return n;
  483. }
  484. static
  485. bool cgpu_match(const char * const pattern, const struct cgpu_info * const cgpu)
  486. {
  487. // all - matches anything
  488. // d0 - matches all processors of device 0
  489. // d0-3 - matches all processors of device 0, 1, 2, or 3
  490. // d0a - matches first processor of device 0
  491. // 0 - matches processor 0
  492. // 0-4 - matches processors 0, 1, 2, 3, or 4
  493. // ___ - matches all processors on all devices using driver/name ___
  494. // ___0 - matches all processors of 0th device using driver/name ___
  495. // ___0a - matches first processor of 0th device using driver/name ___
  496. // @* - matches device with serial or path *
  497. // @*@a - matches first processor of device with serial or path *
  498. // ___@* - matches device with serial or path * using driver/name ___
  499. if (!strcasecmp(pattern, "all"))
  500. return true;
  501. const char *p = pattern, *p2;
  502. size_t L;
  503. int n, i, c = -1;
  504. int n2;
  505. int proc_first = -1, proc_last = -1;
  506. struct cgpu_info *device;
  507. while (p[0] && p[0] != '@' && p[0] != '-' && !isdigit(p[0]))
  508. ++p;
  509. L = p - pattern;
  510. while (L && isspace(pattern[L-1]))
  511. --L;
  512. if (p[0] == '@')
  513. {
  514. // Serial/path
  515. const char * const ser = &p[1];
  516. for (p = ser; p[0] != '@' && p[0] != '\0'; ++p)
  517. {}
  518. p2 = (p[0] == '@') ? &p[1] : p;
  519. const size_t serlen = (p - ser);
  520. p = "";
  521. n = n2 = 0;
  522. const char * const devpath = cgpu->device_path ?: "";
  523. const char * const devser = cgpu->dev_serial ?: "";
  524. if ((!strncmp(devpath, ser, serlen)) && devpath[serlen] == '\0')
  525. {} // Match
  526. else
  527. if ((!strncmp(devser, ser, serlen)) && devser[serlen] == '\0')
  528. {} // Match
  529. else
  530. {
  531. char devpath2[serlen + 1];
  532. memcpy(devpath2, ser, serlen);
  533. devpath2[serlen] = '\0';
  534. if (!devpaths_match(devpath, ser))
  535. return false;
  536. }
  537. }
  538. else
  539. {
  540. if (isdigit(p[0]))
  541. n = strtol(p, (void*)&p2, 0);
  542. else
  543. {
  544. n = 0;
  545. p2 = p;
  546. }
  547. if (p2[0] == '-')
  548. {
  549. ++p2;
  550. if (p2[0] && isdigit(p2[0]))
  551. n2 = strtol(p2, (void*)&p2, 0);
  552. else
  553. n2 = INT_MAX;
  554. }
  555. else
  556. n2 = n;
  557. if (p == pattern)
  558. {
  559. if (!p[0])
  560. return true;
  561. if (p2 && p2[0])
  562. goto invsyntax;
  563. for (i = n; i <= n2; ++i)
  564. {
  565. if (i >= total_devices)
  566. break;
  567. if (cgpu == devices[i])
  568. return true;
  569. }
  570. return false;
  571. }
  572. }
  573. if (p2[0])
  574. {
  575. proc_first = proc_letter_to_number(&p2[0], &p2);
  576. if (p2[0] == '-')
  577. {
  578. ++p2;
  579. if (p2[0])
  580. proc_last = proc_letter_to_number(p2, &p2);
  581. else
  582. proc_last = INT_MAX;
  583. }
  584. else
  585. proc_last = proc_first;
  586. if (p2[0])
  587. goto invsyntax;
  588. }
  589. if (L > 1 || tolower(pattern[0]) != 'd' || !p[0])
  590. {
  591. const struct device_drv * const drv = cgpu->drv;
  592. if ((L == 3 && !strncasecmp(pattern, drv->name, 3)) ||
  593. (!L) ||
  594. (L == strlen(drv->dname) && !strncasecmp(pattern, drv->dname, L)))
  595. {} // Matched name or dname
  596. else
  597. return false;
  598. if (p[0] && (cgpu->device_id < n || cgpu->device_id > n2))
  599. return false;
  600. if (proc_first != -1 && (cgpu->proc_id < proc_first || cgpu->proc_id > proc_last))
  601. return false;
  602. return true;
  603. }
  604. // d#
  605. c = -1;
  606. for (i = 0; ; ++i)
  607. {
  608. if (i == total_devices)
  609. return false;
  610. if (devices[i]->device != devices[i])
  611. continue;
  612. ++c;
  613. if (c < n)
  614. continue;
  615. if (c > n2)
  616. break;
  617. for (device = devices[i]; device; device = device->next_proc)
  618. {
  619. if (proc_first != -1 && (device->proc_id < proc_first || device->proc_id > proc_last))
  620. continue;
  621. if (device == cgpu)
  622. return true;
  623. }
  624. }
  625. return false;
  626. invsyntax:
  627. applog(LOG_WARNING, "%s: Invalid syntax: %s", __func__, pattern);
  628. return false;
  629. }
  630. #define TEST_CGPU_MATCH(pattern) \
  631. if (!cgpu_match(pattern, &cgpu)) \
  632. applog(LOG_ERR, "%s: Pattern \"%s\" should have matched!", __func__, pattern); \
  633. // END TEST_CGPU_MATCH
  634. #define TEST_CGPU_NOMATCH(pattern) \
  635. if (cgpu_match(pattern, &cgpu)) \
  636. applog(LOG_ERR, "%s: Pattern \"%s\" should NOT have matched!", __func__, pattern); \
  637. // END TEST_CGPU_MATCH
  638. static __maybe_unused
  639. void test_cgpu_match()
  640. {
  641. struct device_drv drv = {
  642. .dname = "test",
  643. .name = "TST",
  644. };
  645. struct cgpu_info cgpu = {
  646. .drv = &drv,
  647. .device = &cgpu,
  648. .device_id = 1,
  649. .proc_id = 1,
  650. .proc_repr = "TST 1b",
  651. }, cgpu0a = {
  652. .drv = &drv,
  653. .device = &cgpu0a,
  654. .device_id = 0,
  655. .proc_id = 0,
  656. .proc_repr = "TST 0a",
  657. }, cgpu1a = {
  658. .drv = &drv,
  659. .device = &cgpu0a,
  660. .device_id = 1,
  661. .proc_id = 0,
  662. .proc_repr = "TST 1a",
  663. };
  664. struct cgpu_info *devices_list[3] = {&cgpu0a, &cgpu1a, &cgpu,};
  665. devices = devices_list;
  666. total_devices = 3;
  667. TEST_CGPU_MATCH("all")
  668. TEST_CGPU_MATCH("d1")
  669. TEST_CGPU_NOMATCH("d2")
  670. TEST_CGPU_MATCH("d0-5")
  671. TEST_CGPU_NOMATCH("d0-0")
  672. TEST_CGPU_NOMATCH("d2-5")
  673. TEST_CGPU_MATCH("d-1")
  674. TEST_CGPU_MATCH("d1-")
  675. TEST_CGPU_NOMATCH("d-0")
  676. TEST_CGPU_NOMATCH("d2-")
  677. TEST_CGPU_MATCH("2")
  678. TEST_CGPU_NOMATCH("3")
  679. TEST_CGPU_MATCH("1-2")
  680. TEST_CGPU_MATCH("2-3")
  681. TEST_CGPU_NOMATCH("1-1")
  682. TEST_CGPU_NOMATCH("3-4")
  683. TEST_CGPU_MATCH("TST")
  684. TEST_CGPU_NOMATCH("TSF")
  685. TEST_CGPU_NOMATCH("TS")
  686. TEST_CGPU_NOMATCH("TSTF")
  687. TEST_CGPU_MATCH("TST1")
  688. TEST_CGPU_MATCH("TST0-1")
  689. TEST_CGPU_MATCH("TST 1")
  690. TEST_CGPU_MATCH("TST 1-2")
  691. TEST_CGPU_NOMATCH("TST2")
  692. TEST_CGPU_NOMATCH("TST2-3")
  693. TEST_CGPU_NOMATCH("TST0-0")
  694. TEST_CGPU_MATCH("TST1b")
  695. TEST_CGPU_NOMATCH("TST1c")
  696. TEST_CGPU_NOMATCH("TST1bb")
  697. TEST_CGPU_MATCH("TST0-1b")
  698. TEST_CGPU_NOMATCH("TST0-1c")
  699. TEST_CGPU_MATCH("TST1a-d")
  700. TEST_CGPU_NOMATCH("TST1a-a")
  701. TEST_CGPU_NOMATCH("TST1-a")
  702. TEST_CGPU_NOMATCH("TST1c-z")
  703. TEST_CGPU_NOMATCH("TST1c-")
  704. TEST_CGPU_MATCH("@")
  705. TEST_CGPU_NOMATCH("@abc")
  706. TEST_CGPU_MATCH("@@b")
  707. TEST_CGPU_NOMATCH("@@c")
  708. TEST_CGPU_MATCH("TST@")
  709. TEST_CGPU_NOMATCH("TST@abc")
  710. TEST_CGPU_MATCH("TST@@b")
  711. TEST_CGPU_NOMATCH("TST@@c")
  712. TEST_CGPU_MATCH("TST@@b-f")
  713. TEST_CGPU_NOMATCH("TST@@c-f")
  714. TEST_CGPU_NOMATCH("TST@@-a")
  715. cgpu.device_path = "/dev/test";
  716. cgpu.dev_serial = "testy";
  717. TEST_CGPU_MATCH("TST@/dev/test")
  718. TEST_CGPU_MATCH("TST@testy")
  719. TEST_CGPU_NOMATCH("TST@")
  720. TEST_CGPU_NOMATCH("TST@/dev/test5@b")
  721. TEST_CGPU_NOMATCH("TST@testy3@b")
  722. TEST_CGPU_MATCH("TST@/dev/test@b")
  723. TEST_CGPU_MATCH("TST@testy@b")
  724. TEST_CGPU_NOMATCH("TST@/dev/test@c")
  725. TEST_CGPU_NOMATCH("TST@testy@c")
  726. }
  727. static
  728. int cgpu_search(const char * const pattern, const int first)
  729. {
  730. int i;
  731. struct cgpu_info *cgpu;
  732. #define CHECK_CGPU_SEARCH do{ \
  733. cgpu = get_devices(i); \
  734. if (cgpu_match(pattern, cgpu)) \
  735. return i; \
  736. }while(0)
  737. for (i = first; i < total_devices; ++i)
  738. CHECK_CGPU_SEARCH;
  739. for (i = 0; i < first; ++i)
  740. CHECK_CGPU_SEARCH;
  741. #undef CHECK_CGPU_SEARCH
  742. return -1;
  743. }
  744. static pthread_mutex_t sharelog_lock;
  745. static FILE *sharelog_file = NULL;
  746. struct thr_info *get_thread(int thr_id)
  747. {
  748. struct thr_info *thr;
  749. rd_lock(&mining_thr_lock);
  750. thr = mining_thr[thr_id];
  751. rd_unlock(&mining_thr_lock);
  752. return thr;
  753. }
  754. static struct cgpu_info *get_thr_cgpu(int thr_id)
  755. {
  756. struct thr_info *thr = get_thread(thr_id);
  757. return thr->cgpu;
  758. }
  759. struct cgpu_info *get_devices(int id)
  760. {
  761. struct cgpu_info *cgpu;
  762. rd_lock(&devices_lock);
  763. cgpu = devices[id];
  764. rd_unlock(&devices_lock);
  765. return cgpu;
  766. }
  767. static pthread_mutex_t noncelog_lock = PTHREAD_MUTEX_INITIALIZER;
  768. static FILE *noncelog_file = NULL;
  769. static
  770. void noncelog(const struct work * const work)
  771. {
  772. const int thr_id = work->thr_id;
  773. const struct cgpu_info *proc = get_thr_cgpu(thr_id);
  774. char buf[0x200], hash[65], data[161], midstate[65];
  775. int rv;
  776. size_t ret;
  777. bin2hex(hash, work->hash, 32);
  778. bin2hex(data, work->data, 80);
  779. bin2hex(midstate, work->midstate, 32);
  780. // timestamp,proc,hash,data,midstate
  781. rv = snprintf(buf, sizeof(buf), "%lu,%s,%s,%s,%s\n",
  782. (unsigned long)time(NULL), proc->proc_repr_ns,
  783. hash, data, midstate);
  784. if (unlikely(rv < 1))
  785. {
  786. applog(LOG_ERR, "noncelog printf error");
  787. return;
  788. }
  789. mutex_lock(&noncelog_lock);
  790. ret = fwrite(buf, rv, 1, noncelog_file);
  791. fflush(noncelog_file);
  792. mutex_unlock(&noncelog_lock);
  793. if (ret != 1)
  794. applog(LOG_ERR, "noncelog fwrite error");
  795. }
  796. static void sharelog(const char*disposition, const struct work*work)
  797. {
  798. char target[(sizeof(work->target) * 2) + 1];
  799. char hash[(sizeof(work->hash) * 2) + 1];
  800. char data[(sizeof(work->data) * 2) + 1];
  801. struct cgpu_info *cgpu;
  802. unsigned long int t;
  803. struct pool *pool;
  804. int thr_id, rv;
  805. char s[1024];
  806. size_t ret;
  807. if (!sharelog_file)
  808. return;
  809. thr_id = work->thr_id;
  810. cgpu = get_thr_cgpu(thr_id);
  811. pool = work->pool;
  812. t = work->ts_getwork + timer_elapsed(&work->tv_getwork, &work->tv_work_found);
  813. bin2hex(target, work->target, sizeof(work->target));
  814. bin2hex(hash, work->hash, sizeof(work->hash));
  815. bin2hex(data, work->data, sizeof(work->data));
  816. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  817. 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);
  818. if (rv >= (int)(sizeof(s)))
  819. s[sizeof(s) - 1] = '\0';
  820. else if (rv < 0) {
  821. applog(LOG_ERR, "sharelog printf error");
  822. return;
  823. }
  824. mutex_lock(&sharelog_lock);
  825. ret = fwrite(s, rv, 1, sharelog_file);
  826. fflush(sharelog_file);
  827. mutex_unlock(&sharelog_lock);
  828. if (ret != 1)
  829. applog(LOG_ERR, "sharelog fwrite error");
  830. }
  831. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  832. /* Adjust all the pools' quota to the greatest common denominator after a pool
  833. * has been added or the quotas changed. */
  834. void adjust_quota_gcd(void)
  835. {
  836. unsigned long gcd, lowest_quota = ~0UL, quota;
  837. struct pool *pool;
  838. int i;
  839. for (i = 0; i < total_pools; i++) {
  840. pool = pools[i];
  841. quota = pool->quota;
  842. if (!quota)
  843. continue;
  844. if (quota < lowest_quota)
  845. lowest_quota = quota;
  846. }
  847. if (likely(lowest_quota < ~0UL)) {
  848. gcd = lowest_quota;
  849. for (i = 0; i < total_pools; i++) {
  850. pool = pools[i];
  851. quota = pool->quota;
  852. if (!quota)
  853. continue;
  854. while (quota % gcd)
  855. gcd--;
  856. }
  857. } else
  858. gcd = 1;
  859. for (i = 0; i < total_pools; i++) {
  860. pool = pools[i];
  861. pool->quota_used *= global_quota_gcd;
  862. pool->quota_used /= gcd;
  863. pool->quota_gcd = pool->quota / gcd;
  864. }
  865. global_quota_gcd = gcd;
  866. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  867. }
  868. /* Return value is ignored if not called from add_pool_details */
  869. struct pool *add_pool(void)
  870. {
  871. struct pool *pool;
  872. pool = calloc(sizeof(struct pool), 1);
  873. if (!pool)
  874. quit(1, "Failed to malloc pool in add_pool");
  875. pool->pool_no = pool->prio = total_pools;
  876. mutex_init(&pool->last_work_lock);
  877. mutex_init(&pool->pool_lock);
  878. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  879. quit(1, "Failed to pthread_cond_init in add_pool");
  880. cglock_init(&pool->data_lock);
  881. mutex_init(&pool->stratum_lock);
  882. timer_unset(&pool->swork.tv_transparency);
  883. /* Make sure the pool doesn't think we've been idle since time 0 */
  884. pool->tv_idle.tv_sec = ~0UL;
  885. cgtime(&pool->cgminer_stats.start_tv);
  886. pool->rpc_proxy = NULL;
  887. pool->quota = 1;
  888. adjust_quota_gcd();
  889. pool->sock = INVSOCK;
  890. pool->lp_socket = CURL_SOCKET_BAD;
  891. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  892. pools[total_pools++] = pool;
  893. return pool;
  894. }
  895. /* Pool variant of test and set */
  896. static bool pool_tset(struct pool *pool, bool *var)
  897. {
  898. bool ret;
  899. mutex_lock(&pool->pool_lock);
  900. ret = *var;
  901. *var = true;
  902. mutex_unlock(&pool->pool_lock);
  903. return ret;
  904. }
  905. bool pool_tclear(struct pool *pool, bool *var)
  906. {
  907. bool ret;
  908. mutex_lock(&pool->pool_lock);
  909. ret = *var;
  910. *var = false;
  911. mutex_unlock(&pool->pool_lock);
  912. return ret;
  913. }
  914. struct pool *current_pool(void)
  915. {
  916. struct pool *pool;
  917. cg_rlock(&control_lock);
  918. pool = currentpool;
  919. cg_runlock(&control_lock);
  920. return pool;
  921. }
  922. char *set_int_range(const char *arg, int *i, int min, int max)
  923. {
  924. char *err = opt_set_intval(arg, i);
  925. if (err)
  926. return err;
  927. if (*i < min || *i > max)
  928. return "Value out of range";
  929. return NULL;
  930. }
  931. static char *set_int_0_to_9999(const char *arg, int *i)
  932. {
  933. return set_int_range(arg, i, 0, 9999);
  934. }
  935. static char *set_int_1_to_65535(const char *arg, int *i)
  936. {
  937. return set_int_range(arg, i, 1, 65535);
  938. }
  939. static char *set_int_0_to_10(const char *arg, int *i)
  940. {
  941. return set_int_range(arg, i, 0, 10);
  942. }
  943. static char *set_int_1_to_10(const char *arg, int *i)
  944. {
  945. return set_int_range(arg, i, 1, 10);
  946. }
  947. char *set_strdup(const char *arg, char **p)
  948. {
  949. *p = strdup((char *)arg);
  950. return NULL;
  951. }
  952. #if BLKMAKER_VERSION > 1
  953. static char *set_b58addr(const char *arg, struct _cbscript_t *p)
  954. {
  955. size_t scriptsz = blkmk_address_to_script(NULL, 0, arg);
  956. if (!scriptsz)
  957. return "Invalid address";
  958. char *script = malloc(scriptsz);
  959. if (blkmk_address_to_script(script, scriptsz, arg) != scriptsz) {
  960. free(script);
  961. return "Failed to convert address to script";
  962. }
  963. p->data = script;
  964. p->sz = scriptsz;
  965. return NULL;
  966. }
  967. #endif
  968. static void bdiff_target_leadzero(unsigned char *target, double diff);
  969. char *set_request_diff(const char *arg, float *p)
  970. {
  971. unsigned char target[32];
  972. char *e = opt_set_floatval(arg, p);
  973. if (e)
  974. return e;
  975. request_bdiff = (double)*p * 0.9999847412109375;
  976. bdiff_target_leadzero(target, request_bdiff);
  977. request_target_str = malloc(65);
  978. bin2hex(request_target_str, target, 32);
  979. return NULL;
  980. }
  981. #ifdef NEED_BFG_LOWL_VCOM
  982. extern struct lowlevel_device_info *_vcom_devinfo_findorcreate(struct lowlevel_device_info **, const char *);
  983. #ifdef WIN32
  984. void _vcom_devinfo_scan_querydosdevice(struct lowlevel_device_info ** const devinfo_list)
  985. {
  986. char dev[PATH_MAX];
  987. char *devp = dev;
  988. size_t bufLen = 0x100;
  989. tryagain: ;
  990. char buf[bufLen];
  991. if (!QueryDosDevice(NULL, buf, bufLen)) {
  992. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  993. bufLen *= 2;
  994. applog(LOG_DEBUG, "QueryDosDevice returned insufficent buffer error; enlarging to %lx", (unsigned long)bufLen);
  995. goto tryagain;
  996. }
  997. applogr(, LOG_WARNING, "Error occurred trying to enumerate COM ports with QueryDosDevice");
  998. }
  999. size_t tLen;
  1000. memcpy(devp, "\\\\.\\", 4);
  1001. devp = &devp[4];
  1002. for (char *t = buf; *t; t += tLen) {
  1003. tLen = strlen(t) + 1;
  1004. if (strncmp("COM", t, 3))
  1005. continue;
  1006. memcpy(devp, t, tLen);
  1007. // NOTE: We depend on _vcom_devinfo_findorcreate to further check that there's a number (and only a number) on the end
  1008. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1009. }
  1010. }
  1011. #else
  1012. void _vcom_devinfo_scan_lsdev(struct lowlevel_device_info ** const devinfo_list)
  1013. {
  1014. char dev[PATH_MAX];
  1015. char *devp = dev;
  1016. DIR *D;
  1017. struct dirent *de;
  1018. const char devdir[] = "/dev";
  1019. const size_t devdirlen = sizeof(devdir) - 1;
  1020. char *devpath = devp;
  1021. char *devfile = devpath + devdirlen + 1;
  1022. D = opendir(devdir);
  1023. if (!D)
  1024. applogr(, LOG_DEBUG, "No /dev directory to look for VCOM devices in");
  1025. memcpy(devpath, devdir, devdirlen);
  1026. devpath[devdirlen] = '/';
  1027. while ( (de = readdir(D)) ) {
  1028. if (!strncmp(de->d_name, "cu.", 3))
  1029. goto trydev;
  1030. if (strncmp(de->d_name, "tty", 3))
  1031. continue;
  1032. if (strncmp(&de->d_name[3], "USB", 3) && strncmp(&de->d_name[3], "ACM", 3))
  1033. continue;
  1034. trydev:
  1035. strcpy(devfile, de->d_name);
  1036. _vcom_devinfo_findorcreate(devinfo_list, dev);
  1037. }
  1038. closedir(D);
  1039. }
  1040. #endif
  1041. #endif
  1042. static char *add_serial(const char *arg)
  1043. {
  1044. string_elist_add(arg, &scan_devices);
  1045. return NULL;
  1046. }
  1047. static
  1048. char *opt_string_elist_add(const char *arg, struct string_elist **elist)
  1049. {
  1050. string_elist_add(arg, elist);
  1051. return NULL;
  1052. }
  1053. bool get_intrange(const char *arg, int *val1, int *val2)
  1054. {
  1055. // NOTE: This could be done with sscanf, but its %n is broken in strange ways on Windows
  1056. char *p, *p2;
  1057. *val1 = strtol(arg, &p, 0);
  1058. if (arg == p)
  1059. // Zero-length ending number, invalid
  1060. return false;
  1061. while (true)
  1062. {
  1063. if (!p[0])
  1064. {
  1065. *val2 = *val1;
  1066. return true;
  1067. }
  1068. if (p[0] == '-')
  1069. break;
  1070. if (!isspace(p[0]))
  1071. // Garbage, invalid
  1072. return false;
  1073. ++p;
  1074. }
  1075. p2 = &p[1];
  1076. *val2 = strtol(p2, &p, 0);
  1077. if (p2 == p)
  1078. // Zero-length ending number, invalid
  1079. return false;
  1080. while (true)
  1081. {
  1082. if (!p[0])
  1083. return true;
  1084. if (!isspace(p[0]))
  1085. // Garbage, invalid
  1086. return false;
  1087. ++p;
  1088. }
  1089. }
  1090. static
  1091. void _test_intrange(const char *s, const int v[2])
  1092. {
  1093. int a[2];
  1094. if (!get_intrange(s, &a[0], &a[1]))
  1095. applog(LOG_ERR, "Test \"%s\" failed: returned false", s);
  1096. for (int i = 0; i < 2; ++i)
  1097. if (unlikely(a[i] != v[i]))
  1098. applog(LOG_ERR, "Test \"%s\" failed: value %d should be %d but got %d", s, i, v[i], a[i]);
  1099. }
  1100. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1101. static
  1102. void _test_intrange_fail(const char *s)
  1103. {
  1104. int a[2];
  1105. if (get_intrange(s, &a[0], &a[1]))
  1106. applog(LOG_ERR, "Test !\"%s\" failed: returned true with %d and %d", s, a[0], a[1]);
  1107. }
  1108. static
  1109. void test_intrange()
  1110. {
  1111. _test_intrange("-1--2", -1, -2);
  1112. _test_intrange("-1-2", -1, 2);
  1113. _test_intrange("1--2", 1, -2);
  1114. _test_intrange("1-2", 1, 2);
  1115. _test_intrange("111-222", 111, 222);
  1116. _test_intrange(" 11 - 22 ", 11, 22);
  1117. _test_intrange("+11-+22", 11, 22);
  1118. _test_intrange("-1", -1, -1);
  1119. _test_intrange_fail("all");
  1120. _test_intrange_fail("1-");
  1121. _test_intrange_fail("");
  1122. _test_intrange_fail("1-54x");
  1123. }
  1124. static char *set_devices(char *arg)
  1125. {
  1126. if (*arg) {
  1127. if (*arg == '?') {
  1128. opt_display_devs = true;
  1129. return NULL;
  1130. }
  1131. } else
  1132. return "Invalid device parameters";
  1133. string_elist_add(arg, &opt_devices_enabled_list);
  1134. return NULL;
  1135. }
  1136. static char *set_balance(enum pool_strategy *strategy)
  1137. {
  1138. *strategy = POOL_BALANCE;
  1139. return NULL;
  1140. }
  1141. static char *set_loadbalance(enum pool_strategy *strategy)
  1142. {
  1143. *strategy = POOL_LOADBALANCE;
  1144. return NULL;
  1145. }
  1146. static char *set_rotate(const char *arg, int *i)
  1147. {
  1148. pool_strategy = POOL_ROTATE;
  1149. return set_int_range(arg, i, 0, 9999);
  1150. }
  1151. static char *set_rr(enum pool_strategy *strategy)
  1152. {
  1153. *strategy = POOL_ROUNDROBIN;
  1154. return NULL;
  1155. }
  1156. /* Detect that url is for a stratum protocol either via the presence of
  1157. * stratum+tcp or by detecting a stratum server response */
  1158. bool detect_stratum(struct pool *pool, char *url)
  1159. {
  1160. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  1161. return false;
  1162. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  1163. pool->rpc_url = strdup(url);
  1164. pool->has_stratum = true;
  1165. pool->stratum_url = pool->sockaddr_url;
  1166. return true;
  1167. }
  1168. return false;
  1169. }
  1170. static struct pool *add_url(void)
  1171. {
  1172. total_urls++;
  1173. if (total_urls > total_pools)
  1174. add_pool();
  1175. return pools[total_urls - 1];
  1176. }
  1177. static void setup_url(struct pool *pool, char *arg)
  1178. {
  1179. if (detect_stratum(pool, arg))
  1180. return;
  1181. opt_set_charp(arg, &pool->rpc_url);
  1182. if (strncmp(arg, "http://", 7) &&
  1183. strncmp(arg, "https://", 8)) {
  1184. char *httpinput;
  1185. httpinput = malloc(255);
  1186. if (!httpinput)
  1187. quit(1, "Failed to malloc httpinput");
  1188. strcpy(httpinput, "http://");
  1189. strncat(httpinput, arg, 248);
  1190. pool->rpc_url = httpinput;
  1191. }
  1192. }
  1193. static char *set_url(char *arg)
  1194. {
  1195. struct pool *pool = add_url();
  1196. setup_url(pool, arg);
  1197. return NULL;
  1198. }
  1199. static char *set_quota(char *arg)
  1200. {
  1201. char *semicolon = strchr(arg, ';'), *url;
  1202. int len, qlen, quota;
  1203. struct pool *pool;
  1204. if (!semicolon)
  1205. return "No semicolon separated quota;URL pair found";
  1206. len = strlen(arg);
  1207. *semicolon = '\0';
  1208. qlen = strlen(arg);
  1209. if (!qlen)
  1210. return "No parameter for quota found";
  1211. len -= qlen + 1;
  1212. if (len < 1)
  1213. return "No parameter for URL found";
  1214. quota = atoi(arg);
  1215. if (quota < 0)
  1216. return "Invalid negative parameter for quota set";
  1217. url = arg + qlen + 1;
  1218. pool = add_url();
  1219. setup_url(pool, url);
  1220. pool->quota = quota;
  1221. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  1222. adjust_quota_gcd();
  1223. return NULL;
  1224. }
  1225. static char *set_user(const char *arg)
  1226. {
  1227. struct pool *pool;
  1228. total_users++;
  1229. if (total_users > total_pools)
  1230. add_pool();
  1231. pool = pools[total_users - 1];
  1232. opt_set_charp(arg, &pool->rpc_user);
  1233. return NULL;
  1234. }
  1235. static char *set_pass(const char *arg)
  1236. {
  1237. struct pool *pool;
  1238. total_passes++;
  1239. if (total_passes > total_pools)
  1240. add_pool();
  1241. pool = pools[total_passes - 1];
  1242. opt_set_charp(arg, &pool->rpc_pass);
  1243. return NULL;
  1244. }
  1245. static char *set_userpass(const char *arg)
  1246. {
  1247. struct pool *pool;
  1248. char *updup;
  1249. if (total_users != total_passes)
  1250. return "User + pass options must be balanced before userpass";
  1251. ++total_users;
  1252. ++total_passes;
  1253. if (total_users > total_pools)
  1254. add_pool();
  1255. pool = pools[total_users - 1];
  1256. updup = strdup(arg);
  1257. opt_set_charp(arg, &pool->rpc_userpass);
  1258. pool->rpc_user = strtok(updup, ":");
  1259. if (!pool->rpc_user)
  1260. return "Failed to find : delimited user info";
  1261. pool->rpc_pass = strtok(NULL, ":");
  1262. if (!pool->rpc_pass)
  1263. pool->rpc_pass = "";
  1264. return NULL;
  1265. }
  1266. static char *set_pool_priority(const char *arg)
  1267. {
  1268. struct pool *pool;
  1269. if (!total_pools)
  1270. return "Usage of --pool-priority before pools are defined does not make sense";
  1271. pool = pools[total_pools - 1];
  1272. opt_set_intval(arg, &pool->prio);
  1273. return NULL;
  1274. }
  1275. static char *set_pool_proxy(const char *arg)
  1276. {
  1277. struct pool *pool;
  1278. if (!total_pools)
  1279. return "Usage of --pool-proxy before pools are defined does not make sense";
  1280. if (!our_curl_supports_proxy_uris())
  1281. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  1282. pool = pools[total_pools - 1];
  1283. opt_set_charp(arg, &pool->rpc_proxy);
  1284. return NULL;
  1285. }
  1286. static char *set_pool_force_rollntime(const char *arg)
  1287. {
  1288. struct pool *pool;
  1289. if (!total_pools)
  1290. return "Usage of --force-rollntime before pools are defined does not make sense";
  1291. pool = pools[total_pools - 1];
  1292. opt_set_intval(arg, &pool->force_rollntime);
  1293. return NULL;
  1294. }
  1295. static char *enable_debug(bool *flag)
  1296. {
  1297. *flag = true;
  1298. opt_debug_console = true;
  1299. /* Turn on verbose output, too. */
  1300. opt_log_output = true;
  1301. return NULL;
  1302. }
  1303. static char *set_schedtime(const char *arg, struct schedtime *st)
  1304. {
  1305. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  1306. {
  1307. if (strcasecmp(arg, "now"))
  1308. return "Invalid time set, should be HH:MM";
  1309. } else
  1310. schedstop.tm.tm_sec = 0;
  1311. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  1312. return "Invalid time set.";
  1313. st->enable = true;
  1314. return NULL;
  1315. }
  1316. static
  1317. char *set_log_file(char *arg)
  1318. {
  1319. char *r = "";
  1320. long int i = strtol(arg, &r, 10);
  1321. int fd, stderr_fd = fileno(stderr);
  1322. if ((!*r) && i >= 0 && i <= INT_MAX)
  1323. fd = i;
  1324. else
  1325. if (!strcmp(arg, "-"))
  1326. {
  1327. fd = fileno(stdout);
  1328. if (unlikely(fd == -1))
  1329. return "Standard output missing for log-file";
  1330. }
  1331. else
  1332. {
  1333. fd = open(arg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
  1334. if (unlikely(fd == -1))
  1335. return "Failed to open log-file";
  1336. }
  1337. close(stderr_fd);
  1338. if (unlikely(-1 == dup2(fd, stderr_fd)))
  1339. return "Failed to dup2 for log-file";
  1340. close(fd);
  1341. return NULL;
  1342. }
  1343. static
  1344. char *_bfgopt_set_file(const char *arg, FILE **F, const char *mode, const char *purpose)
  1345. {
  1346. char *r = "";
  1347. long int i = strtol(arg, &r, 10);
  1348. static char *err = NULL;
  1349. const size_t errbufsz = 0x100;
  1350. free(err);
  1351. err = NULL;
  1352. if ((!*r) && i >= 0 && i <= INT_MAX) {
  1353. *F = fdopen((int)i, mode);
  1354. if (!*F)
  1355. {
  1356. err = malloc(errbufsz);
  1357. snprintf(err, errbufsz, "Failed to open fd %d for %s",
  1358. (int)i, purpose);
  1359. return err;
  1360. }
  1361. } else if (!strcmp(arg, "-")) {
  1362. *F = (mode[0] == 'a') ? stdout : stdin;
  1363. if (!*F)
  1364. {
  1365. err = malloc(errbufsz);
  1366. snprintf(err, errbufsz, "Standard %sput missing for %s",
  1367. (mode[0] == 'a') ? "out" : "in", purpose);
  1368. return err;
  1369. }
  1370. } else {
  1371. *F = fopen(arg, mode);
  1372. if (!*F)
  1373. {
  1374. err = malloc(errbufsz);
  1375. snprintf(err, errbufsz, "Failed to open %s for %s",
  1376. arg, purpose);
  1377. return err;
  1378. }
  1379. }
  1380. return NULL;
  1381. }
  1382. static char *set_noncelog(char *arg)
  1383. {
  1384. return _bfgopt_set_file(arg, &noncelog_file, "a", "nonce log");
  1385. }
  1386. static char *set_sharelog(char *arg)
  1387. {
  1388. return _bfgopt_set_file(arg, &sharelog_file, "a", "share log");
  1389. }
  1390. static char *temp_cutoff_str = "";
  1391. static char *temp_target_str = "";
  1392. char *set_temp_cutoff(char *arg)
  1393. {
  1394. int val;
  1395. if (!(arg && arg[0]))
  1396. return "Invalid parameters for set temp cutoff";
  1397. val = atoi(arg);
  1398. if (val < 0 || val > 200)
  1399. return "Invalid value passed to set temp cutoff";
  1400. temp_cutoff_str = arg;
  1401. return NULL;
  1402. }
  1403. char *set_temp_target(char *arg)
  1404. {
  1405. int val;
  1406. if (!(arg && arg[0]))
  1407. return "Invalid parameters for set temp target";
  1408. val = atoi(arg);
  1409. if (val < 0 || val > 200)
  1410. return "Invalid value passed to set temp target";
  1411. temp_target_str = arg;
  1412. return NULL;
  1413. }
  1414. // For a single element string, this always returns the number (for all calls)
  1415. // For multi-element strings, it returns each element as a number in order, and 0 when there are no more
  1416. static int temp_strtok(char *base, char **n)
  1417. {
  1418. char *i = *n;
  1419. char *p = strchr(i, ',');
  1420. if (p) {
  1421. p[0] = '\0';
  1422. *n = &p[1];
  1423. }
  1424. else
  1425. if (base != i)
  1426. *n = strchr(i, '\0');
  1427. return atoi(i);
  1428. }
  1429. static void load_temp_config_cgpu(struct cgpu_info *cgpu, char **cutoff_np, char **target_np)
  1430. {
  1431. int target_off, val;
  1432. // cutoff default may be specified by driver during probe; otherwise, opt_cutofftemp (const)
  1433. if (!cgpu->cutofftemp)
  1434. cgpu->cutofftemp = opt_cutofftemp;
  1435. // target default may be specified by driver, and is moved with offset; otherwise, offset minus 6
  1436. if (cgpu->targettemp)
  1437. target_off = cgpu->targettemp - cgpu->cutofftemp;
  1438. else
  1439. target_off = -6;
  1440. cgpu->cutofftemp_default = cgpu->cutofftemp;
  1441. val = temp_strtok(temp_cutoff_str, cutoff_np);
  1442. if (val < 0 || val > 200)
  1443. quit(1, "Invalid value passed to set temp cutoff");
  1444. if (val)
  1445. cgpu->cutofftemp = val;
  1446. cgpu->targettemp_default = cgpu->cutofftemp + target_off;
  1447. val = temp_strtok(temp_target_str, target_np);
  1448. if (val < 0 || val > 200)
  1449. quit(1, "Invalid value passed to set temp target");
  1450. if (val)
  1451. cgpu->targettemp = val;
  1452. else
  1453. cgpu->targettemp = cgpu->cutofftemp + target_off;
  1454. applog(LOG_DEBUG, "%"PRIprepr": Set temperature config: target=%d cutoff=%d",
  1455. cgpu->proc_repr,
  1456. cgpu->targettemp, cgpu->cutofftemp);
  1457. }
  1458. static void load_temp_config()
  1459. {
  1460. int i;
  1461. char *cutoff_n, *target_n;
  1462. struct cgpu_info *cgpu;
  1463. cutoff_n = temp_cutoff_str;
  1464. target_n = temp_target_str;
  1465. for (i = 0; i < total_devices; ++i) {
  1466. cgpu = get_devices(i);
  1467. load_temp_config_cgpu(cgpu, &cutoff_n, &target_n);
  1468. }
  1469. if (cutoff_n != temp_cutoff_str && cutoff_n[0])
  1470. quit(1, "Too many values passed to set temp cutoff");
  1471. if (target_n != temp_target_str && target_n[0])
  1472. quit(1, "Too many values passed to set temp target");
  1473. }
  1474. static char *set_api_allow(const char *arg)
  1475. {
  1476. opt_set_charp(arg, &opt_api_allow);
  1477. return NULL;
  1478. }
  1479. static char *set_api_groups(const char *arg)
  1480. {
  1481. opt_set_charp(arg, &opt_api_groups);
  1482. return NULL;
  1483. }
  1484. static char *set_api_description(const char *arg)
  1485. {
  1486. opt_set_charp(arg, &opt_api_description);
  1487. return NULL;
  1488. }
  1489. static char *set_api_mcast_des(const char *arg)
  1490. {
  1491. opt_set_charp(arg, &opt_api_mcast_des);
  1492. return NULL;
  1493. }
  1494. #ifdef USE_ICARUS
  1495. static char *set_icarus_options(const char *arg)
  1496. {
  1497. opt_set_charp(arg, &opt_icarus_options);
  1498. return NULL;
  1499. }
  1500. static char *set_icarus_timing(const char *arg)
  1501. {
  1502. opt_set_charp(arg, &opt_icarus_timing);
  1503. return NULL;
  1504. }
  1505. #endif
  1506. #ifdef USE_AVALON
  1507. static char *set_avalon_options(const char *arg)
  1508. {
  1509. opt_set_charp(arg, &opt_avalon_options);
  1510. return NULL;
  1511. }
  1512. #endif
  1513. #ifdef USE_KLONDIKE
  1514. static char *set_klondike_options(const char *arg)
  1515. {
  1516. opt_set_charp(arg, &opt_klondike_options);
  1517. return NULL;
  1518. }
  1519. #endif
  1520. __maybe_unused
  1521. static char *set_null(const char __maybe_unused *arg)
  1522. {
  1523. return NULL;
  1524. }
  1525. /* These options are available from config file or commandline */
  1526. static struct opt_table opt_config_table[] = {
  1527. #ifdef WANT_CPUMINE
  1528. OPT_WITH_ARG("--algo|-a",
  1529. set_algo, show_algo, &opt_algo,
  1530. "Specify sha256 implementation for CPU mining:\n"
  1531. "\tfastauto*\tQuick benchmark at startup to pick a working algorithm\n"
  1532. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  1533. "\n\tc\t\tLinux kernel sha256, implemented in C"
  1534. #ifdef WANT_SSE2_4WAY
  1535. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  1536. #endif
  1537. #ifdef WANT_VIA_PADLOCK
  1538. "\n\tvia\t\tVIA padlock implementation"
  1539. #endif
  1540. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  1541. #ifdef WANT_CRYPTOPP_ASM32
  1542. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  1543. #endif
  1544. #ifdef WANT_X8632_SSE2
  1545. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  1546. #endif
  1547. #ifdef WANT_X8664_SSE2
  1548. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  1549. #endif
  1550. #ifdef WANT_X8664_SSE4
  1551. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  1552. #endif
  1553. #ifdef WANT_ALTIVEC_4WAY
  1554. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  1555. #endif
  1556. ),
  1557. #endif
  1558. OPT_WITH_ARG("--api-allow",
  1559. set_api_allow, NULL, NULL,
  1560. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  1561. OPT_WITH_ARG("--api-description",
  1562. set_api_description, NULL, NULL,
  1563. "Description placed in the API status header, default: BFGMiner version"),
  1564. OPT_WITH_ARG("--api-groups",
  1565. set_api_groups, NULL, NULL,
  1566. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  1567. OPT_WITHOUT_ARG("--api-listen",
  1568. opt_set_bool, &opt_api_listen,
  1569. "Enable API, default: disabled"),
  1570. OPT_WITHOUT_ARG("--api-mcast",
  1571. opt_set_bool, &opt_api_mcast,
  1572. "Enable API Multicast listener, default: disabled"),
  1573. OPT_WITH_ARG("--api-mcast-addr",
  1574. opt_set_charp, opt_show_charp, &opt_api_mcast_addr,
  1575. "API Multicast listen address"),
  1576. OPT_WITH_ARG("--api-mcast-code",
  1577. opt_set_charp, opt_show_charp, &opt_api_mcast_code,
  1578. "Code expected in the API Multicast message, don't use '-'"),
  1579. OPT_WITH_ARG("--api-mcast-des",
  1580. set_api_mcast_des, NULL, NULL,
  1581. "Description appended to the API Multicast reply, default: ''"),
  1582. OPT_WITH_ARG("--api-mcast-port",
  1583. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  1584. "API Multicast listen port"),
  1585. OPT_WITHOUT_ARG("--api-network",
  1586. opt_set_bool, &opt_api_network,
  1587. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  1588. OPT_WITH_ARG("--api-port",
  1589. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  1590. "Port number of miner API"),
  1591. #ifdef HAVE_ADL
  1592. OPT_WITHOUT_ARG("--auto-fan",
  1593. opt_set_bool, &opt_autofan,
  1594. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  1595. OPT_WITHOUT_ARG("--auto-gpu",
  1596. opt_set_bool, &opt_autoengine,
  1597. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  1598. #endif
  1599. OPT_WITHOUT_ARG("--balance",
  1600. set_balance, &pool_strategy,
  1601. "Change multipool strategy from failover to even share balance"),
  1602. OPT_WITHOUT_ARG("--benchmark",
  1603. opt_set_bool, &opt_benchmark,
  1604. "Run BFGMiner in benchmark mode - produces no shares"),
  1605. #if defined(USE_BITFORCE)
  1606. OPT_WITHOUT_ARG("--bfl-range",
  1607. opt_set_bool, &opt_bfl_noncerange,
  1608. "Use nonce range on bitforce devices if supported"),
  1609. #endif
  1610. #ifdef WANT_CPUMINE
  1611. OPT_WITH_ARG("--bench-algo|-b",
  1612. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  1613. opt_hidden),
  1614. #endif
  1615. #ifdef HAVE_CHROOT
  1616. OPT_WITH_ARG("--chroot-dir",
  1617. opt_set_charp, NULL, &chroot_dir,
  1618. "Chroot to a directory right after startup"),
  1619. #endif
  1620. OPT_WITH_ARG("--cmd-idle",
  1621. opt_set_charp, NULL, &cmd_idle,
  1622. "Execute a command when a device is allowed to be idle (rest or wait)"),
  1623. OPT_WITH_ARG("--cmd-sick",
  1624. opt_set_charp, NULL, &cmd_sick,
  1625. "Execute a command when a device is declared sick"),
  1626. OPT_WITH_ARG("--cmd-dead",
  1627. opt_set_charp, NULL, &cmd_dead,
  1628. "Execute a command when a device is declared dead"),
  1629. #if BLKMAKER_VERSION > 1
  1630. OPT_WITH_ARG("--coinbase-addr",
  1631. set_b58addr, NULL, &opt_coinbase_script,
  1632. "Set coinbase payout address for solo mining"),
  1633. OPT_WITH_ARG("--coinbase-payout|--cbaddr|--cb-addr|--payout",
  1634. set_b58addr, NULL, &opt_coinbase_script,
  1635. opt_hidden),
  1636. #endif
  1637. #if BLKMAKER_VERSION > 0
  1638. OPT_WITH_ARG("--coinbase-sig",
  1639. set_strdup, NULL, &opt_coinbase_sig,
  1640. "Set coinbase signature when possible"),
  1641. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  1642. set_strdup, NULL, &opt_coinbase_sig,
  1643. opt_hidden),
  1644. #endif
  1645. #ifdef HAVE_CURSES
  1646. OPT_WITHOUT_ARG("--compact",
  1647. opt_set_bool, &opt_compact,
  1648. "Use compact display without per device statistics"),
  1649. #endif
  1650. #ifdef WANT_CPUMINE
  1651. OPT_WITH_ARG("--cpu-threads|-t",
  1652. force_nthreads_int, opt_show_intval, &opt_n_threads,
  1653. "Number of miner CPU threads"),
  1654. #endif
  1655. OPT_WITHOUT_ARG("--debug|-D",
  1656. enable_debug, &opt_debug,
  1657. "Enable debug output"),
  1658. OPT_WITHOUT_ARG("--debuglog",
  1659. opt_set_bool, &opt_debug,
  1660. "Enable debug logging"),
  1661. OPT_WITHOUT_ARG("--device-protocol-dump",
  1662. opt_set_bool, &opt_dev_protocol,
  1663. "Verbose dump of device protocol-level activities"),
  1664. OPT_WITH_ARG("--device|-d",
  1665. set_devices, NULL, NULL,
  1666. "Enable only devices matching pattern (default: all)"),
  1667. OPT_WITHOUT_ARG("--disable-rejecting",
  1668. opt_set_bool, &opt_disable_pool,
  1669. "Automatically disable pools that continually reject shares"),
  1670. #ifdef USE_LIBMICROHTTPD
  1671. OPT_WITH_ARG("--http-port",
  1672. opt_set_intval, opt_show_intval, &httpsrv_port,
  1673. "Port number to listen on for HTTP getwork miners (-1 means disabled)"),
  1674. #endif
  1675. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  1676. OPT_WITHOUT_ARG("--enable-cpu|-C",
  1677. opt_set_bool, &opt_usecpu,
  1678. opt_hidden),
  1679. #endif
  1680. OPT_WITH_ARG("--expiry|-E",
  1681. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1682. "Upper bound on how many seconds after getting work we consider a share from it stale (w/o longpoll active)"),
  1683. OPT_WITH_ARG("--expiry-lp",
  1684. set_int_0_to_9999, opt_show_intval, &opt_expiry_lp,
  1685. "Upper bound on how many seconds after getting work we consider a share from it stale (with longpoll active)"),
  1686. OPT_WITHOUT_ARG("--failover-only",
  1687. opt_set_bool, &opt_fail_only,
  1688. "Don't leak work to backup pools when primary pool is lagging"),
  1689. #ifdef USE_FPGA
  1690. OPT_WITHOUT_ARG("--force-dev-init",
  1691. opt_set_bool, &opt_force_dev_init,
  1692. "Always initialize devices when possible (such as bitstream uploads to some FPGAs)"),
  1693. #endif
  1694. #ifdef HAVE_OPENCL
  1695. OPT_WITH_ARG("--gpu-dyninterval",
  1696. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  1697. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  1698. OPT_WITH_ARG("--gpu-platform",
  1699. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  1700. "Select OpenCL platform ID to use for GPU mining"),
  1701. OPT_WITH_ARG("--gpu-threads|-g",
  1702. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  1703. "Number of threads per GPU (1 - 10)"),
  1704. #ifdef HAVE_ADL
  1705. OPT_WITH_ARG("--gpu-engine",
  1706. set_gpu_engine, NULL, NULL,
  1707. "GPU engine (over)clock range in MHz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  1708. OPT_WITH_ARG("--gpu-fan",
  1709. set_gpu_fan, NULL, NULL,
  1710. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  1711. OPT_WITH_ARG("--gpu-map",
  1712. set_gpu_map, NULL, NULL,
  1713. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  1714. OPT_WITH_ARG("--gpu-memclock",
  1715. set_gpu_memclock, NULL, NULL,
  1716. "Set the GPU memory (over)clock in MHz - one value for all or separate by commas for per card"),
  1717. OPT_WITH_ARG("--gpu-memdiff",
  1718. set_gpu_memdiff, NULL, NULL,
  1719. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  1720. OPT_WITH_ARG("--gpu-powertune",
  1721. set_gpu_powertune, NULL, NULL,
  1722. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  1723. OPT_WITHOUT_ARG("--gpu-reorder",
  1724. opt_set_bool, &opt_reorder,
  1725. "Attempt to reorder GPU devices according to PCI Bus ID"),
  1726. OPT_WITH_ARG("--gpu-vddc",
  1727. set_gpu_vddc, NULL, NULL,
  1728. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  1729. #endif
  1730. #ifdef USE_SCRYPT
  1731. OPT_WITH_ARG("--lookup-gap",
  1732. set_lookup_gap, NULL, NULL,
  1733. "Set GPU lookup gap for scrypt mining, comma separated"),
  1734. OPT_WITH_ARG("--intensity|-I",
  1735. set_intensity, NULL, NULL,
  1736. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1737. " -> " MAX_SCRYPT_INTENSITY_STR
  1738. ",default: d to maintain desktop interactivity)"),
  1739. #else
  1740. OPT_WITH_ARG("--intensity|-I",
  1741. set_intensity, NULL, NULL,
  1742. "Intensity of GPU scanning (d or " MIN_SHA_INTENSITY_STR
  1743. " -> " MAX_SHA_INTENSITY_STR
  1744. ",default: d to maintain desktop interactivity)"),
  1745. #endif
  1746. #endif
  1747. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_X6500) || defined(USE_ZTEX)
  1748. OPT_WITH_ARG("--kernel-path|-K",
  1749. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1750. "Specify a path to where bitstream and kernel files are"),
  1751. #endif
  1752. #ifdef HAVE_OPENCL
  1753. OPT_WITH_ARG("--kernel|-k",
  1754. set_kernel, NULL, NULL,
  1755. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  1756. #endif
  1757. #ifdef USE_ICARUS
  1758. OPT_WITH_ARG("--icarus-options",
  1759. set_icarus_options, NULL, NULL,
  1760. opt_hidden),
  1761. OPT_WITH_ARG("--icarus-timing",
  1762. set_icarus_timing, NULL, NULL,
  1763. opt_hidden),
  1764. #endif
  1765. #ifdef USE_AVALON
  1766. OPT_WITH_ARG("--avalon-options",
  1767. set_avalon_options, NULL, NULL,
  1768. opt_hidden),
  1769. #endif
  1770. #ifdef USE_KLONDIKE
  1771. OPT_WITH_ARG("--klondike-options",
  1772. set_klondike_options, NULL, NULL,
  1773. "Set klondike options clock:temptarget"),
  1774. #endif
  1775. OPT_WITHOUT_ARG("--load-balance",
  1776. set_loadbalance, &pool_strategy,
  1777. "Change multipool strategy from failover to quota based balance"),
  1778. OPT_WITH_ARG("--log|-l",
  1779. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1780. "Interval in seconds between log output"),
  1781. OPT_WITH_ARG("--log-file|-L",
  1782. set_log_file, NULL, NULL,
  1783. "Append log file for output messages"),
  1784. OPT_WITH_ARG("--logfile",
  1785. set_log_file, NULL, NULL,
  1786. opt_hidden),
  1787. OPT_WITHOUT_ARG("--log-microseconds",
  1788. opt_set_bool, &opt_log_microseconds,
  1789. "Include microseconds in log output"),
  1790. #if defined(unix) || defined(__APPLE__)
  1791. OPT_WITH_ARG("--monitor|-m",
  1792. opt_set_charp, NULL, &opt_stderr_cmd,
  1793. "Use custom pipe cmd for output messages"),
  1794. #endif // defined(unix)
  1795. OPT_WITHOUT_ARG("--net-delay",
  1796. opt_set_bool, &opt_delaynet,
  1797. "Impose small delays in networking to avoid overloading slow routers"),
  1798. OPT_WITHOUT_ARG("--no-adl",
  1799. opt_set_bool, &opt_noadl,
  1800. #ifdef HAVE_ADL
  1801. "Disable the ATI display library used for monitoring and setting GPU parameters"
  1802. #else
  1803. opt_hidden
  1804. #endif
  1805. ),
  1806. OPT_WITHOUT_ARG("--no-gbt",
  1807. opt_set_invbool, &want_gbt,
  1808. "Disable getblocktemplate support"),
  1809. OPT_WITHOUT_ARG("--no-getwork",
  1810. opt_set_invbool, &want_getwork,
  1811. "Disable getwork support"),
  1812. OPT_WITHOUT_ARG("--no-longpoll",
  1813. opt_set_invbool, &want_longpoll,
  1814. "Disable X-Long-Polling support"),
  1815. OPT_WITHOUT_ARG("--no-pool-disable",
  1816. opt_set_invbool, &opt_disable_pool,
  1817. opt_hidden),
  1818. OPT_WITHOUT_ARG("--no-restart",
  1819. opt_set_invbool, &opt_restart,
  1820. "Do not attempt to restart devices that hang"
  1821. ),
  1822. OPT_WITHOUT_ARG("--no-show-processors",
  1823. opt_set_invbool, &opt_show_procs,
  1824. opt_hidden),
  1825. OPT_WITHOUT_ARG("--no-show-procs",
  1826. opt_set_invbool, &opt_show_procs,
  1827. opt_hidden),
  1828. OPT_WITHOUT_ARG("--no-stratum",
  1829. opt_set_invbool, &want_stratum,
  1830. "Disable Stratum detection"),
  1831. OPT_WITHOUT_ARG("--no-submit-stale",
  1832. opt_set_invbool, &opt_submit_stale,
  1833. "Don't submit shares if they are detected as stale"),
  1834. #ifdef HAVE_OPENCL
  1835. OPT_WITHOUT_ARG("--no-opencl-binaries",
  1836. opt_set_invbool, &opt_opencl_binaries,
  1837. "Don't attempt to use or save OpenCL kernel binaries"),
  1838. #endif
  1839. OPT_WITHOUT_ARG("--no-unicode",
  1840. #ifdef USE_UNICODE
  1841. opt_set_invbool, &use_unicode,
  1842. "Don't use Unicode characters in TUI"
  1843. #else
  1844. set_null, &use_unicode,
  1845. opt_hidden
  1846. #endif
  1847. ),
  1848. OPT_WITH_ARG("--noncelog",
  1849. set_noncelog, NULL, NULL,
  1850. "Create log of all nonces found"),
  1851. OPT_WITH_ARG("--pass|-p",
  1852. set_pass, NULL, NULL,
  1853. "Password for bitcoin JSON-RPC server"),
  1854. OPT_WITHOUT_ARG("--per-device-stats",
  1855. opt_set_bool, &want_per_device_stats,
  1856. "Force verbose mode and output per-device statistics"),
  1857. OPT_WITH_ARG("--userpass|-O", // duplicate to ensure config loads it before pool-priority
  1858. set_userpass, NULL, NULL,
  1859. opt_hidden),
  1860. OPT_WITH_ARG("--pool-priority",
  1861. set_pool_priority, NULL, NULL,
  1862. "Priority for just the previous-defined pool"),
  1863. OPT_WITH_ARG("--pool-proxy|-x",
  1864. set_pool_proxy, NULL, NULL,
  1865. "Proxy URI to use for connecting to just the previous-defined pool"),
  1866. OPT_WITH_ARG("--force-rollntime", // NOTE: must be after --pass for config file ordering
  1867. set_pool_force_rollntime, NULL, NULL,
  1868. opt_hidden),
  1869. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1870. opt_set_bool, &opt_protocol,
  1871. "Verbose dump of protocol-level activities"),
  1872. OPT_WITH_ARG("--queue|-Q",
  1873. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1874. "Minimum number of work items to have queued (0+)"),
  1875. OPT_WITHOUT_ARG("--quiet|-q",
  1876. opt_set_bool, &opt_quiet,
  1877. "Disable logging output, display status and errors"),
  1878. OPT_WITHOUT_ARG("--quiet-work-updates|--quiet-work-update",
  1879. opt_set_bool, &opt_quiet_work_updates,
  1880. opt_hidden),
  1881. OPT_WITH_ARG("--quota|-U",
  1882. set_quota, NULL, NULL,
  1883. "quota;URL combination for server with load-balance strategy quotas"),
  1884. OPT_WITHOUT_ARG("--real-quiet",
  1885. opt_set_bool, &opt_realquiet,
  1886. "Disable all output"),
  1887. OPT_WITH_ARG("--request-diff",
  1888. set_request_diff, opt_show_floatval, &request_pdiff,
  1889. "Request a specific difficulty from pools"),
  1890. OPT_WITH_ARG("--retries",
  1891. opt_set_intval, opt_show_intval, &opt_retries,
  1892. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1893. OPT_WITH_ARG("--retry-pause",
  1894. set_null, NULL, NULL,
  1895. opt_hidden),
  1896. OPT_WITH_ARG("--rotate",
  1897. set_rotate, opt_show_intval, &opt_rotate_period,
  1898. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1899. OPT_WITHOUT_ARG("--round-robin",
  1900. set_rr, &pool_strategy,
  1901. "Change multipool strategy from failover to round robin on failure"),
  1902. OPT_WITH_ARG("--scan|-S",
  1903. add_serial, NULL, NULL,
  1904. "Configure how to scan for mining devices"),
  1905. OPT_WITH_ARG("--scan-device|--scan-serial|--devscan",
  1906. add_serial, NULL, NULL,
  1907. opt_hidden),
  1908. OPT_WITH_ARG("--scan-time|-s",
  1909. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1910. "Upper bound on time spent scanning current work, in seconds"),
  1911. OPT_WITH_ARG("--scantime",
  1912. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1913. opt_hidden),
  1914. OPT_WITH_ARG("--sched-start",
  1915. set_schedtime, NULL, &schedstart,
  1916. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1917. OPT_WITH_ARG("--sched-stop",
  1918. set_schedtime, NULL, &schedstop,
  1919. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1920. #ifdef USE_SCRYPT
  1921. OPT_WITHOUT_ARG("--scrypt",
  1922. opt_set_bool, &opt_scrypt,
  1923. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1924. #endif
  1925. OPT_WITH_ARG("--set-device",
  1926. opt_string_elist_add, NULL, &opt_set_device_list,
  1927. "Set default parameters on devices; eg, NFY:osc6_bits=50"),
  1928. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1929. OPT_WITH_ARG("--shaders",
  1930. set_shaders, NULL, NULL,
  1931. "GPU shaders per card for tuning scrypt, comma separated"),
  1932. #endif
  1933. #ifdef HAVE_PWD_H
  1934. OPT_WITH_ARG("--setuid",
  1935. opt_set_charp, NULL, &opt_setuid,
  1936. "Username of an unprivileged user to run as"),
  1937. #endif
  1938. OPT_WITH_ARG("--sharelog",
  1939. set_sharelog, NULL, NULL,
  1940. "Append share log to file"),
  1941. OPT_WITH_ARG("--shares",
  1942. opt_set_intval, NULL, &opt_shares,
  1943. "Quit after mining N shares (default: unlimited)"),
  1944. OPT_WITHOUT_ARG("--show-processors",
  1945. opt_set_bool, &opt_show_procs,
  1946. "Show per processor statistics in summary"),
  1947. OPT_WITHOUT_ARG("--show-procs",
  1948. opt_set_bool, &opt_show_procs,
  1949. opt_hidden),
  1950. OPT_WITH_ARG("--skip-security-checks",
  1951. set_int_0_to_9999, NULL, &opt_skip_checks,
  1952. "Skip security checks sometimes to save bandwidth; only check 1/<arg>th of the time (default: never skip)"),
  1953. OPT_WITH_ARG("--socks-proxy",
  1954. opt_set_charp, NULL, &opt_socks_proxy,
  1955. "Set socks proxy (host:port)"),
  1956. #ifdef USE_LIBEVENT
  1957. OPT_WITH_ARG("--stratum-port",
  1958. opt_set_intval, opt_show_intval, &stratumsrv_port,
  1959. "Port number to listen on for stratum miners (-1 means disabled)"),
  1960. #endif
  1961. OPT_WITHOUT_ARG("--submit-stale",
  1962. opt_set_bool, &opt_submit_stale,
  1963. opt_hidden),
  1964. OPT_WITH_ARG("--submit-threads",
  1965. opt_set_intval, opt_show_intval, &opt_submit_threads,
  1966. "Minimum number of concurrent share submissions (default: 64)"),
  1967. #ifdef HAVE_SYSLOG_H
  1968. OPT_WITHOUT_ARG("--syslog",
  1969. opt_set_bool, &use_syslog,
  1970. "Use system log for output messages (default: standard error)"),
  1971. #endif
  1972. OPT_WITH_ARG("--temp-cutoff",
  1973. set_temp_cutoff, NULL, &opt_cutofftemp,
  1974. "Maximum temperature devices will be allowed to reach before being disabled, one value or comma separated list"),
  1975. OPT_WITH_ARG("--temp-hysteresis",
  1976. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  1977. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1978. #ifdef HAVE_ADL
  1979. OPT_WITH_ARG("--temp-overheat",
  1980. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  1981. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1982. #endif
  1983. OPT_WITH_ARG("--temp-target",
  1984. set_temp_target, NULL, NULL,
  1985. "Target temperature when automatically managing fan and clock speeds, one value or comma separated list"),
  1986. OPT_WITHOUT_ARG("--text-only|-T",
  1987. opt_set_invbool, &use_curses,
  1988. #ifdef HAVE_CURSES
  1989. "Disable ncurses formatted screen output"
  1990. #else
  1991. opt_hidden
  1992. #endif
  1993. ),
  1994. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1995. OPT_WITH_ARG("--thread-concurrency",
  1996. set_thread_concurrency, NULL, NULL,
  1997. "Set GPU thread concurrency for scrypt mining, comma separated"),
  1998. #endif
  1999. #ifdef USE_UNICODE
  2000. OPT_WITHOUT_ARG("--unicode",
  2001. opt_set_bool, &use_unicode,
  2002. "Use Unicode characters in TUI"),
  2003. #endif
  2004. OPT_WITH_ARG("--url|-o",
  2005. set_url, NULL, NULL,
  2006. "URL for bitcoin JSON-RPC server"),
  2007. OPT_WITH_ARG("--user|-u",
  2008. set_user, NULL, NULL,
  2009. "Username for bitcoin JSON-RPC server"),
  2010. #ifdef HAVE_OPENCL
  2011. OPT_WITH_ARG("--vectors|-v",
  2012. set_vector, NULL, NULL,
  2013. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  2014. #endif
  2015. OPT_WITHOUT_ARG("--verbose",
  2016. opt_set_bool, &opt_log_output,
  2017. "Log verbose output to stderr as well as status output"),
  2018. #ifdef HAVE_OPENCL
  2019. OPT_WITH_ARG("--worksize|-w",
  2020. set_worksize, NULL, NULL,
  2021. "Override detected optimal worksize - one value or comma separated list"),
  2022. #endif
  2023. OPT_WITHOUT_ARG("--unittest",
  2024. opt_set_bool, &opt_unittest, opt_hidden),
  2025. OPT_WITH_ARG("--userpass|-O",
  2026. set_userpass, NULL, NULL,
  2027. "Username:Password pair for bitcoin JSON-RPC server"),
  2028. OPT_WITHOUT_ARG("--worktime",
  2029. opt_set_bool, &opt_worktime,
  2030. "Display extra work time debug information"),
  2031. OPT_WITH_ARG("--pools",
  2032. opt_set_bool, NULL, NULL, opt_hidden),
  2033. OPT_ENDTABLE
  2034. };
  2035. static char *load_config(const char *arg, void __maybe_unused *unused);
  2036. static int fileconf_load;
  2037. static char *parse_config(json_t *config, bool fileconf)
  2038. {
  2039. static char err_buf[200];
  2040. struct opt_table *opt;
  2041. json_t *val;
  2042. if (fileconf && !fileconf_load)
  2043. fileconf_load = 1;
  2044. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2045. char *p, *name, *sp;
  2046. /* We don't handle subtables. */
  2047. assert(!(opt->type & OPT_SUBTABLE));
  2048. if (!opt->names)
  2049. continue;
  2050. /* Pull apart the option name(s). */
  2051. name = strdup(opt->names);
  2052. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  2053. char *err = "Invalid value";
  2054. /* Ignore short options. */
  2055. if (p[1] != '-')
  2056. continue;
  2057. val = json_object_get(config, p+2);
  2058. if (!val)
  2059. continue;
  2060. if (opt->type & OPT_HASARG) {
  2061. if (json_is_string(val)) {
  2062. err = opt->cb_arg(json_string_value(val),
  2063. opt->u.arg);
  2064. } else if (json_is_number(val)) {
  2065. char buf[256], *p, *q;
  2066. snprintf(buf, 256, "%f", json_number_value(val));
  2067. if ( (p = strchr(buf, '.')) ) {
  2068. // Trim /\.0*$/ to work properly with integer-only arguments
  2069. q = p;
  2070. while (*(++q) == '0') {}
  2071. if (*q == '\0')
  2072. *p = '\0';
  2073. }
  2074. err = opt->cb_arg(buf, opt->u.arg);
  2075. } else if (json_is_array(val)) {
  2076. int n, size = json_array_size(val);
  2077. err = NULL;
  2078. for (n = 0; n < size && !err; n++) {
  2079. if (json_is_string(json_array_get(val, n)))
  2080. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  2081. else if (json_is_object(json_array_get(val, n)))
  2082. err = parse_config(json_array_get(val, n), false);
  2083. }
  2084. }
  2085. } else if (opt->type & OPT_NOARG) {
  2086. if (json_is_true(val))
  2087. err = opt->cb(opt->u.arg);
  2088. else if (json_is_boolean(val)) {
  2089. if (opt->cb == (void*)opt_set_bool)
  2090. err = opt_set_invbool(opt->u.arg);
  2091. else if (opt->cb == (void*)opt_set_invbool)
  2092. err = opt_set_bool(opt->u.arg);
  2093. }
  2094. }
  2095. if (err) {
  2096. /* Allow invalid values to be in configuration
  2097. * file, just skipping over them provided the
  2098. * JSON is still valid after that. */
  2099. if (fileconf) {
  2100. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  2101. fileconf_load = -1;
  2102. } else {
  2103. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  2104. p, err);
  2105. return err_buf;
  2106. }
  2107. }
  2108. }
  2109. free(name);
  2110. }
  2111. val = json_object_get(config, JSON_INCLUDE_CONF);
  2112. if (val && json_is_string(val))
  2113. return load_config(json_string_value(val), NULL);
  2114. return NULL;
  2115. }
  2116. char *cnfbuf = NULL;
  2117. static char *load_config(const char *arg, void __maybe_unused *unused)
  2118. {
  2119. json_error_t err;
  2120. json_t *config;
  2121. char *json_error;
  2122. size_t siz;
  2123. if (!cnfbuf)
  2124. cnfbuf = strdup(arg);
  2125. if (++include_count > JSON_MAX_DEPTH)
  2126. return JSON_MAX_DEPTH_ERR;
  2127. #if JANSSON_MAJOR_VERSION > 1
  2128. config = json_load_file(arg, 0, &err);
  2129. #else
  2130. config = json_load_file(arg, &err);
  2131. #endif
  2132. if (!json_is_object(config)) {
  2133. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  2134. json_error = malloc(siz);
  2135. if (!json_error)
  2136. quit(1, "Malloc failure in json error");
  2137. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  2138. return json_error;
  2139. }
  2140. config_loaded = true;
  2141. /* Parse the config now, so we can override it. That can keep pointers
  2142. * so don't free config object. */
  2143. return parse_config(config, true);
  2144. }
  2145. static void load_default_config(void)
  2146. {
  2147. cnfbuf = malloc(PATH_MAX);
  2148. #if defined(unix)
  2149. if (getenv("HOME") && *getenv("HOME")) {
  2150. strcpy(cnfbuf, getenv("HOME"));
  2151. strcat(cnfbuf, "/");
  2152. } else
  2153. strcpy(cnfbuf, "");
  2154. char *dirp = cnfbuf + strlen(cnfbuf);
  2155. strcpy(dirp, ".bfgminer/");
  2156. strcat(dirp, def_conf);
  2157. if (access(cnfbuf, R_OK))
  2158. // No BFGMiner config, try Cgminer's...
  2159. strcpy(dirp, ".cgminer/cgminer.conf");
  2160. #else
  2161. strcpy(cnfbuf, "");
  2162. strcat(cnfbuf, def_conf);
  2163. #endif
  2164. if (!access(cnfbuf, R_OK))
  2165. load_config(cnfbuf, NULL);
  2166. else {
  2167. free(cnfbuf);
  2168. cnfbuf = NULL;
  2169. }
  2170. }
  2171. extern const char *opt_argv0;
  2172. static char *opt_verusage_and_exit(const char *extra)
  2173. {
  2174. puts(packagename);
  2175. printf(" Drivers:%s\n", BFG_DRIVERLIST);
  2176. printf(" Algoritms:%s\n", BFG_ALGOLIST);
  2177. printf(" Options:%s\n", BFG_OPTLIST);
  2178. printf("%s", opt_usage(opt_argv0, extra));
  2179. fflush(stdout);
  2180. exit(0);
  2181. }
  2182. /* These options are available from commandline only */
  2183. static struct opt_table opt_cmdline_table[] = {
  2184. OPT_WITH_ARG("--config|-c",
  2185. load_config, NULL, NULL,
  2186. "Load a JSON-format configuration file\n"
  2187. "See example.conf for an example configuration."),
  2188. OPT_WITHOUT_ARG("--help|-h",
  2189. opt_verusage_and_exit, NULL,
  2190. "Print this message"),
  2191. #ifdef HAVE_OPENCL
  2192. OPT_WITHOUT_ARG("--ndevs|-n",
  2193. print_ndevs_and_exit, &nDevs,
  2194. opt_hidden),
  2195. #endif
  2196. OPT_WITHOUT_ARG("--version|-V",
  2197. opt_version_and_exit, packagename,
  2198. "Display version and exit"),
  2199. OPT_ENDTABLE
  2200. };
  2201. static bool jobj_binary(const json_t *obj, const char *key,
  2202. void *buf, size_t buflen, bool required)
  2203. {
  2204. const char *hexstr;
  2205. json_t *tmp;
  2206. tmp = json_object_get(obj, key);
  2207. if (unlikely(!tmp)) {
  2208. if (unlikely(required))
  2209. applog(LOG_ERR, "JSON key '%s' not found", key);
  2210. return false;
  2211. }
  2212. hexstr = json_string_value(tmp);
  2213. if (unlikely(!hexstr)) {
  2214. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  2215. return false;
  2216. }
  2217. if (!hex2bin(buf, hexstr, buflen))
  2218. return false;
  2219. return true;
  2220. }
  2221. static void calc_midstate(struct work *work)
  2222. {
  2223. union {
  2224. unsigned char c[64];
  2225. uint32_t i[16];
  2226. } data;
  2227. swap32yes(&data.i[0], work->data, 16);
  2228. sha256_ctx ctx;
  2229. sha256_init(&ctx);
  2230. sha256_update(&ctx, data.c, 64);
  2231. memcpy(work->midstate, ctx.h, sizeof(work->midstate));
  2232. swap32tole(work->midstate, work->midstate, 8);
  2233. }
  2234. static struct work *make_work(void)
  2235. {
  2236. struct work *work = calloc(1, sizeof(struct work));
  2237. if (unlikely(!work))
  2238. quit(1, "Failed to calloc work in make_work");
  2239. cg_wlock(&control_lock);
  2240. work->id = total_work++;
  2241. cg_wunlock(&control_lock);
  2242. return work;
  2243. }
  2244. /* This is the central place all work that is about to be retired should be
  2245. * cleaned to remove any dynamically allocated arrays within the struct */
  2246. void clean_work(struct work *work)
  2247. {
  2248. free(work->job_id);
  2249. bytes_free(&work->nonce2);
  2250. free(work->nonce1);
  2251. if (work->tmpl) {
  2252. struct pool *pool = work->pool;
  2253. mutex_lock(&pool->pool_lock);
  2254. bool free_tmpl = !--*work->tmpl_refcount;
  2255. mutex_unlock(&pool->pool_lock);
  2256. if (free_tmpl) {
  2257. blktmpl_free(work->tmpl);
  2258. free(work->tmpl_refcount);
  2259. }
  2260. }
  2261. memset(work, 0, sizeof(struct work));
  2262. }
  2263. /* All dynamically allocated work structs should be freed here to not leak any
  2264. * ram from arrays allocated within the work struct */
  2265. void free_work(struct work *work)
  2266. {
  2267. clean_work(work);
  2268. free(work);
  2269. }
  2270. 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";
  2271. // Must only be called with ch_lock held!
  2272. static
  2273. void __update_block_title(const unsigned char *hash_swap)
  2274. {
  2275. if (hash_swap) {
  2276. char tmp[17];
  2277. // Only provided when the block has actually changed
  2278. free(current_hash);
  2279. current_hash = malloc(3 /* ... */ + 16 /* block hash segment */ + 1);
  2280. bin2hex(tmp, &hash_swap[24], 8);
  2281. memset(current_hash, '.', 3);
  2282. memcpy(&current_hash[3], tmp, 17);
  2283. known_blkheight_current = false;
  2284. } else if (likely(known_blkheight_current)) {
  2285. return;
  2286. }
  2287. if (current_block_id == known_blkheight_blkid) {
  2288. // FIXME: The block number will overflow this sometime around AD 2025-2027
  2289. if (known_blkheight < 1000000) {
  2290. memmove(&current_hash[3], &current_hash[11], 8);
  2291. snprintf(&current_hash[11], 20-11, " #%6u", known_blkheight);
  2292. }
  2293. known_blkheight_current = true;
  2294. }
  2295. }
  2296. static
  2297. void have_block_height(uint32_t block_id, uint32_t blkheight)
  2298. {
  2299. if (known_blkheight == blkheight)
  2300. return;
  2301. applog(LOG_DEBUG, "Learned that block id %08" PRIx32 " is height %" PRIu32, (uint32_t)be32toh(block_id), blkheight);
  2302. cg_wlock(&ch_lock);
  2303. known_blkheight = blkheight;
  2304. known_blkheight_blkid = block_id;
  2305. block_subsidy = 5000000000LL >> (blkheight / 210000);
  2306. if (block_id == current_block_id)
  2307. __update_block_title(NULL);
  2308. cg_wunlock(&ch_lock);
  2309. }
  2310. static
  2311. void pool_set_opaque(struct pool *pool, bool opaque)
  2312. {
  2313. if (pool->swork.opaque == opaque)
  2314. return;
  2315. pool->swork.opaque = opaque;
  2316. if (opaque)
  2317. applog(LOG_WARNING, "Pool %u is hiding block contents from us",
  2318. pool->pool_no);
  2319. else
  2320. applog(LOG_NOTICE, "Pool %u now providing block contents to us",
  2321. pool->pool_no);
  2322. }
  2323. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2324. {
  2325. json_t *res_val = json_object_get(val, "result");
  2326. json_t *tmp_val;
  2327. bool ret = false;
  2328. if (unlikely(detect_algo == 1)) {
  2329. json_t *tmp = json_object_get(res_val, "algorithm");
  2330. const char *v = tmp ? json_string_value(tmp) : "";
  2331. if (strncasecmp(v, "scrypt", 6))
  2332. detect_algo = 2;
  2333. }
  2334. if (work->tmpl) {
  2335. struct timeval tv_now;
  2336. cgtime(&tv_now);
  2337. const char *err = blktmpl_add_jansson(work->tmpl, res_val, tv_now.tv_sec);
  2338. if (err) {
  2339. applog(LOG_ERR, "blktmpl error: %s", err);
  2340. return false;
  2341. }
  2342. work->rolltime = blkmk_time_left(work->tmpl, tv_now.tv_sec);
  2343. #if BLKMAKER_VERSION > 1
  2344. if (opt_coinbase_script.sz)
  2345. {
  2346. bool newcb;
  2347. #if BLKMAKER_VERSION > 2
  2348. blkmk_init_generation2(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz, &newcb);
  2349. #else
  2350. newcb = !work->tmpl->cbtxn;
  2351. blkmk_init_generation(work->tmpl, opt_coinbase_script.data, opt_coinbase_script.sz);
  2352. #endif
  2353. if (newcb)
  2354. {
  2355. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, &template_nonce, sizeof(template_nonce));
  2356. if (ae < (ssize_t)sizeof(template_nonce))
  2357. 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);
  2358. ++template_nonce;
  2359. }
  2360. }
  2361. #endif
  2362. #if BLKMAKER_VERSION > 0
  2363. {
  2364. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  2365. static bool appenderr = false;
  2366. if (ae <= 0) {
  2367. if (opt_coinbase_sig) {
  2368. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%"PRId64")", pool->pool_no, (int64_t)ae);
  2369. appenderr = true;
  2370. }
  2371. } else if (ae >= 3 || opt_coinbase_sig) {
  2372. const char *cbappend = opt_coinbase_sig;
  2373. const char full[] = PACKAGE " " VERSION;
  2374. if (!cbappend) {
  2375. if ((size_t)ae >= sizeof(full) - 1)
  2376. cbappend = full;
  2377. else if ((size_t)ae >= sizeof(PACKAGE) - 1)
  2378. cbappend = PACKAGE;
  2379. else
  2380. cbappend = "BFG";
  2381. }
  2382. size_t cbappendsz = strlen(cbappend);
  2383. static bool truncatewarning = false;
  2384. if (cbappendsz <= (size_t)ae) {
  2385. if (cbappendsz < (size_t)ae)
  2386. // If we have space, include the trailing \0
  2387. ++cbappendsz;
  2388. ae = cbappendsz;
  2389. truncatewarning = false;
  2390. } else {
  2391. char *tmp = malloc(ae + 1);
  2392. memcpy(tmp, opt_coinbase_sig, ae);
  2393. tmp[ae] = '\0';
  2394. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  2395. "Pool %u truncating appended coinbase signature at %"PRId64" bytes: %s(%s)",
  2396. pool->pool_no, (int64_t)ae, tmp, &opt_coinbase_sig[ae]);
  2397. free(tmp);
  2398. truncatewarning = true;
  2399. }
  2400. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  2401. if (ae <= 0) {
  2402. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%"PRId64")", (int64_t)ae);
  2403. appenderr = true;
  2404. } else
  2405. appenderr = false;
  2406. }
  2407. }
  2408. #endif
  2409. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  2410. return false;
  2411. swap32yes(work->data, work->data, 80 / 4);
  2412. memcpy(&work->data[80], workpadding_bin, 48);
  2413. const struct blktmpl_longpoll_req *lp;
  2414. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  2415. free(pool->lp_id);
  2416. pool->lp_id = strdup(lp->id);
  2417. #if 0 /* This just doesn't work :( */
  2418. curl_socket_t sock = pool->lp_socket;
  2419. if (sock != CURL_SOCKET_BAD) {
  2420. pool->lp_socket = CURL_SOCKET_BAD;
  2421. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  2422. shutdown(sock, SHUT_RDWR);
  2423. }
  2424. #endif
  2425. }
  2426. }
  2427. else
  2428. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  2429. applog(LOG_ERR, "JSON inval data");
  2430. return false;
  2431. }
  2432. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2433. // Calculate it ourselves
  2434. applog(LOG_DEBUG, "Calculating midstate locally");
  2435. calc_midstate(work);
  2436. }
  2437. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2438. applog(LOG_ERR, "JSON inval target");
  2439. return false;
  2440. }
  2441. if (work->tmpl) {
  2442. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  2443. {
  2444. int p = (sizeof(work->target) - 1) - i;
  2445. unsigned char c = work->target[i];
  2446. work->target[i] = work->target[p];
  2447. work->target[p] = c;
  2448. }
  2449. }
  2450. if ( (tmp_val = json_object_get(res_val, "height")) ) {
  2451. uint32_t blkheight = json_number_value(tmp_val);
  2452. uint32_t block_id = ((uint32_t*)work->data)[1];
  2453. have_block_height(block_id, blkheight);
  2454. }
  2455. memset(work->hash, 0, sizeof(work->hash));
  2456. cgtime(&work->tv_staged);
  2457. pool_set_opaque(pool, !work->tmpl);
  2458. ret = true;
  2459. return ret;
  2460. }
  2461. /* Returns whether the pool supports local work generation or not. */
  2462. static bool pool_localgen(struct pool *pool)
  2463. {
  2464. return (pool->last_work_copy || pool->has_stratum);
  2465. }
  2466. int dev_from_id(int thr_id)
  2467. {
  2468. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2469. return cgpu->device_id;
  2470. }
  2471. /* Create an exponentially decaying average over the opt_log_interval */
  2472. void decay_time(double *f, double fadd, double fsecs)
  2473. {
  2474. double ftotal, fprop;
  2475. fprop = 1.0 - 1 / (exp(fsecs / (double)opt_log_interval));
  2476. ftotal = 1.0 + fprop;
  2477. *f += (fadd * fprop);
  2478. *f /= ftotal;
  2479. }
  2480. static int __total_staged(void)
  2481. {
  2482. return HASH_COUNT(staged_work);
  2483. }
  2484. static int total_staged(void)
  2485. {
  2486. int ret;
  2487. mutex_lock(stgd_lock);
  2488. ret = __total_staged();
  2489. mutex_unlock(stgd_lock);
  2490. return ret;
  2491. }
  2492. #ifdef HAVE_CURSES
  2493. WINDOW *mainwin, *statuswin, *logwin;
  2494. #endif
  2495. double total_secs = 1.0;
  2496. static char statusline[256];
  2497. /* logstart is where the log window should start */
  2498. static int devcursor, logstart, logcursor;
  2499. #ifdef HAVE_CURSES
  2500. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2501. static int statusy;
  2502. static int devsummaryYOffset;
  2503. static int total_lines;
  2504. #endif
  2505. #ifdef HAVE_OPENCL
  2506. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  2507. #endif
  2508. struct cgpu_info *cpus;
  2509. bool _bfg_console_cancel_disabled;
  2510. int _bfg_console_prev_cancelstate;
  2511. #ifdef HAVE_CURSES
  2512. #define lock_curses() bfg_console_lock()
  2513. #define unlock_curses() bfg_console_unlock()
  2514. static bool curses_active_locked(void)
  2515. {
  2516. bool ret;
  2517. lock_curses();
  2518. ret = curses_active;
  2519. if (!ret)
  2520. unlock_curses();
  2521. return ret;
  2522. }
  2523. // Cancellable getch
  2524. int my_cancellable_getch(void)
  2525. {
  2526. // This only works because the macro only hits direct getch() calls
  2527. typedef int (*real_getch_t)(void);
  2528. const real_getch_t real_getch = __real_getch;
  2529. int type, rv;
  2530. bool sct;
  2531. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  2532. rv = real_getch();
  2533. if (sct)
  2534. pthread_setcanceltype(type, &type);
  2535. return rv;
  2536. }
  2537. #ifdef PDCURSES
  2538. static
  2539. int bfg_wresize(WINDOW *win, int lines, int columns)
  2540. {
  2541. int rv = wresize(win, lines, columns);
  2542. int x, y;
  2543. getyx(win, y, x);
  2544. if (unlikely(y >= lines || x >= columns))
  2545. {
  2546. if (y >= lines)
  2547. y = lines - 1;
  2548. if (x >= columns)
  2549. x = columns - 1;
  2550. wmove(win, y, x);
  2551. }
  2552. return rv;
  2553. }
  2554. #else
  2555. # define bfg_wresize wresize
  2556. #endif
  2557. #endif
  2558. void tailsprintf(char *buf, size_t bufsz, const char *fmt, ...)
  2559. {
  2560. va_list ap;
  2561. size_t presz = strlen(buf);
  2562. va_start(ap, fmt);
  2563. vsnprintf(&buf[presz], bufsz - presz, fmt, ap);
  2564. va_end(ap);
  2565. }
  2566. double stats_elapsed(struct cgminer_stats *stats)
  2567. {
  2568. struct timeval now;
  2569. double elapsed;
  2570. if (stats->start_tv.tv_sec == 0)
  2571. elapsed = total_secs;
  2572. else {
  2573. cgtime(&now);
  2574. elapsed = tdiff(&now, &stats->start_tv);
  2575. }
  2576. if (elapsed < 1.0)
  2577. elapsed = 1.0;
  2578. return elapsed;
  2579. }
  2580. bool drv_ready(struct cgpu_info *cgpu)
  2581. {
  2582. switch (cgpu->status) {
  2583. case LIFE_INIT:
  2584. case LIFE_DEAD2:
  2585. return false;
  2586. default:
  2587. return true;
  2588. }
  2589. }
  2590. double cgpu_utility(struct cgpu_info *cgpu)
  2591. {
  2592. double dev_runtime = cgpu_runtime(cgpu);
  2593. return cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2594. }
  2595. /* Convert a uint64_t value into a truncated string for displaying with its
  2596. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2597. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  2598. {
  2599. const double dkilo = 1000.0;
  2600. const uint64_t kilo = 1000ull;
  2601. const uint64_t mega = 1000000ull;
  2602. const uint64_t giga = 1000000000ull;
  2603. const uint64_t tera = 1000000000000ull;
  2604. const uint64_t peta = 1000000000000000ull;
  2605. const uint64_t exa = 1000000000000000000ull;
  2606. char suffix[2] = "";
  2607. bool decimal = true;
  2608. double dval;
  2609. if (val >= exa) {
  2610. val /= peta;
  2611. dval = (double)val / dkilo;
  2612. strcpy(suffix, "E");
  2613. } else if (val >= peta) {
  2614. val /= tera;
  2615. dval = (double)val / dkilo;
  2616. strcpy(suffix, "P");
  2617. } else if (val >= tera) {
  2618. val /= giga;
  2619. dval = (double)val / dkilo;
  2620. strcpy(suffix, "T");
  2621. } else if (val >= giga) {
  2622. val /= mega;
  2623. dval = (double)val / dkilo;
  2624. strcpy(suffix, "G");
  2625. } else if (val >= mega) {
  2626. val /= kilo;
  2627. dval = (double)val / dkilo;
  2628. strcpy(suffix, "M");
  2629. } else if (val >= kilo) {
  2630. dval = (double)val / dkilo;
  2631. strcpy(suffix, "k");
  2632. } else {
  2633. dval = val;
  2634. decimal = false;
  2635. }
  2636. if (!sigdigits) {
  2637. if (decimal)
  2638. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  2639. else
  2640. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  2641. } else {
  2642. /* Always show sigdigits + 1, padded on right with zeroes
  2643. * followed by suffix */
  2644. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2645. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2646. }
  2647. }
  2648. static float
  2649. utility_to_hashrate(double utility)
  2650. {
  2651. return utility * 0x4444444;
  2652. }
  2653. static const char*_unitchar = "pn\xb5m kMGTPEZY?";
  2654. static const int _unitbase = 4;
  2655. static
  2656. void pick_unit(float hashrate, unsigned char *unit)
  2657. {
  2658. unsigned char i;
  2659. if (hashrate == 0)
  2660. {
  2661. if (*unit < _unitbase)
  2662. *unit = _unitbase;
  2663. return;
  2664. }
  2665. hashrate *= 1e12;
  2666. for (i = 0; i < *unit; ++i)
  2667. hashrate /= 1e3;
  2668. // 1000 but with tolerance for floating-point rounding, avoid showing "1000.0"
  2669. while (hashrate >= 999.95)
  2670. {
  2671. hashrate /= 1e3;
  2672. if (likely(_unitchar[*unit] != '?'))
  2673. ++*unit;
  2674. }
  2675. }
  2676. #define hashrate_pick_unit(hashrate, unit) pick_unit(hashrate, unit)
  2677. enum h2bs_fmt {
  2678. H2B_NOUNIT, // "xxx.x"
  2679. H2B_SHORT, // "xxx.xMH/s"
  2680. H2B_SPACED, // "xxx.x MH/s"
  2681. };
  2682. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  2683. enum bfu_floatprec {
  2684. FUP_INTEGER,
  2685. FUP_HASHES,
  2686. FUP_BTC,
  2687. };
  2688. static
  2689. int format_unit3(char *buf, size_t sz, enum bfu_floatprec fprec, const char *measurement, enum h2bs_fmt fmt, float hashrate, signed char unitin)
  2690. {
  2691. char *s = buf;
  2692. unsigned char prec, i, unit;
  2693. int rv = 0;
  2694. if (unitin == -1)
  2695. {
  2696. unit = 0;
  2697. hashrate_pick_unit(hashrate, &unit);
  2698. }
  2699. else
  2700. unit = unitin;
  2701. hashrate *= 1e12;
  2702. for (i = 0; i < unit; ++i)
  2703. hashrate /= 1000;
  2704. switch (fprec)
  2705. {
  2706. case FUP_HASHES:
  2707. // 100 but with tolerance for floating-point rounding, max "99.99" then "100.0"
  2708. if (hashrate >= 99.995 || unit < 6)
  2709. prec = 1;
  2710. else
  2711. prec = 2;
  2712. _SNP("%5.*f", prec, hashrate);
  2713. break;
  2714. case FUP_INTEGER:
  2715. _SNP("%3d", (int)hashrate);
  2716. break;
  2717. case FUP_BTC:
  2718. if (hashrate >= 99.995)
  2719. prec = 0;
  2720. else
  2721. prec = 2;
  2722. _SNP("%5.*f", prec, hashrate);
  2723. }
  2724. switch (fmt) {
  2725. case H2B_SPACED:
  2726. _SNP(" ");
  2727. case H2B_SHORT:
  2728. _SNP("%c%s", _unitchar[unit], measurement);
  2729. default:
  2730. break;
  2731. }
  2732. return rv;
  2733. }
  2734. #define format_unit2(buf, sz, floatprec, measurement, fmt, n, unit) \
  2735. format_unit3(buf, sz, floatprec ? FUP_HASHES : FUP_INTEGER, measurement, fmt, n, unit)
  2736. static
  2737. 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)
  2738. {
  2739. unsigned char unit = 0;
  2740. bool allzero = true;
  2741. int i;
  2742. size_t delimsz = 0;
  2743. char *buf = buflist[0];
  2744. size_t bufsz = bufszlist[0];
  2745. size_t itemwidth = (floatprec ? 5 : 3);
  2746. if (!isarray)
  2747. delimsz = strlen(delim);
  2748. for (i = 0; i < count; ++i)
  2749. if (numbers[i] != 0)
  2750. {
  2751. pick_unit(numbers[i], &unit);
  2752. allzero = false;
  2753. }
  2754. if (allzero)
  2755. unit = _unitbase;
  2756. --count;
  2757. for (i = 0; i < count; ++i)
  2758. {
  2759. format_unit2(buf, bufsz, floatprec, NULL, H2B_NOUNIT, numbers[i], unit);
  2760. if (isarray)
  2761. {
  2762. buf = buflist[i + 1];
  2763. bufsz = bufszlist[i + 1];
  2764. }
  2765. else
  2766. {
  2767. buf += itemwidth;
  2768. bufsz -= itemwidth;
  2769. if (delimsz > bufsz)
  2770. delimsz = bufsz;
  2771. memcpy(buf, delim, delimsz);
  2772. buf += delimsz;
  2773. bufsz -= delimsz;
  2774. }
  2775. }
  2776. // Last entry has the unit
  2777. format_unit2(buf, bufsz, floatprec, measurement, fmt, numbers[count], unit);
  2778. return buflist[0];
  2779. }
  2780. #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)
  2781. #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)
  2782. static
  2783. int percentf3(char * const buf, size_t sz, double p, const double t)
  2784. {
  2785. char *s = buf;
  2786. int rv = 0;
  2787. if (!p)
  2788. _SNP("none");
  2789. else
  2790. if (t <= p)
  2791. _SNP("100%%");
  2792. else
  2793. {
  2794. p /= t;
  2795. if (p < 0.00995) // 0.01 but with tolerance for floating-point rounding, max ".99%"
  2796. _SNP(".%02.0f%%", p * 10000); // ".01%"
  2797. else
  2798. if (p < 0.0995) // 0.1 but with tolerance for floating-point rounding, max "9.9%"
  2799. _SNP("%.1f%%", p * 100); // "9.1%"
  2800. else
  2801. _SNP("%3.0f%%", p * 100); // " 99%"
  2802. }
  2803. return rv;
  2804. }
  2805. #define percentf4(buf, bufsz, p, t) percentf3(buf, bufsz, p, p + t)
  2806. static
  2807. void test_decimal_width()
  2808. {
  2809. // The pipe character at end of each line should perfectly line up
  2810. char printbuf[512];
  2811. char testbuf1[64];
  2812. char testbuf2[64];
  2813. char testbuf3[64];
  2814. char testbuf4[64];
  2815. double testn;
  2816. int width;
  2817. int saved;
  2818. // Hotspots around 0.1 and 0.01
  2819. saved = -1;
  2820. for (testn = 0.09; testn <= 0.11; testn += 0.000001) {
  2821. percentf3(testbuf1, sizeof(testbuf1), testn, 1.0);
  2822. percentf3(testbuf2, sizeof(testbuf2), testn, 10.0);
  2823. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s |", testn, testbuf1, testbuf2);
  2824. if (unlikely((saved != -1) && (width != saved))) {
  2825. applog(LOG_ERR, "Test width mismatch in percentf3! %d not %d at %10g", width, saved, testn);
  2826. applog(LOG_ERR, "%s", printbuf);
  2827. }
  2828. saved = width;
  2829. }
  2830. // Hotspot around 100 (but test this in several units because format_unit2 also has unit<2 check)
  2831. saved = -1;
  2832. for (testn = 99.0; testn <= 101.0; testn += 0.0001) {
  2833. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2834. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2835. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2836. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s |", testn, testbuf1, testbuf2, testbuf3);
  2837. if (unlikely((saved != -1) && (width != saved))) {
  2838. applog(LOG_ERR, "Test width mismatch in format_unit2! %d not %d at %10g", width, saved, testn);
  2839. applog(LOG_ERR, "%s", printbuf);
  2840. }
  2841. saved = width;
  2842. }
  2843. // Hotspot around unit transition boundary in pick_unit
  2844. saved = -1;
  2845. for (testn = 999.0; testn <= 1001.0; testn += 0.0001) {
  2846. format_unit2(testbuf1, sizeof(testbuf1), true, "x", H2B_SHORT, testn , -1);
  2847. format_unit2(testbuf2, sizeof(testbuf2), true, "x", H2B_SHORT, testn * 1e3, -1);
  2848. format_unit2(testbuf3, sizeof(testbuf3), true, "x", H2B_SHORT, testn * 1e6, -1);
  2849. format_unit2(testbuf4, sizeof(testbuf4), true, "x", H2B_SHORT, testn * 1e9, -1);
  2850. width = snprintf(printbuf, sizeof(printbuf), "%10g %s %s %s %s |", testn, testbuf1, testbuf2, testbuf3, testbuf4);
  2851. if (unlikely((saved != -1) && (width != saved))) {
  2852. applog(LOG_ERR, "Test width mismatch in pick_unit! %d not %d at %10g", width, saved, testn);
  2853. applog(LOG_ERR, "%s", printbuf);
  2854. }
  2855. saved = width;
  2856. }
  2857. }
  2858. #ifdef HAVE_CURSES
  2859. static void adj_width(int var, int *length);
  2860. #endif
  2861. #ifdef HAVE_CURSES
  2862. static int awidth = 1, rwidth = 1, swidth = 1, hwwidth = 1;
  2863. static
  2864. 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 badnonces, int allnonces)
  2865. {
  2866. char rejpcbuf[6];
  2867. char bnbuf[6];
  2868. adj_width(accepted, &awidth);
  2869. adj_width(rejected, &rwidth);
  2870. adj_width(stale, &swidth);
  2871. adj_width(hwerrs, &hwwidth);
  2872. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  2873. percentf3(bnbuf, sizeof(bnbuf), badnonces, allnonces);
  2874. tailsprintf(buf, bufsz, "%s/%s/%s | A:%*d R:%*d+%*d(%s) HW:%*d/%s",
  2875. cHr, aHr, uHr,
  2876. awidth, accepted,
  2877. rwidth, rejected,
  2878. swidth, stale,
  2879. rejpcbuf,
  2880. hwwidth, hwerrs,
  2881. bnbuf
  2882. );
  2883. }
  2884. #endif
  2885. static inline
  2886. void temperature_column(char *buf, size_t bufsz, bool maybe_unicode, const float * const temp)
  2887. {
  2888. if (!(use_unicode && have_unicode_degrees))
  2889. maybe_unicode = false;
  2890. if (temp && *temp > 0.)
  2891. if (maybe_unicode)
  2892. snprintf(buf, bufsz, "%4.1f"U8_DEGREE"C", *temp);
  2893. else
  2894. snprintf(buf, bufsz, "%4.1fC", *temp);
  2895. else
  2896. {
  2897. if (temp)
  2898. snprintf(buf, bufsz, " ");
  2899. if (maybe_unicode)
  2900. tailsprintf(buf, bufsz, " ");
  2901. }
  2902. tailsprintf(buf, bufsz, " | ");
  2903. }
  2904. void get_statline3(char *buf, size_t bufsz, struct cgpu_info *cgpu, bool for_curses, bool opt_show_procs)
  2905. {
  2906. #ifndef HAVE_CURSES
  2907. assert(for_curses == false);
  2908. #endif
  2909. struct device_drv *drv = cgpu->drv;
  2910. enum h2bs_fmt hashrate_style = for_curses ? H2B_SHORT : H2B_SPACED;
  2911. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[hashrate_style]];
  2912. char rejpcbuf[6];
  2913. char bnbuf[6];
  2914. double dev_runtime;
  2915. if (!opt_show_procs)
  2916. cgpu = cgpu->device;
  2917. dev_runtime = cgpu_runtime(cgpu);
  2918. cgpu_utility(cgpu);
  2919. cgpu->utility_diff1 = cgpu->diff_accepted / dev_runtime * 60;
  2920. double rolling = cgpu->rolling;
  2921. double mhashes = cgpu->total_mhashes;
  2922. int accepted = cgpu->accepted;
  2923. int rejected = cgpu->rejected;
  2924. int stale = cgpu->stale;
  2925. double waccepted = cgpu->diff_accepted;
  2926. double wnotaccepted = cgpu->diff_rejected + cgpu->diff_stale;
  2927. int hwerrs = cgpu->hw_errors;
  2928. int badnonces = cgpu->bad_nonces;
  2929. int goodnonces = cgpu->diff1;
  2930. if (!opt_show_procs)
  2931. {
  2932. struct cgpu_info *slave = cgpu;
  2933. for (int i = 1; i < cgpu->procs; ++i)
  2934. {
  2935. slave = slave->next_proc;
  2936. slave->utility = slave->accepted / dev_runtime * 60;
  2937. slave->utility_diff1 = slave->diff_accepted / dev_runtime * 60;
  2938. rolling += slave->rolling;
  2939. mhashes += slave->total_mhashes;
  2940. accepted += slave->accepted;
  2941. rejected += slave->rejected;
  2942. stale += slave->stale;
  2943. waccepted += slave->diff_accepted;
  2944. wnotaccepted += slave->diff_rejected + slave->diff_stale;
  2945. hwerrs += slave->hw_errors;
  2946. badnonces += slave->bad_nonces;
  2947. goodnonces += slave->diff1;
  2948. }
  2949. }
  2950. double wtotal = (waccepted + wnotaccepted);
  2951. multi_format_unit_array2(
  2952. ((char*[]){cHr, aHr, uHr}),
  2953. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[hashrate_style]}),
  2954. true, "h/s", hashrate_style,
  2955. 3,
  2956. 1e6*rolling,
  2957. 1e6*mhashes / dev_runtime,
  2958. utility_to_hashrate(goodnonces * (wtotal ? (waccepted / wtotal) : 1) * 60 / dev_runtime));
  2959. // Processor representation
  2960. #ifdef HAVE_CURSES
  2961. if (for_curses)
  2962. {
  2963. if (opt_show_procs)
  2964. snprintf(buf, bufsz, " %"PRIprepr": ", cgpu->proc_repr);
  2965. else
  2966. snprintf(buf, bufsz, " %s: ", cgpu->dev_repr);
  2967. }
  2968. else
  2969. #endif
  2970. snprintf(buf, bufsz, "%s ", opt_show_procs ? cgpu->proc_repr_ns : cgpu->dev_repr_ns);
  2971. if (unlikely(cgpu->status == LIFE_INIT))
  2972. {
  2973. tailsprintf(buf, bufsz, "Initializing...");
  2974. return;
  2975. }
  2976. {
  2977. const size_t bufln = strlen(buf);
  2978. const size_t abufsz = (bufln >= bufsz) ? 0 : (bufsz - bufln);
  2979. if (likely(cgpu->status != LIFE_DEAD2) && drv->override_statline_temp2 && drv->override_statline_temp2(buf, bufsz, cgpu, opt_show_procs))
  2980. temperature_column(&buf[bufln], abufsz, for_curses, NULL);
  2981. else
  2982. {
  2983. float temp = cgpu->temp;
  2984. if (!opt_show_procs)
  2985. {
  2986. // Find the highest temperature of all processors
  2987. struct cgpu_info *proc = cgpu;
  2988. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  2989. if (proc->temp > temp)
  2990. temp = proc->temp;
  2991. }
  2992. temperature_column(&buf[bufln], abufsz, for_curses, &temp);
  2993. }
  2994. }
  2995. #ifdef HAVE_CURSES
  2996. if (for_curses)
  2997. {
  2998. const char *cHrStatsOpt[] = {AS_BAD("DEAD "), AS_BAD("SICK "), "OFF ", AS_BAD("REST "), AS_BAD(" ERR "), AS_BAD("WAIT "), cHr};
  2999. const char *cHrStats;
  3000. int cHrStatsI = (sizeof(cHrStatsOpt) / sizeof(*cHrStatsOpt)) - 1;
  3001. bool all_dead = true, all_off = true, all_rdrv = true;
  3002. struct cgpu_info *proc = cgpu;
  3003. for (int i = 0; i < cgpu->procs; ++i, (proc = proc->next_proc))
  3004. {
  3005. switch (cHrStatsI) {
  3006. default:
  3007. if (proc->status == LIFE_WAIT)
  3008. cHrStatsI = 5;
  3009. case 5:
  3010. if (proc->deven == DEV_RECOVER_ERR)
  3011. cHrStatsI = 4;
  3012. case 4:
  3013. if (proc->deven == DEV_RECOVER)
  3014. cHrStatsI = 3;
  3015. case 3:
  3016. if (proc->status == LIFE_SICK || proc->status == LIFE_DEAD || proc->status == LIFE_DEAD2)
  3017. {
  3018. cHrStatsI = 1;
  3019. all_off = false;
  3020. }
  3021. else
  3022. {
  3023. if (likely(proc->deven == DEV_ENABLED))
  3024. all_off = false;
  3025. if (proc->deven != DEV_RECOVER_DRV)
  3026. all_rdrv = false;
  3027. }
  3028. case 1:
  3029. break;
  3030. }
  3031. if (likely(proc->status != LIFE_DEAD && proc->status != LIFE_DEAD2))
  3032. all_dead = false;
  3033. if (opt_show_procs)
  3034. break;
  3035. }
  3036. if (unlikely(all_dead))
  3037. cHrStatsI = 0;
  3038. else
  3039. if (unlikely(all_off))
  3040. cHrStatsI = 2;
  3041. cHrStats = cHrStatsOpt[cHrStatsI];
  3042. if (cHrStatsI == 2 && all_rdrv)
  3043. cHrStats = " RST ";
  3044. format_statline(buf, bufsz,
  3045. cHrStats,
  3046. aHr, uHr,
  3047. accepted, rejected, stale,
  3048. wnotaccepted, waccepted,
  3049. hwerrs,
  3050. badnonces, badnonces + goodnonces);
  3051. }
  3052. else
  3053. #endif
  3054. {
  3055. percentf4(rejpcbuf, sizeof(rejpcbuf), wnotaccepted, waccepted);
  3056. percentf4(bnbuf, sizeof(bnbuf), badnonces, goodnonces);
  3057. tailsprintf(buf, bufsz, "%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  3058. opt_log_interval,
  3059. cHr, aHr, uHr,
  3060. accepted,
  3061. rejected,
  3062. stale,
  3063. rejpcbuf,
  3064. hwerrs,
  3065. bnbuf
  3066. );
  3067. }
  3068. }
  3069. #define get_statline(buf, bufsz, cgpu) get_statline3(buf, bufsz, cgpu, false, opt_show_procs)
  3070. #define get_statline2(buf, bufsz, cgpu, for_curses) get_statline3(buf, bufsz, cgpu, for_curses, opt_show_procs)
  3071. static void text_print_status(int thr_id)
  3072. {
  3073. struct cgpu_info *cgpu;
  3074. char logline[256];
  3075. cgpu = get_thr_cgpu(thr_id);
  3076. if (cgpu) {
  3077. get_statline(logline, sizeof(logline), cgpu);
  3078. printf("%s\n", logline);
  3079. }
  3080. }
  3081. #ifdef HAVE_CURSES
  3082. static int attr_bad = A_BOLD;
  3083. #ifdef WIN32
  3084. #define swprintf snwprintf
  3085. #endif
  3086. static
  3087. void bfg_waddstr(WINDOW *win, const char *s)
  3088. {
  3089. const char *p = s;
  3090. int32_t w;
  3091. int wlen;
  3092. unsigned char stop_ascii = (use_unicode ? '|' : 0x80);
  3093. while (true)
  3094. {
  3095. while (likely(p[0] == '\n' || (p[0] >= 0x20 && p[0] < stop_ascii)))
  3096. {
  3097. // Printable ASCII
  3098. ++p;
  3099. }
  3100. if (p != s)
  3101. waddnstr(win, s, p - s);
  3102. w = utf8_decode(p, &wlen);
  3103. if (unlikely(p[0] == '\xb5')) // HACK for Mu (SI prefix micro-)
  3104. {
  3105. w = unicode_micro;
  3106. wlen = 1;
  3107. }
  3108. s = p += wlen;
  3109. switch(w)
  3110. {
  3111. // NOTE: U+F000-U+F7FF are reserved for font hacks
  3112. case '\0':
  3113. return;
  3114. case 0xf000: // "bad" off
  3115. wattroff(win, attr_bad);
  3116. break;
  3117. case 0xf001: // "bad" on
  3118. wattron(win, attr_bad);
  3119. break;
  3120. #ifdef USE_UNICODE
  3121. case '|':
  3122. wadd_wch(win, WACS_VLINE);
  3123. break;
  3124. #endif
  3125. case 0x2500: // BOX DRAWINGS LIGHT HORIZONTAL
  3126. case 0x2534: // BOX DRAWINGS LIGHT UP AND HORIZONTAL
  3127. if (!use_unicode)
  3128. {
  3129. waddch(win, '-');
  3130. break;
  3131. }
  3132. #ifdef USE_UNICODE
  3133. wadd_wch(win, (w == 0x2500) ? WACS_HLINE : WACS_BTEE);
  3134. break;
  3135. #endif
  3136. case 0x2022:
  3137. if (w > WCHAR_MAX || !iswprint(w))
  3138. w = '*';
  3139. default:
  3140. if (w > WCHAR_MAX || !(iswprint(w) || w == '\n'))
  3141. {
  3142. #if REPLACEMENT_CHAR <= WCHAR_MAX
  3143. if (iswprint(REPLACEMENT_CHAR))
  3144. w = REPLACEMENT_CHAR;
  3145. else
  3146. #endif
  3147. w = '?';
  3148. }
  3149. {
  3150. #ifdef USE_UNICODE
  3151. wchar_t wbuf[0x10];
  3152. int wbuflen = sizeof(wbuf) / sizeof(*wbuf);
  3153. wbuflen = swprintf(wbuf, wbuflen, L"%lc", (wint_t)w);
  3154. waddnwstr(win, wbuf, wbuflen);
  3155. #else
  3156. wprintw(win, "%lc", (wint_t)w);
  3157. #endif
  3158. }
  3159. }
  3160. }
  3161. }
  3162. static inline
  3163. void bfg_hline(WINDOW *win, int y)
  3164. {
  3165. #ifdef USE_UNICODE
  3166. if (use_unicode)
  3167. mvwhline_set(win, y, 0, WACS_HLINE, 80);
  3168. else
  3169. #endif
  3170. mvwhline(win, y, 0, '-', 80);
  3171. }
  3172. static int menu_attr = A_REVERSE;
  3173. #define CURBUFSIZ 256
  3174. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  3175. char tmp42[CURBUFSIZ]; \
  3176. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3177. wmove(win, y, x); \
  3178. bfg_waddstr(win, tmp42); \
  3179. } while (0)
  3180. #define cg_wprintw(win, fmt, ...) do { \
  3181. char tmp42[CURBUFSIZ]; \
  3182. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  3183. bfg_waddstr(win, tmp42); \
  3184. } while (0)
  3185. /* Must be called with curses mutex lock held and curses_active */
  3186. static void curses_print_status(const int ts)
  3187. {
  3188. struct pool *pool = currentpool;
  3189. struct timeval now, tv;
  3190. float efficiency;
  3191. double income;
  3192. int logdiv;
  3193. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  3194. wattron(statuswin, A_BOLD);
  3195. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  3196. timer_set_now(&now);
  3197. {
  3198. unsigned int days, hours;
  3199. div_t d;
  3200. timersub(&now, &miner_started, &tv);
  3201. d = div(tv.tv_sec, 86400);
  3202. days = d.quot;
  3203. d = div(d.rem, 3600);
  3204. hours = d.quot;
  3205. d = div(d.rem, 60);
  3206. cg_wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  3207. , days
  3208. , (days == 1) ? ' ' : 's'
  3209. , hours
  3210. , d.quot
  3211. , d.rem
  3212. );
  3213. }
  3214. wattroff(statuswin, A_BOLD);
  3215. wattron(statuswin, menu_attr);
  3216. cg_mvwprintw(statuswin, 1, 0, " [M]anage devices [P]ool management [S]ettings [D]isplay options [H]elp [Q]uit ");
  3217. wattroff(statuswin, menu_attr);
  3218. if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  3219. cg_mvwprintw(statuswin, 2, 0, " Connected to multiple pools with%s block change notify",
  3220. have_longpoll ? "": "out");
  3221. } else if (pool->has_stratum) {
  3222. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with stratum as user %s",
  3223. pool->sockaddr_url, pool->diff, pool->rpc_user);
  3224. } else {
  3225. cg_mvwprintw(statuswin, 2, 0, " Connected to %s diff %s with%s LP as user %s",
  3226. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out", pool->rpc_user);
  3227. }
  3228. wclrtoeol(statuswin);
  3229. cg_mvwprintw(statuswin, 3, 0, " Block: %s Diff:%s (%s) Started: %s",
  3230. current_hash, block_diff, net_hashrate, blocktime);
  3231. income = total_diff_accepted * 3600 * block_subsidy / total_secs / current_diff;
  3232. char bwstr[12], incomestr[13];
  3233. format_unit3(incomestr, sizeof(incomestr), FUP_BTC, "BTC/hr", H2B_SHORT, income/1e8, -1);
  3234. cg_mvwprintw(statuswin, 4, 0, " ST:%d F:%d NB:%d AS:%d BW:[%s] E:%.2f I:%s BS:%s",
  3235. ts,
  3236. total_go + total_ro,
  3237. new_blocks,
  3238. total_submitting,
  3239. multi_format_unit2(bwstr, sizeof(bwstr),
  3240. false, "B/s", H2B_SHORT, "/", 2,
  3241. (float)(total_bytes_rcvd / total_secs),
  3242. (float)(total_bytes_sent / total_secs)),
  3243. efficiency,
  3244. incomestr,
  3245. best_share);
  3246. wclrtoeol(statuswin);
  3247. mvwaddstr(statuswin, 5, 0, " ");
  3248. bfg_waddstr(statuswin, statusline);
  3249. wclrtoeol(statuswin);
  3250. logdiv = statusy - 1;
  3251. bfg_hline(statuswin, 6);
  3252. bfg_hline(statuswin, logdiv);
  3253. #ifdef USE_UNICODE
  3254. if (use_unicode)
  3255. {
  3256. int offset = 8 /* device */ + 5 /* temperature */ + 1 /* padding space */;
  3257. if (opt_show_procs && !opt_compact)
  3258. ++offset; // proc letter
  3259. if (have_unicode_degrees)
  3260. ++offset; // degrees symbol
  3261. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3262. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3263. offset += 24; // hashrates etc
  3264. mvwadd_wch(statuswin, 6, offset, WACS_PLUS);
  3265. mvwadd_wch(statuswin, logdiv, offset, WACS_BTEE);
  3266. }
  3267. #endif
  3268. }
  3269. static void adj_width(int var, int *length)
  3270. {
  3271. if ((int)(log10(var) + 1) > *length)
  3272. (*length)++;
  3273. }
  3274. static int dev_width;
  3275. static void curses_print_devstatus(struct cgpu_info *cgpu)
  3276. {
  3277. char logline[256];
  3278. int ypos;
  3279. if (opt_compact)
  3280. return;
  3281. /* Check this isn't out of the window size */
  3282. if (opt_show_procs)
  3283. ypos = cgpu->cgminer_id;
  3284. else
  3285. {
  3286. if (cgpu->proc_id)
  3287. return;
  3288. ypos = cgpu->device_line_id;
  3289. }
  3290. ypos += devsummaryYOffset;
  3291. if (ypos < 0)
  3292. return;
  3293. ypos += devcursor - 1;
  3294. if (ypos >= statusy - 1)
  3295. return;
  3296. if (wmove(statuswin, ypos, 0) == ERR)
  3297. return;
  3298. get_statline2(logline, sizeof(logline), cgpu, true);
  3299. if (selecting_device && (opt_show_procs ? (selected_device == cgpu->cgminer_id) : (devices[selected_device]->device == cgpu)))
  3300. wattron(statuswin, A_REVERSE);
  3301. bfg_waddstr(statuswin, logline);
  3302. wattroff(statuswin, A_REVERSE);
  3303. wclrtoeol(statuswin);
  3304. }
  3305. static
  3306. void refresh_devstatus() {
  3307. if (curses_active_locked()) {
  3308. int i;
  3309. for (i = 0; i < total_devices; i++)
  3310. curses_print_devstatus(get_devices(i));
  3311. touchwin(statuswin);
  3312. wrefresh(statuswin);
  3313. unlock_curses();
  3314. }
  3315. }
  3316. #endif
  3317. static void print_status(int thr_id)
  3318. {
  3319. if (!curses_active)
  3320. text_print_status(thr_id);
  3321. }
  3322. #ifdef HAVE_CURSES
  3323. /* Check for window resize. Called with curses mutex locked */
  3324. static inline void change_logwinsize(void)
  3325. {
  3326. int x, y, logx, logy;
  3327. getmaxyx(mainwin, y, x);
  3328. if (x < 80 || y < 25)
  3329. return;
  3330. if (y > statusy + 2 && statusy < logstart) {
  3331. if (y - 2 < logstart)
  3332. statusy = y - 2;
  3333. else
  3334. statusy = logstart;
  3335. logcursor = statusy;
  3336. mvwin(logwin, logcursor, 0);
  3337. bfg_wresize(statuswin, statusy, x);
  3338. }
  3339. y -= logcursor;
  3340. getmaxyx(logwin, logy, logx);
  3341. /* Detect screen size change */
  3342. if (x != logx || y != logy)
  3343. bfg_wresize(logwin, y, x);
  3344. }
  3345. static void check_winsizes(void)
  3346. {
  3347. if (!use_curses)
  3348. return;
  3349. if (curses_active_locked()) {
  3350. int y, x;
  3351. erase();
  3352. x = getmaxx(statuswin);
  3353. if (logstart > LINES - 2)
  3354. statusy = LINES - 2;
  3355. else
  3356. statusy = logstart;
  3357. logcursor = statusy;
  3358. bfg_wresize(statuswin, statusy, x);
  3359. getmaxyx(mainwin, y, x);
  3360. y -= logcursor;
  3361. bfg_wresize(logwin, y, x);
  3362. mvwin(logwin, logcursor, 0);
  3363. unlock_curses();
  3364. }
  3365. }
  3366. static int device_line_id_count;
  3367. static void switch_logsize(void)
  3368. {
  3369. if (curses_active_locked()) {
  3370. if (opt_compact) {
  3371. logstart = devcursor - 1;
  3372. logcursor = logstart + 1;
  3373. } else {
  3374. total_lines = (opt_show_procs ? total_devices : device_line_id_count);
  3375. logstart = devcursor + total_lines;
  3376. logcursor = logstart;
  3377. }
  3378. unlock_curses();
  3379. }
  3380. check_winsizes();
  3381. }
  3382. /* For mandatory printing when mutex is already locked */
  3383. void _wlog(const char *str)
  3384. {
  3385. static bool newline;
  3386. size_t end = strlen(str) - 1;
  3387. if (newline)
  3388. bfg_waddstr(logwin, "\n");
  3389. if (str[end] == '\n')
  3390. {
  3391. char *s;
  3392. newline = true;
  3393. s = alloca(end + 1);
  3394. memcpy(s, str, end);
  3395. s[end] = '\0';
  3396. str = s;
  3397. }
  3398. else
  3399. newline = false;
  3400. bfg_waddstr(logwin, str);
  3401. }
  3402. /* Mandatory printing */
  3403. void _wlogprint(const char *str)
  3404. {
  3405. if (curses_active_locked()) {
  3406. _wlog(str);
  3407. unlock_curses();
  3408. }
  3409. }
  3410. #endif
  3411. #ifdef HAVE_CURSES
  3412. bool _log_curses_only(int prio, const char *datetime, const char *str)
  3413. {
  3414. bool high_prio;
  3415. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  3416. if (curses_active)
  3417. {
  3418. if (!opt_loginput || high_prio) {
  3419. wlog(" %s %s\n", datetime, str);
  3420. if (high_prio) {
  3421. touchwin(logwin);
  3422. wrefresh(logwin);
  3423. }
  3424. }
  3425. return true;
  3426. }
  3427. return false;
  3428. }
  3429. void clear_logwin(void)
  3430. {
  3431. if (curses_active_locked()) {
  3432. wclear(logwin);
  3433. unlock_curses();
  3434. }
  3435. }
  3436. void logwin_update(void)
  3437. {
  3438. if (curses_active_locked()) {
  3439. touchwin(logwin);
  3440. wrefresh(logwin);
  3441. unlock_curses();
  3442. }
  3443. }
  3444. #endif
  3445. static void enable_pool(struct pool *pool)
  3446. {
  3447. if (pool->enabled != POOL_ENABLED) {
  3448. enabled_pools++;
  3449. pool->enabled = POOL_ENABLED;
  3450. }
  3451. }
  3452. #ifdef HAVE_CURSES
  3453. static void disable_pool(struct pool *pool)
  3454. {
  3455. if (pool->enabled == POOL_ENABLED)
  3456. enabled_pools--;
  3457. pool->enabled = POOL_DISABLED;
  3458. }
  3459. #endif
  3460. static void reject_pool(struct pool *pool)
  3461. {
  3462. if (pool->enabled == POOL_ENABLED)
  3463. enabled_pools--;
  3464. pool->enabled = POOL_REJECTING;
  3465. }
  3466. static uint64_t share_diff(const struct work *);
  3467. static
  3468. void share_result_msg(const struct work *work, const char *disp, const char *reason, bool resubmit, const char *worktime) {
  3469. struct cgpu_info *cgpu;
  3470. const unsigned char *hashpart = &work->hash[opt_scrypt ? 26 : 24];
  3471. char shrdiffdisp[16];
  3472. int tgtdiff = floor(work->work_difficulty);
  3473. char tgtdiffdisp[16];
  3474. char where[20];
  3475. cgpu = get_thr_cgpu(work->thr_id);
  3476. suffix_string(work->share_diff, shrdiffdisp, sizeof(shrdiffdisp), 0);
  3477. suffix_string(tgtdiff, tgtdiffdisp, sizeof(tgtdiffdisp), 0);
  3478. if (total_pools > 1)
  3479. snprintf(where, sizeof(where), " pool %d", work->pool->pool_no);
  3480. else
  3481. where[0] = '\0';
  3482. applog(LOG_NOTICE, "%s %02x%02x%02x%02x %"PRIprepr"%s Diff %s/%s%s %s%s",
  3483. disp,
  3484. (unsigned)hashpart[3], (unsigned)hashpart[2], (unsigned)hashpart[1], (unsigned)hashpart[0],
  3485. cgpu->proc_repr,
  3486. where,
  3487. shrdiffdisp, tgtdiffdisp,
  3488. reason,
  3489. resubmit ? "(resubmit)" : "",
  3490. worktime
  3491. );
  3492. }
  3493. static bool test_work_current(struct work *);
  3494. static void _submit_work_async(struct work *);
  3495. static
  3496. void maybe_local_submit(const struct work *work)
  3497. {
  3498. #if BLKMAKER_VERSION > 3
  3499. if (unlikely(work->block && work->tmpl))
  3500. {
  3501. // This is a block with a full template (GBT)
  3502. // Regardless of the result, submit to local bitcoind(s) as well
  3503. struct work *work_cp;
  3504. char *p;
  3505. for (int i = 0; i < total_pools; ++i)
  3506. {
  3507. p = strchr(pools[i]->rpc_url, '#');
  3508. if (likely(!(p && strstr(&p[1], "allblocks"))))
  3509. continue;
  3510. applog(LOG_DEBUG, "Attempting submission of full block to pool %d", pools[i]->pool_no);
  3511. work_cp = copy_work(work);
  3512. work_cp->pool = pools[i];
  3513. work_cp->do_foreign_submit = true;
  3514. _submit_work_async(work_cp);
  3515. }
  3516. }
  3517. #endif
  3518. }
  3519. /* Theoretically threads could race when modifying accepted and
  3520. * rejected values but the chance of two submits completing at the
  3521. * same time is zero so there is no point adding extra locking */
  3522. static void
  3523. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  3524. /*char *hashshow,*/ bool resubmit, char *worktime)
  3525. {
  3526. struct pool *pool = work->pool;
  3527. struct cgpu_info *cgpu;
  3528. cgpu = get_thr_cgpu(work->thr_id);
  3529. if ((json_is_null(err) || !err) && (json_is_null(res) || json_is_true(res))) {
  3530. mutex_lock(&stats_lock);
  3531. cgpu->accepted++;
  3532. total_accepted++;
  3533. pool->accepted++;
  3534. cgpu->diff_accepted += work->work_difficulty;
  3535. total_diff_accepted += work->work_difficulty;
  3536. pool->diff_accepted += work->work_difficulty;
  3537. mutex_unlock(&stats_lock);
  3538. pool->seq_rejects = 0;
  3539. cgpu->last_share_pool = pool->pool_no;
  3540. cgpu->last_share_pool_time = time(NULL);
  3541. cgpu->last_share_diff = work->work_difficulty;
  3542. pool->last_share_time = cgpu->last_share_pool_time;
  3543. pool->last_share_diff = work->work_difficulty;
  3544. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  3545. if (!QUIET) {
  3546. share_result_msg(work, "Accepted", "", resubmit, worktime);
  3547. }
  3548. sharelog("accept", work);
  3549. if (opt_shares && total_diff_accepted >= opt_shares) {
  3550. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  3551. kill_work();
  3552. return;
  3553. }
  3554. /* Detect if a pool that has been temporarily disabled for
  3555. * continually rejecting shares has started accepting shares.
  3556. * This will only happen with the work returned from a
  3557. * longpoll */
  3558. if (unlikely(pool->enabled == POOL_REJECTING)) {
  3559. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  3560. enable_pool(pool);
  3561. switch_pools(NULL);
  3562. }
  3563. if (unlikely(work->block)) {
  3564. // Force moving on to this new block :)
  3565. struct work fakework;
  3566. memset(&fakework, 0, sizeof(fakework));
  3567. fakework.pool = work->pool;
  3568. // Copy block version, bits, and time from share
  3569. memcpy(&fakework.data[ 0], &work->data[ 0], 4);
  3570. memcpy(&fakework.data[68], &work->data[68], 8);
  3571. // Set prevblock to winning hash (swap32'd)
  3572. swap32yes(&fakework.data[4], &work->hash[0], 32 / 4);
  3573. test_work_current(&fakework);
  3574. }
  3575. } else {
  3576. mutex_lock(&stats_lock);
  3577. cgpu->rejected++;
  3578. total_rejected++;
  3579. pool->rejected++;
  3580. cgpu->diff_rejected += work->work_difficulty;
  3581. total_diff_rejected += work->work_difficulty;
  3582. pool->diff_rejected += work->work_difficulty;
  3583. pool->seq_rejects++;
  3584. mutex_unlock(&stats_lock);
  3585. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  3586. if (!QUIET) {
  3587. char where[20];
  3588. char disposition[36] = "reject";
  3589. char reason[32];
  3590. strcpy(reason, "");
  3591. if (total_pools > 1)
  3592. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  3593. else
  3594. strcpy(where, "");
  3595. if (!json_is_string(res))
  3596. res = json_object_get(val, "reject-reason");
  3597. if (res) {
  3598. const char *reasontmp = json_string_value(res);
  3599. size_t reasonLen = strlen(reasontmp);
  3600. if (reasonLen > 28)
  3601. reasonLen = 28;
  3602. reason[0] = ' '; reason[1] = '(';
  3603. memcpy(2 + reason, reasontmp, reasonLen);
  3604. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  3605. memcpy(disposition + 7, reasontmp, reasonLen);
  3606. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  3607. } else if (work->stratum && err && json_is_array(err)) {
  3608. json_t *reason_val = json_array_get(err, 1);
  3609. char *reason_str;
  3610. if (reason_val && json_is_string(reason_val)) {
  3611. reason_str = (char *)json_string_value(reason_val);
  3612. snprintf(reason, 31, " (%s)", reason_str);
  3613. }
  3614. }
  3615. share_result_msg(work, "Rejected", reason, resubmit, worktime);
  3616. sharelog(disposition, work);
  3617. }
  3618. /* Once we have more than a nominal amount of sequential rejects,
  3619. * at least 10 and more than 3 mins at the current utility,
  3620. * disable the pool because some pool error is likely to have
  3621. * ensued. Do not do this if we know the share just happened to
  3622. * be stale due to networking delays.
  3623. */
  3624. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  3625. double utility = total_accepted / total_secs * 60;
  3626. if (pool->seq_rejects > utility * 3) {
  3627. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  3628. pool->pool_no, pool->seq_rejects);
  3629. reject_pool(pool);
  3630. if (pool == current_pool())
  3631. switch_pools(NULL);
  3632. pool->seq_rejects = 0;
  3633. }
  3634. }
  3635. }
  3636. maybe_local_submit(work);
  3637. }
  3638. static char *submit_upstream_work_request(struct work *work)
  3639. {
  3640. char *hexstr = NULL;
  3641. char *s, *sd;
  3642. struct pool *pool = work->pool;
  3643. if (work->tmpl) {
  3644. json_t *req;
  3645. unsigned char data[80];
  3646. swap32yes(data, work->data, 80 / 4);
  3647. #if BLKMAKER_VERSION > 3
  3648. if (work->do_foreign_submit)
  3649. req = blkmk_submit_foreign_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3650. else
  3651. #endif
  3652. req = blkmk_submit_jansson(work->tmpl, data, work->dataid, le32toh(*((uint32_t*)&work->data[76])));
  3653. s = json_dumps(req, 0);
  3654. json_decref(req);
  3655. sd = malloc(161);
  3656. bin2hex(sd, data, 80);
  3657. } else {
  3658. /* build hex string */
  3659. hexstr = malloc((sizeof(work->data) * 2) + 1);
  3660. bin2hex(hexstr, work->data, sizeof(work->data));
  3661. /* build JSON-RPC request */
  3662. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  3663. s = realloc_strcat(s, hexstr);
  3664. s = realloc_strcat(s, "\" ], \"id\":1}");
  3665. free(hexstr);
  3666. sd = s;
  3667. }
  3668. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  3669. if (work->tmpl)
  3670. free(sd);
  3671. else
  3672. s = realloc_strcat(s, "\n");
  3673. return s;
  3674. }
  3675. static bool submit_upstream_work_completed(struct work *work, bool resubmit, struct timeval *ptv_submit, json_t *val) {
  3676. json_t *res, *err;
  3677. bool rc = false;
  3678. int thr_id = work->thr_id;
  3679. struct pool *pool = work->pool;
  3680. struct timeval tv_submit_reply;
  3681. time_t ts_submit_reply;
  3682. char worktime[200] = "";
  3683. cgtime(&tv_submit_reply);
  3684. ts_submit_reply = time(NULL);
  3685. if (unlikely(!val)) {
  3686. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  3687. if (!pool_tset(pool, &pool->submit_fail)) {
  3688. total_ro++;
  3689. pool->remotefail_occasions++;
  3690. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  3691. }
  3692. goto out;
  3693. } else if (pool_tclear(pool, &pool->submit_fail))
  3694. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  3695. res = json_object_get(val, "result");
  3696. err = json_object_get(val, "error");
  3697. if (!QUIET) {
  3698. if (opt_worktime) {
  3699. char workclone[20];
  3700. struct tm _tm;
  3701. struct tm *tm, tm_getwork, tm_submit_reply;
  3702. tm = &_tm;
  3703. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  3704. (struct timeval *)&(work->tv_getwork));
  3705. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  3706. (struct timeval *)&(work->tv_getwork_reply));
  3707. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  3708. (struct timeval *)&(work->tv_work_start));
  3709. double work_to_submit = tdiff(ptv_submit,
  3710. (struct timeval *)&(work->tv_work_found));
  3711. double submit_time = tdiff(&tv_submit_reply, ptv_submit);
  3712. int diffplaces = 3;
  3713. localtime_r(&work->ts_getwork, tm);
  3714. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3715. localtime_r(&ts_submit_reply, tm);
  3716. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3717. if (work->clone) {
  3718. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3719. tdiff((struct timeval *)&(work->tv_cloned),
  3720. (struct timeval *)&(work->tv_getwork_reply)));
  3721. }
  3722. else
  3723. strcpy(workclone, "O");
  3724. if (work->work_difficulty < 1)
  3725. diffplaces = 6;
  3726. snprintf(worktime, sizeof(worktime),
  3727. " <-%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",
  3728. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3729. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3730. work->getwork_mode, diffplaces, work->work_difficulty,
  3731. tm_getwork.tm_hour, tm_getwork.tm_min,
  3732. tm_getwork.tm_sec, getwork_time, workclone,
  3733. getwork_to_work, work_time, work_to_submit, submit_time,
  3734. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3735. tm_submit_reply.tm_sec);
  3736. }
  3737. }
  3738. share_result(val, res, err, work, resubmit, worktime);
  3739. if (!opt_realquiet)
  3740. print_status(thr_id);
  3741. if (!want_per_device_stats) {
  3742. char logline[256];
  3743. struct cgpu_info *cgpu;
  3744. cgpu = get_thr_cgpu(thr_id);
  3745. get_statline(logline, sizeof(logline), cgpu);
  3746. applog(LOG_INFO, "%s", logline);
  3747. }
  3748. json_decref(val);
  3749. rc = true;
  3750. out:
  3751. return rc;
  3752. }
  3753. /* Specifies whether we can use this pool for work or not. */
  3754. static bool pool_unworkable(struct pool *pool)
  3755. {
  3756. if (pool->idle)
  3757. return true;
  3758. if (pool->enabled != POOL_ENABLED)
  3759. return true;
  3760. if (pool->has_stratum && !pool->stratum_active)
  3761. return true;
  3762. return false;
  3763. }
  3764. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3765. * rolling average per 10 minutes and if pools start getting more, it biases
  3766. * away from them to distribute work evenly. The share count is reset to the
  3767. * rolling average every 10 minutes to not send all work to one pool after it
  3768. * has been disabled/out for an extended period. */
  3769. static struct pool *select_balanced(struct pool *cp)
  3770. {
  3771. int i, lowest = cp->shares;
  3772. struct pool *ret = cp;
  3773. for (i = 0; i < total_pools; i++) {
  3774. struct pool *pool = pools[i];
  3775. if (pool_unworkable(pool))
  3776. continue;
  3777. if (pool->shares < lowest) {
  3778. lowest = pool->shares;
  3779. ret = pool;
  3780. }
  3781. }
  3782. ret->shares++;
  3783. return ret;
  3784. }
  3785. static bool pool_active(struct pool *, bool pinging);
  3786. static void pool_died(struct pool *);
  3787. static struct pool *priority_pool(int choice);
  3788. static bool pool_unusable(struct pool *pool);
  3789. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3790. * it has any quota left. */
  3791. static inline struct pool *select_pool(bool lagging)
  3792. {
  3793. static int rotating_pool = 0;
  3794. struct pool *pool, *cp;
  3795. bool avail = false;
  3796. int tested, i;
  3797. cp = current_pool();
  3798. retry:
  3799. if (pool_strategy == POOL_BALANCE) {
  3800. pool = select_balanced(cp);
  3801. goto out;
  3802. }
  3803. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3804. pool = cp;
  3805. goto out;
  3806. } else
  3807. pool = NULL;
  3808. for (i = 0; i < total_pools; i++) {
  3809. struct pool *tp = pools[i];
  3810. if (tp->quota_used < tp->quota_gcd) {
  3811. avail = true;
  3812. break;
  3813. }
  3814. }
  3815. /* There are no pools with quota, so reset them. */
  3816. if (!avail) {
  3817. for (i = 0; i < total_pools; i++)
  3818. pools[i]->quota_used = 0;
  3819. if (++rotating_pool >= total_pools)
  3820. rotating_pool = 0;
  3821. }
  3822. /* Try to find the first pool in the rotation that is usable */
  3823. tested = 0;
  3824. while (!pool && tested++ < total_pools) {
  3825. pool = pools[rotating_pool];
  3826. if (pool->quota_used++ < pool->quota_gcd) {
  3827. if (!pool_unworkable(pool))
  3828. break;
  3829. /* Failover-only flag for load-balance means distribute
  3830. * unused quota to priority pool 0. */
  3831. if (opt_fail_only)
  3832. priority_pool(0)->quota_used--;
  3833. }
  3834. pool = NULL;
  3835. if (++rotating_pool >= total_pools)
  3836. rotating_pool = 0;
  3837. }
  3838. /* If there are no alive pools with quota, choose according to
  3839. * priority. */
  3840. if (!pool) {
  3841. for (i = 0; i < total_pools; i++) {
  3842. struct pool *tp = priority_pool(i);
  3843. if (!pool_unusable(tp)) {
  3844. pool = tp;
  3845. break;
  3846. }
  3847. }
  3848. }
  3849. /* If still nothing is usable, use the current pool */
  3850. if (!pool)
  3851. pool = cp;
  3852. out:
  3853. if (cp != pool)
  3854. {
  3855. if (!pool_active(pool, false))
  3856. {
  3857. pool_died(pool);
  3858. goto retry;
  3859. }
  3860. pool_tclear(pool, &pool->idle);
  3861. }
  3862. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3863. return pool;
  3864. }
  3865. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249215.0;
  3866. static const uint64_t diffone = 0xFFFF000000000000ull;
  3867. static double target_diff(const unsigned char *target)
  3868. {
  3869. double targ = 0;
  3870. signed int i;
  3871. for (i = 31; i >= 0; --i)
  3872. targ = (targ * 0x100) + target[i];
  3873. return DIFFEXACTONE / (targ ?: 1);
  3874. }
  3875. /*
  3876. * Calculate the work share difficulty
  3877. */
  3878. static void calc_diff(struct work *work, int known)
  3879. {
  3880. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3881. double difficulty;
  3882. if (!known) {
  3883. work->work_difficulty = target_diff(work->target);
  3884. } else
  3885. work->work_difficulty = known;
  3886. difficulty = work->work_difficulty;
  3887. pool_stats->last_diff = difficulty;
  3888. suffix_string((uint64_t)difficulty, work->pool->diff, sizeof(work->pool->diff), 0);
  3889. if (difficulty == pool_stats->min_diff)
  3890. pool_stats->min_diff_count++;
  3891. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3892. pool_stats->min_diff = difficulty;
  3893. pool_stats->min_diff_count = 1;
  3894. }
  3895. if (difficulty == pool_stats->max_diff)
  3896. pool_stats->max_diff_count++;
  3897. else if (difficulty > pool_stats->max_diff) {
  3898. pool_stats->max_diff = difficulty;
  3899. pool_stats->max_diff_count = 1;
  3900. }
  3901. }
  3902. static void get_benchmark_work(struct work *work)
  3903. {
  3904. // Use a random work block pulled from a pool
  3905. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  3906. size_t bench_size = sizeof(*work);
  3907. size_t work_size = sizeof(bench_block);
  3908. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  3909. memset(work, 0, sizeof(*work));
  3910. memcpy(work, &bench_block, min_size);
  3911. work->mandatory = true;
  3912. work->pool = pools[0];
  3913. cgtime(&work->tv_getwork);
  3914. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3915. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3916. calc_diff(work, 0);
  3917. }
  3918. static void wake_gws(void);
  3919. static void update_last_work(struct work *work)
  3920. {
  3921. if (!work->tmpl)
  3922. // Only save GBT jobs, since rollntime isn't coordinated well yet
  3923. return;
  3924. struct pool *pool = work->pool;
  3925. mutex_lock(&pool->last_work_lock);
  3926. if (pool->last_work_copy)
  3927. free_work(pool->last_work_copy);
  3928. pool->last_work_copy = copy_work(work);
  3929. pool->last_work_copy->work_restart_id = pool->work_restart_id;
  3930. mutex_unlock(&pool->last_work_lock);
  3931. }
  3932. static
  3933. void gbt_req_target(json_t *req)
  3934. {
  3935. json_t *j;
  3936. json_t *n;
  3937. if (!request_target_str)
  3938. return;
  3939. j = json_object_get(req, "params");
  3940. if (!j)
  3941. {
  3942. n = json_array();
  3943. if (!n)
  3944. return;
  3945. if (json_object_set_new(req, "params", n))
  3946. goto erradd;
  3947. j = n;
  3948. }
  3949. n = json_array_get(j, 0);
  3950. if (!n)
  3951. {
  3952. n = json_object();
  3953. if (!n)
  3954. return;
  3955. if (json_array_append_new(j, n))
  3956. goto erradd;
  3957. }
  3958. j = n;
  3959. n = json_string(request_target_str);
  3960. if (!n)
  3961. return;
  3962. if (json_object_set_new(j, "target", n))
  3963. goto erradd;
  3964. return;
  3965. erradd:
  3966. json_decref(n);
  3967. }
  3968. static char *prepare_rpc_req2(struct work *work, enum pool_protocol proto, const char *lpid, bool probe)
  3969. {
  3970. char *rpc_req;
  3971. clean_work(work);
  3972. switch (proto) {
  3973. case PLP_GETWORK:
  3974. work->getwork_mode = GETWORK_MODE_POOL;
  3975. return strdup(getwork_req);
  3976. case PLP_GETBLOCKTEMPLATE:
  3977. work->getwork_mode = GETWORK_MODE_GBT;
  3978. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  3979. if (!work->tmpl_refcount)
  3980. return NULL;
  3981. work->tmpl = blktmpl_create();
  3982. if (!work->tmpl)
  3983. goto gbtfail2;
  3984. *work->tmpl_refcount = 1;
  3985. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  3986. if (!caps)
  3987. goto gbtfail;
  3988. caps |= GBT_LONGPOLL;
  3989. #if BLKMAKER_VERSION > 1
  3990. if (opt_coinbase_script.sz)
  3991. caps |= GBT_CBVALUE;
  3992. #endif
  3993. json_t *req = blktmpl_request_jansson(caps, lpid);
  3994. if (!req)
  3995. goto gbtfail;
  3996. if (probe)
  3997. gbt_req_target(req);
  3998. rpc_req = json_dumps(req, 0);
  3999. if (!rpc_req)
  4000. goto gbtfail;
  4001. json_decref(req);
  4002. return rpc_req;
  4003. default:
  4004. return NULL;
  4005. }
  4006. return NULL;
  4007. gbtfail:
  4008. blktmpl_free(work->tmpl);
  4009. work->tmpl = NULL;
  4010. gbtfail2:
  4011. free(work->tmpl_refcount);
  4012. work->tmpl_refcount = NULL;
  4013. return NULL;
  4014. }
  4015. #define prepare_rpc_req(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, false)
  4016. #define prepare_rpc_req_probe(work, proto, lpid) prepare_rpc_req2(work, proto, lpid, true)
  4017. static const char *pool_protocol_name(enum pool_protocol proto)
  4018. {
  4019. switch (proto) {
  4020. case PLP_GETBLOCKTEMPLATE:
  4021. return "getblocktemplate";
  4022. case PLP_GETWORK:
  4023. return "getwork";
  4024. default:
  4025. return "UNKNOWN";
  4026. }
  4027. }
  4028. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  4029. {
  4030. switch (proto) {
  4031. case PLP_GETBLOCKTEMPLATE:
  4032. if (want_getwork)
  4033. return PLP_GETWORK;
  4034. default:
  4035. return PLP_NONE;
  4036. }
  4037. }
  4038. static bool get_upstream_work(struct work *work, CURL *curl)
  4039. {
  4040. struct pool *pool = work->pool;
  4041. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  4042. struct timeval tv_elapsed;
  4043. json_t *val = NULL;
  4044. bool rc = false;
  4045. char *url;
  4046. enum pool_protocol proto;
  4047. char *rpc_req;
  4048. if (pool->proto == PLP_NONE)
  4049. pool->proto = PLP_GETBLOCKTEMPLATE;
  4050. tryagain:
  4051. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  4052. work->pool = pool;
  4053. if (!rpc_req)
  4054. return false;
  4055. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  4056. url = pool->rpc_url;
  4057. cgtime(&work->tv_getwork);
  4058. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  4059. false, &work->rolltime, pool, false);
  4060. pool_stats->getwork_attempts++;
  4061. free(rpc_req);
  4062. if (likely(val)) {
  4063. rc = work_decode(pool, work, val);
  4064. if (unlikely(!rc))
  4065. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  4066. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  4067. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  4068. pool->proto = proto;
  4069. goto tryagain;
  4070. } else
  4071. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  4072. cgtime(&work->tv_getwork_reply);
  4073. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  4074. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  4075. pool_stats->getwork_wait_rolling /= 1.63;
  4076. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  4077. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  4078. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  4079. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  4080. }
  4081. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  4082. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  4083. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  4084. }
  4085. pool_stats->getwork_calls++;
  4086. work->pool = pool;
  4087. work->longpoll = false;
  4088. calc_diff(work, 0);
  4089. total_getworks++;
  4090. pool->getwork_requested++;
  4091. if (rc)
  4092. update_last_work(work);
  4093. if (likely(val))
  4094. json_decref(val);
  4095. return rc;
  4096. }
  4097. #ifdef HAVE_CURSES
  4098. static void disable_curses(void)
  4099. {
  4100. if (curses_active_locked()) {
  4101. use_curses = false;
  4102. curses_active = false;
  4103. leaveok(logwin, false);
  4104. leaveok(statuswin, false);
  4105. leaveok(mainwin, false);
  4106. nocbreak();
  4107. echo();
  4108. delwin(logwin);
  4109. delwin(statuswin);
  4110. delwin(mainwin);
  4111. endwin();
  4112. #ifdef WIN32
  4113. // Move the cursor to after curses output.
  4114. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  4115. CONSOLE_SCREEN_BUFFER_INFO csbi;
  4116. COORD coord;
  4117. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  4118. coord.X = 0;
  4119. coord.Y = csbi.dwSize.Y - 1;
  4120. SetConsoleCursorPosition(hout, coord);
  4121. }
  4122. #endif
  4123. unlock_curses();
  4124. }
  4125. }
  4126. #endif
  4127. static void __kill_work(void)
  4128. {
  4129. struct cgpu_info *cgpu;
  4130. struct thr_info *thr;
  4131. int i;
  4132. if (!successful_connect)
  4133. return;
  4134. applog(LOG_INFO, "Received kill message");
  4135. shutting_down = true;
  4136. applog(LOG_DEBUG, "Prompting submit_work thread to finish");
  4137. notifier_wake(submit_waiting_notifier);
  4138. #ifdef USE_LIBMICROHTTPD
  4139. httpsrv_stop();
  4140. #endif
  4141. applog(LOG_DEBUG, "Killing off watchpool thread");
  4142. /* Kill the watchpool thread */
  4143. thr = &control_thr[watchpool_thr_id];
  4144. thr_info_cancel(thr);
  4145. applog(LOG_DEBUG, "Killing off watchdog thread");
  4146. /* Kill the watchdog thread */
  4147. thr = &control_thr[watchdog_thr_id];
  4148. thr_info_cancel(thr);
  4149. applog(LOG_DEBUG, "Shutting down mining threads");
  4150. for (i = 0; i < mining_threads; i++) {
  4151. thr = get_thread(i);
  4152. if (!thr)
  4153. continue;
  4154. cgpu = thr->cgpu;
  4155. if (!cgpu)
  4156. continue;
  4157. if (!cgpu->threads)
  4158. continue;
  4159. cgpu->shutdown = true;
  4160. thr->work_restart = true;
  4161. notifier_wake(thr->notifier);
  4162. notifier_wake(thr->work_restart_notifier);
  4163. }
  4164. sleep(1);
  4165. applog(LOG_DEBUG, "Killing off mining threads");
  4166. /* Kill the mining threads*/
  4167. for (i = 0; i < mining_threads; i++) {
  4168. thr = get_thread(i);
  4169. if (!thr)
  4170. continue;
  4171. cgpu = thr->cgpu;
  4172. if (cgpu->threads)
  4173. {
  4174. applog(LOG_WARNING, "Killing %"PRIpreprv, thr->cgpu->proc_repr);
  4175. thr_info_cancel(thr);
  4176. }
  4177. cgpu->status = LIFE_DEAD2;
  4178. }
  4179. /* Stop the others */
  4180. applog(LOG_DEBUG, "Killing off API thread");
  4181. thr = &control_thr[api_thr_id];
  4182. thr_info_cancel(thr);
  4183. }
  4184. /* This should be the common exit path */
  4185. void kill_work(void)
  4186. {
  4187. __kill_work();
  4188. quit(0, "Shutdown signal received.");
  4189. }
  4190. static
  4191. #ifdef WIN32
  4192. #ifndef _WIN64
  4193. const
  4194. #endif
  4195. #endif
  4196. char **initial_args;
  4197. void _bfg_clean_up(bool);
  4198. void app_restart(void)
  4199. {
  4200. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  4201. __kill_work();
  4202. _bfg_clean_up(true);
  4203. #if defined(unix) || defined(__APPLE__)
  4204. if (forkpid > 0) {
  4205. kill(forkpid, SIGTERM);
  4206. forkpid = 0;
  4207. }
  4208. #endif
  4209. execv(initial_args[0], initial_args);
  4210. applog(LOG_WARNING, "Failed to restart application");
  4211. }
  4212. static void sighandler(int __maybe_unused sig)
  4213. {
  4214. /* Restore signal handlers so we can still quit if kill_work fails */
  4215. sigaction(SIGTERM, &termhandler, NULL);
  4216. sigaction(SIGINT, &inthandler, NULL);
  4217. kill_work();
  4218. }
  4219. static void start_longpoll(void);
  4220. static void stop_longpoll(void);
  4221. /* Called with pool_lock held. Recruit an extra curl if none are available for
  4222. * this pool. */
  4223. static void recruit_curl(struct pool *pool)
  4224. {
  4225. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  4226. if (unlikely(!ce))
  4227. quit(1, "Failed to calloc in recruit_curl");
  4228. ce->curl = curl_easy_init();
  4229. if (unlikely(!ce->curl))
  4230. quit(1, "Failed to init in recruit_curl");
  4231. LL_PREPEND(pool->curllist, ce);
  4232. pool->curls++;
  4233. }
  4234. /* Grab an available curl if there is one. If not, then recruit extra curls
  4235. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  4236. * and there are already 5 curls in circulation. Limit total number to the
  4237. * number of mining threads per pool as well to prevent blasting a pool during
  4238. * network delays/outages. */
  4239. static struct curl_ent *pop_curl_entry3(struct pool *pool, int blocking)
  4240. {
  4241. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  4242. bool recruited = false;
  4243. struct curl_ent *ce;
  4244. mutex_lock(&pool->pool_lock);
  4245. retry:
  4246. if (!pool->curls) {
  4247. recruit_curl(pool);
  4248. recruited = true;
  4249. } else if (!pool->curllist) {
  4250. if (blocking < 2 && pool->curls >= curl_limit && (blocking || pool->curls >= opt_submit_threads)) {
  4251. if (!blocking) {
  4252. mutex_unlock(&pool->pool_lock);
  4253. return NULL;
  4254. }
  4255. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  4256. goto retry;
  4257. } else {
  4258. recruit_curl(pool);
  4259. recruited = true;
  4260. }
  4261. }
  4262. ce = pool->curllist;
  4263. LL_DELETE(pool->curllist, ce);
  4264. mutex_unlock(&pool->pool_lock);
  4265. if (recruited)
  4266. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  4267. return ce;
  4268. }
  4269. static struct curl_ent *pop_curl_entry2(struct pool *pool, bool blocking)
  4270. {
  4271. return pop_curl_entry3(pool, blocking ? 1 : 0);
  4272. }
  4273. __maybe_unused
  4274. static struct curl_ent *pop_curl_entry(struct pool *pool)
  4275. {
  4276. return pop_curl_entry3(pool, 1);
  4277. }
  4278. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  4279. {
  4280. mutex_lock(&pool->pool_lock);
  4281. if (!ce || !ce->curl)
  4282. quithere(1, "Attempted to add NULL");
  4283. LL_PREPEND(pool->curllist, ce);
  4284. cgtime(&ce->tv);
  4285. pthread_cond_broadcast(&pool->cr_cond);
  4286. mutex_unlock(&pool->pool_lock);
  4287. }
  4288. bool stale_work(struct work *work, bool share);
  4289. static inline bool should_roll(struct work *work)
  4290. {
  4291. struct timeval now;
  4292. time_t expiry;
  4293. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  4294. return false;
  4295. if (stale_work(work, false))
  4296. return false;
  4297. if (work->rolltime > opt_scantime)
  4298. expiry = work->rolltime;
  4299. else
  4300. expiry = opt_scantime;
  4301. expiry = expiry * 2 / 3;
  4302. /* We shouldn't roll if we're unlikely to get one shares' duration
  4303. * work out of doing so */
  4304. cgtime(&now);
  4305. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  4306. return false;
  4307. return true;
  4308. }
  4309. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  4310. * reject blocks as invalid. */
  4311. static inline bool can_roll(struct work *work)
  4312. {
  4313. if (work->stratum)
  4314. return false;
  4315. if (!(work->pool && !work->clone))
  4316. return false;
  4317. if (work->tmpl) {
  4318. if (stale_work(work, false))
  4319. return false;
  4320. return blkmk_work_left(work->tmpl);
  4321. }
  4322. return (work->rolltime &&
  4323. work->rolls < 7000 && !stale_work(work, false));
  4324. }
  4325. static void roll_work(struct work *work)
  4326. {
  4327. if (work->tmpl) {
  4328. struct timeval tv_now;
  4329. cgtime(&tv_now);
  4330. if (blkmk_get_data(work->tmpl, work->data, 80, tv_now.tv_sec, NULL, &work->dataid) < 76)
  4331. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  4332. swap32yes(work->data, work->data, 80 / 4);
  4333. calc_midstate(work);
  4334. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  4335. } else {
  4336. uint32_t *work_ntime;
  4337. uint32_t ntime;
  4338. work_ntime = (uint32_t *)(work->data + 68);
  4339. ntime = be32toh(*work_ntime);
  4340. ntime++;
  4341. *work_ntime = htobe32(ntime);
  4342. applog(LOG_DEBUG, "Successfully rolled time header in work");
  4343. }
  4344. local_work++;
  4345. work->rolls++;
  4346. work->blk.nonce = 0;
  4347. /* This is now a different work item so it needs a different ID for the
  4348. * hashtable */
  4349. work->id = total_work++;
  4350. }
  4351. /* Duplicates any dynamically allocated arrays within the work struct to
  4352. * prevent a copied work struct from freeing ram belonging to another struct */
  4353. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  4354. {
  4355. int id = work->id;
  4356. clean_work(work);
  4357. memcpy(work, base_work, sizeof(struct work));
  4358. /* Keep the unique new id assigned during make_work to prevent copied
  4359. * work from having the same id. */
  4360. work->id = id;
  4361. if (base_work->job_id)
  4362. work->job_id = strdup(base_work->job_id);
  4363. if (base_work->nonce1)
  4364. work->nonce1 = strdup(base_work->nonce1);
  4365. bytes_cpy(&work->nonce2, &base_work->nonce2);
  4366. if (base_work->tmpl) {
  4367. struct pool *pool = work->pool;
  4368. mutex_lock(&pool->pool_lock);
  4369. ++*work->tmpl_refcount;
  4370. mutex_unlock(&pool->pool_lock);
  4371. }
  4372. if (noffset)
  4373. {
  4374. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  4375. uint32_t ntime = be32toh(*work_ntime);
  4376. ntime += noffset;
  4377. *work_ntime = htobe32(ntime);
  4378. }
  4379. }
  4380. /* Generates a copy of an existing work struct, creating fresh heap allocations
  4381. * for all dynamically allocated arrays within the struct */
  4382. struct work *copy_work(const struct work *base_work)
  4383. {
  4384. struct work *work = make_work();
  4385. _copy_work(work, base_work, 0);
  4386. return work;
  4387. }
  4388. void __copy_work(struct work *work, const struct work *base_work)
  4389. {
  4390. _copy_work(work, base_work, 0);
  4391. }
  4392. static struct work *make_clone(struct work *work)
  4393. {
  4394. struct work *work_clone = copy_work(work);
  4395. work_clone->clone = true;
  4396. cgtime((struct timeval *)&(work_clone->tv_cloned));
  4397. work_clone->longpoll = false;
  4398. work_clone->mandatory = false;
  4399. /* Make cloned work appear slightly older to bias towards keeping the
  4400. * master work item which can be further rolled */
  4401. work_clone->tv_staged.tv_sec -= 1;
  4402. return work_clone;
  4403. }
  4404. static void stage_work(struct work *work);
  4405. static bool clone_available(void)
  4406. {
  4407. struct work *work_clone = NULL, *work, *tmp;
  4408. bool cloned = false;
  4409. mutex_lock(stgd_lock);
  4410. if (!staged_rollable)
  4411. goto out_unlock;
  4412. HASH_ITER(hh, staged_work, work, tmp) {
  4413. if (can_roll(work) && should_roll(work)) {
  4414. roll_work(work);
  4415. work_clone = make_clone(work);
  4416. applog(LOG_DEBUG, "%s: Rolling work %d to %d", __func__, work->id, work_clone->id);
  4417. roll_work(work);
  4418. cloned = true;
  4419. break;
  4420. }
  4421. }
  4422. out_unlock:
  4423. mutex_unlock(stgd_lock);
  4424. if (cloned) {
  4425. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  4426. stage_work(work_clone);
  4427. }
  4428. return cloned;
  4429. }
  4430. static void pool_died(struct pool *pool)
  4431. {
  4432. if (!pool_tset(pool, &pool->idle)) {
  4433. cgtime(&pool->tv_idle);
  4434. if (pool == current_pool()) {
  4435. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  4436. switch_pools(NULL);
  4437. } else
  4438. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  4439. }
  4440. }
  4441. bool stale_work(struct work *work, bool share)
  4442. {
  4443. unsigned work_expiry;
  4444. struct pool *pool;
  4445. uint32_t block_id;
  4446. unsigned getwork_delay;
  4447. if (opt_benchmark)
  4448. return false;
  4449. block_id = ((uint32_t*)work->data)[1];
  4450. pool = work->pool;
  4451. /* Technically the rolltime should be correct but some pools
  4452. * advertise a broken expire= that is lower than a meaningful
  4453. * scantime */
  4454. if (work->rolltime >= opt_scantime || work->tmpl)
  4455. work_expiry = work->rolltime;
  4456. else
  4457. work_expiry = opt_expiry;
  4458. unsigned max_expiry = (have_longpoll ? opt_expiry_lp : opt_expiry);
  4459. if (work_expiry > max_expiry)
  4460. work_expiry = max_expiry;
  4461. if (share) {
  4462. /* If the share isn't on this pool's latest block, it's stale */
  4463. if (pool->block_id && pool->block_id != block_id)
  4464. {
  4465. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  4466. return true;
  4467. }
  4468. /* If the pool doesn't want old shares, then any found in work before
  4469. * the most recent longpoll is stale */
  4470. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  4471. {
  4472. applog(LOG_DEBUG, "Share stale due to mandatory work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4473. return true;
  4474. }
  4475. } else {
  4476. /* If this work isn't for the latest Bitcoin block, it's stale */
  4477. /* But only care about the current pool if failover-only */
  4478. if (enabled_pools <= 1 || opt_fail_only) {
  4479. if (pool->block_id && block_id != pool->block_id)
  4480. {
  4481. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4482. return true;
  4483. }
  4484. } else {
  4485. if (block_id != current_block_id)
  4486. {
  4487. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  4488. return true;
  4489. }
  4490. }
  4491. /* If the pool has asked us to restart since this work, it's stale */
  4492. if (work->work_restart_id != pool->work_restart_id)
  4493. {
  4494. applog(LOG_DEBUG, "Work stale due to work update (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  4495. return true;
  4496. }
  4497. if (pool->has_stratum && work->job_id) {
  4498. bool same_job;
  4499. if (!pool->stratum_active || !pool->stratum_notify) {
  4500. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  4501. return true;
  4502. }
  4503. same_job = true;
  4504. cg_rlock(&pool->data_lock);
  4505. if (strcmp(work->job_id, pool->swork.job_id))
  4506. same_job = false;
  4507. cg_runlock(&pool->data_lock);
  4508. if (!same_job) {
  4509. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  4510. return true;
  4511. }
  4512. }
  4513. /* Factor in the average getwork delay of this pool, rounding it up to
  4514. * the nearest second */
  4515. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  4516. if (unlikely(work_expiry <= getwork_delay + 5))
  4517. work_expiry = 5;
  4518. else
  4519. work_expiry -= getwork_delay;
  4520. }
  4521. int elapsed_since_staged = timer_elapsed(&work->tv_staged, NULL);
  4522. if (elapsed_since_staged > work_expiry) {
  4523. applog(LOG_DEBUG, "%s stale due to expiry (%d >= %u)", share?"Share":"Work", elapsed_since_staged, work_expiry);
  4524. return true;
  4525. }
  4526. /* If the user only wants strict failover, any work from a pool other than
  4527. * the current one is always considered stale */
  4528. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  4529. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4530. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  4531. return true;
  4532. }
  4533. return false;
  4534. }
  4535. static uint64_t share_diff(const struct work *work)
  4536. {
  4537. uint64_t ret;
  4538. bool new_best = false;
  4539. ret = target_diff(work->hash);
  4540. cg_wlock(&control_lock);
  4541. if (unlikely(ret > best_diff)) {
  4542. new_best = true;
  4543. best_diff = ret;
  4544. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4545. }
  4546. if (unlikely(ret > work->pool->best_diff))
  4547. work->pool->best_diff = ret;
  4548. cg_wunlock(&control_lock);
  4549. if (unlikely(new_best))
  4550. applog(LOG_INFO, "New best share: %s", best_share);
  4551. return ret;
  4552. }
  4553. static void regen_hash(struct work *work)
  4554. {
  4555. hash_data(work->hash, work->data);
  4556. }
  4557. static void rebuild_hash(struct work *work)
  4558. {
  4559. if (opt_scrypt)
  4560. scrypt_regenhash(work);
  4561. else
  4562. regen_hash(work);
  4563. work->share_diff = share_diff(work);
  4564. if (unlikely(work->share_diff >= current_diff)) {
  4565. work->block = true;
  4566. work->pool->solved++;
  4567. found_blocks++;
  4568. work->mandatory = true;
  4569. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  4570. }
  4571. }
  4572. static void submit_discard_share2(const char *reason, struct work *work)
  4573. {
  4574. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  4575. sharelog(reason, work);
  4576. mutex_lock(&stats_lock);
  4577. ++total_stale;
  4578. ++cgpu->stale;
  4579. ++(work->pool->stale_shares);
  4580. total_diff_stale += work->work_difficulty;
  4581. cgpu->diff_stale += work->work_difficulty;
  4582. work->pool->diff_stale += work->work_difficulty;
  4583. mutex_unlock(&stats_lock);
  4584. }
  4585. static void submit_discard_share(struct work *work)
  4586. {
  4587. submit_discard_share2("discard", work);
  4588. }
  4589. struct submit_work_state {
  4590. struct work *work;
  4591. bool resubmit;
  4592. struct curl_ent *ce;
  4593. int failures;
  4594. struct timeval tv_staleexpire;
  4595. char *s;
  4596. struct timeval tv_submit;
  4597. struct submit_work_state *next;
  4598. };
  4599. static int my_curl_timer_set(__maybe_unused CURLM *curlm, long timeout_ms, void *userp)
  4600. {
  4601. long *p_timeout_us = userp;
  4602. const long max_ms = LONG_MAX / 1000;
  4603. if (max_ms < timeout_ms)
  4604. timeout_ms = max_ms;
  4605. *p_timeout_us = timeout_ms * 1000;
  4606. return 0;
  4607. }
  4608. static void sws_has_ce(struct submit_work_state *sws)
  4609. {
  4610. struct pool *pool = sws->work->pool;
  4611. sws->s = submit_upstream_work_request(sws->work);
  4612. cgtime(&sws->tv_submit);
  4613. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4614. }
  4615. static struct submit_work_state *begin_submission(struct work *work)
  4616. {
  4617. struct pool *pool;
  4618. struct submit_work_state *sws = NULL;
  4619. pool = work->pool;
  4620. sws = malloc(sizeof(*sws));
  4621. *sws = (struct submit_work_state){
  4622. .work = work,
  4623. };
  4624. rebuild_hash(work);
  4625. if (stale_work(work, true)) {
  4626. work->stale = true;
  4627. if (opt_submit_stale)
  4628. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  4629. else if (pool->submit_old)
  4630. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  4631. else {
  4632. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  4633. submit_discard_share(work);
  4634. goto out;
  4635. }
  4636. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4637. }
  4638. if (work->stratum) {
  4639. char *s;
  4640. s = malloc(1024);
  4641. sws->s = s;
  4642. } else {
  4643. /* submit solution to bitcoin via JSON-RPC */
  4644. sws->ce = pop_curl_entry2(pool, false);
  4645. if (sws->ce) {
  4646. sws_has_ce(sws);
  4647. } else {
  4648. sws->next = pool->sws_waiting_on_curl;
  4649. pool->sws_waiting_on_curl = sws;
  4650. if (sws->next)
  4651. applog(LOG_DEBUG, "submit_thread queuing submission");
  4652. else
  4653. applog(LOG_WARNING, "submit_thread queuing submissions (see --submit-threads)");
  4654. }
  4655. }
  4656. return sws;
  4657. out:
  4658. free(sws);
  4659. return NULL;
  4660. }
  4661. static bool retry_submission(struct submit_work_state *sws)
  4662. {
  4663. struct work *work = sws->work;
  4664. struct pool *pool = work->pool;
  4665. sws->resubmit = true;
  4666. if ((!work->stale) && stale_work(work, true)) {
  4667. work->stale = true;
  4668. if (opt_submit_stale)
  4669. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as user requested", pool->pool_no);
  4670. else if (pool->submit_old)
  4671. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, will retry as pool requested", pool->pool_no);
  4672. else {
  4673. applog(LOG_NOTICE, "Pool %d share became stale during submission failure, discarding", pool->pool_no);
  4674. submit_discard_share(work);
  4675. return false;
  4676. }
  4677. timer_set_delay_from_now(&sws->tv_staleexpire, 300000000);
  4678. }
  4679. if (unlikely((opt_retries >= 0) && (++sws->failures > opt_retries))) {
  4680. applog(LOG_ERR, "Pool %d failed %d submission retries, discarding", pool->pool_no, opt_retries);
  4681. submit_discard_share(work);
  4682. return false;
  4683. }
  4684. else if (work->stale) {
  4685. if (unlikely(opt_retries < 0 && timer_passed(&sws->tv_staleexpire, NULL)))
  4686. {
  4687. applog(LOG_NOTICE, "Pool %d stale share failed to submit for 5 minutes, discarding", pool->pool_no);
  4688. submit_discard_share(work);
  4689. return false;
  4690. }
  4691. }
  4692. /* pause, then restart work-request loop */
  4693. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  4694. cgtime(&sws->tv_submit);
  4695. json_rpc_call_async(sws->ce->curl, pool->rpc_url, pool->rpc_userpass, sws->s, false, pool, true, sws);
  4696. return true;
  4697. }
  4698. static void free_sws(struct submit_work_state *sws)
  4699. {
  4700. free(sws->s);
  4701. free_work(sws->work);
  4702. free(sws);
  4703. }
  4704. static void *submit_work_thread(__maybe_unused void *userdata)
  4705. {
  4706. int wip = 0;
  4707. CURLM *curlm;
  4708. long curlm_timeout_us = -1;
  4709. struct timeval curlm_timer;
  4710. struct submit_work_state *sws, **swsp;
  4711. struct submit_work_state *write_sws = NULL;
  4712. unsigned tsreduce = 0;
  4713. pthread_detach(pthread_self());
  4714. RenameThread("submit_work");
  4715. applog(LOG_DEBUG, "Creating extra submit work thread");
  4716. curlm = curl_multi_init();
  4717. curlm_timeout_us = -1;
  4718. curl_multi_setopt(curlm, CURLMOPT_TIMERDATA, &curlm_timeout_us);
  4719. curl_multi_setopt(curlm, CURLMOPT_TIMERFUNCTION, my_curl_timer_set);
  4720. fd_set rfds, wfds, efds;
  4721. int maxfd;
  4722. struct timeval tv_timeout, tv_now;
  4723. int n;
  4724. CURLMsg *cm;
  4725. FD_ZERO(&rfds);
  4726. while (1) {
  4727. mutex_lock(&submitting_lock);
  4728. total_submitting -= tsreduce;
  4729. tsreduce = 0;
  4730. if (FD_ISSET(submit_waiting_notifier[0], &rfds)) {
  4731. notifier_read(submit_waiting_notifier);
  4732. }
  4733. // Receive any new submissions
  4734. while (submit_waiting) {
  4735. struct work *work = submit_waiting;
  4736. DL_DELETE(submit_waiting, work);
  4737. if ( (sws = begin_submission(work)) ) {
  4738. if (sws->ce)
  4739. curl_multi_add_handle(curlm, sws->ce->curl);
  4740. else if (sws->s) {
  4741. sws->next = write_sws;
  4742. write_sws = sws;
  4743. }
  4744. ++wip;
  4745. }
  4746. else {
  4747. --total_submitting;
  4748. free_work(work);
  4749. }
  4750. }
  4751. if (unlikely(shutting_down && !wip))
  4752. break;
  4753. mutex_unlock(&submitting_lock);
  4754. FD_ZERO(&rfds);
  4755. FD_ZERO(&wfds);
  4756. FD_ZERO(&efds);
  4757. tv_timeout.tv_sec = -1;
  4758. // Setup cURL with select
  4759. // Need to call perform to ensure the timeout gets updated
  4760. curl_multi_perform(curlm, &n);
  4761. curl_multi_fdset(curlm, &rfds, &wfds, &efds, &maxfd);
  4762. if (curlm_timeout_us >= 0)
  4763. {
  4764. timer_set_delay_from_now(&curlm_timer, curlm_timeout_us);
  4765. reduce_timeout_to(&tv_timeout, &curlm_timer);
  4766. }
  4767. // Setup waiting stratum submissions with select
  4768. for (sws = write_sws; sws; sws = sws->next)
  4769. {
  4770. struct pool *pool = sws->work->pool;
  4771. int fd = pool->sock;
  4772. if (fd == INVSOCK || (!pool->stratum_init) || !pool->stratum_notify)
  4773. continue;
  4774. FD_SET(fd, &wfds);
  4775. set_maxfd(&maxfd, fd);
  4776. }
  4777. // Setup "submit waiting" notifier with select
  4778. FD_SET(submit_waiting_notifier[0], &rfds);
  4779. set_maxfd(&maxfd, submit_waiting_notifier[0]);
  4780. // Wait for something interesting to happen :)
  4781. cgtime(&tv_now);
  4782. if (select(maxfd+1, &rfds, &wfds, &efds, select_timeout(&tv_timeout, &tv_now)) < 0) {
  4783. FD_ZERO(&rfds);
  4784. continue;
  4785. }
  4786. // Handle any stratum ready-to-write results
  4787. for (swsp = &write_sws; (sws = *swsp); ) {
  4788. struct work *work = sws->work;
  4789. struct pool *pool = work->pool;
  4790. int fd = pool->sock;
  4791. bool sessionid_match;
  4792. if (fd == INVSOCK || (!pool->stratum_init) || (!pool->stratum_notify) || !FD_ISSET(fd, &wfds)) {
  4793. next_write_sws:
  4794. // TODO: Check if stale, possibly discard etc
  4795. swsp = &sws->next;
  4796. continue;
  4797. }
  4798. cg_rlock(&pool->data_lock);
  4799. // 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
  4800. // NOTE: Worst case scenario for a false positive: the pool rejects it as H-not-zero
  4801. sessionid_match = (!pool->nonce1) || !strcmp(work->nonce1, pool->nonce1);
  4802. cg_runlock(&pool->data_lock);
  4803. if (!sessionid_match)
  4804. {
  4805. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  4806. submit_discard_share2("disconnect", work);
  4807. ++tsreduce;
  4808. next_write_sws_del:
  4809. // Clear the fd from wfds, to avoid potentially blocking on other submissions to the same socket
  4810. FD_CLR(fd, &wfds);
  4811. // Delete sws for this submission, since we're done with it
  4812. *swsp = sws->next;
  4813. free_sws(sws);
  4814. --wip;
  4815. continue;
  4816. }
  4817. char *s = sws->s;
  4818. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  4819. int sshare_id;
  4820. uint32_t nonce;
  4821. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  4822. char noncehex[9];
  4823. char ntimehex[9];
  4824. sshare->work = copy_work(work);
  4825. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  4826. nonce = *((uint32_t *)(work->data + 76));
  4827. bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  4828. bin2hex(ntimehex, (void *)&work->data[68], 4);
  4829. mutex_lock(&sshare_lock);
  4830. /* Give the stratum share a unique id */
  4831. sshare_id =
  4832. sshare->id = swork_id++;
  4833. HASH_ADD_INT(stratum_shares, id, sshare);
  4834. snprintf(s, 1024, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  4835. pool->rpc_user, work->job_id, nonce2hex, ntimehex, noncehex, sshare->id);
  4836. mutex_unlock(&sshare_lock);
  4837. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  4838. if (likely(stratum_send(pool, s, strlen(s)))) {
  4839. if (pool_tclear(pool, &pool->submit_fail))
  4840. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  4841. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  4842. goto next_write_sws_del;
  4843. } else if (!pool_tset(pool, &pool->submit_fail)) {
  4844. // Undo stuff
  4845. mutex_lock(&sshare_lock);
  4846. // NOTE: Need to find it again in case something else has consumed it already (like the stratum-disconnect resubmitter...)
  4847. HASH_FIND_INT(stratum_shares, &sshare_id, sshare);
  4848. if (sshare)
  4849. HASH_DEL(stratum_shares, sshare);
  4850. mutex_unlock(&sshare_lock);
  4851. if (sshare)
  4852. {
  4853. free_work(sshare->work);
  4854. free(sshare);
  4855. }
  4856. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  4857. total_ro++;
  4858. pool->remotefail_occasions++;
  4859. if (!sshare)
  4860. goto next_write_sws_del;
  4861. goto next_write_sws;
  4862. }
  4863. }
  4864. // Handle any cURL activities
  4865. curl_multi_perform(curlm, &n);
  4866. while( (cm = curl_multi_info_read(curlm, &n)) ) {
  4867. if (cm->msg == CURLMSG_DONE)
  4868. {
  4869. bool finished;
  4870. json_t *val = json_rpc_call_completed(cm->easy_handle, cm->data.result, false, NULL, &sws);
  4871. curl_multi_remove_handle(curlm, cm->easy_handle);
  4872. finished = submit_upstream_work_completed(sws->work, sws->resubmit, &sws->tv_submit, val);
  4873. if (!finished) {
  4874. if (retry_submission(sws))
  4875. curl_multi_add_handle(curlm, sws->ce->curl);
  4876. else
  4877. finished = true;
  4878. }
  4879. if (finished) {
  4880. --wip;
  4881. ++tsreduce;
  4882. struct pool *pool = sws->work->pool;
  4883. if (pool->sws_waiting_on_curl) {
  4884. pool->sws_waiting_on_curl->ce = sws->ce;
  4885. sws_has_ce(pool->sws_waiting_on_curl);
  4886. pool->sws_waiting_on_curl = pool->sws_waiting_on_curl->next;
  4887. curl_multi_add_handle(curlm, sws->ce->curl);
  4888. } else {
  4889. push_curl_entry(sws->ce, sws->work->pool);
  4890. }
  4891. free_sws(sws);
  4892. }
  4893. }
  4894. }
  4895. }
  4896. assert(!write_sws);
  4897. mutex_unlock(&submitting_lock);
  4898. curl_multi_cleanup(curlm);
  4899. applog(LOG_DEBUG, "submit_work thread exiting");
  4900. return NULL;
  4901. }
  4902. /* Find the pool that currently has the highest priority */
  4903. static struct pool *priority_pool(int choice)
  4904. {
  4905. struct pool *ret = NULL;
  4906. int i;
  4907. for (i = 0; i < total_pools; i++) {
  4908. struct pool *pool = pools[i];
  4909. if (pool->prio == choice) {
  4910. ret = pool;
  4911. break;
  4912. }
  4913. }
  4914. if (unlikely(!ret)) {
  4915. applog(LOG_ERR, "WTF No pool %d found!", choice);
  4916. return pools[choice];
  4917. }
  4918. return ret;
  4919. }
  4920. int prioritize_pools(char *param, int *pid)
  4921. {
  4922. char *ptr, *next;
  4923. int i, pr, prio = 0;
  4924. if (total_pools == 0) {
  4925. return MSG_NOPOOL;
  4926. }
  4927. if (param == NULL || *param == '\0') {
  4928. return MSG_MISPID;
  4929. }
  4930. bool pools_changed[total_pools];
  4931. int new_prio[total_pools];
  4932. for (i = 0; i < total_pools; ++i)
  4933. pools_changed[i] = false;
  4934. next = param;
  4935. while (next && *next) {
  4936. ptr = next;
  4937. next = strchr(ptr, ',');
  4938. if (next)
  4939. *(next++) = '\0';
  4940. i = atoi(ptr);
  4941. if (i < 0 || i >= total_pools) {
  4942. *pid = i;
  4943. return MSG_INVPID;
  4944. }
  4945. if (pools_changed[i]) {
  4946. *pid = i;
  4947. return MSG_DUPPID;
  4948. }
  4949. pools_changed[i] = true;
  4950. new_prio[i] = prio++;
  4951. }
  4952. // Only change them if no errors
  4953. for (i = 0; i < total_pools; i++) {
  4954. if (pools_changed[i])
  4955. pools[i]->prio = new_prio[i];
  4956. }
  4957. // In priority order, cycle through the unchanged pools and append them
  4958. for (pr = 0; pr < total_pools; pr++)
  4959. for (i = 0; i < total_pools; i++) {
  4960. if (!pools_changed[i] && pools[i]->prio == pr) {
  4961. pools[i]->prio = prio++;
  4962. pools_changed[i] = true;
  4963. break;
  4964. }
  4965. }
  4966. if (current_pool()->prio)
  4967. switch_pools(NULL);
  4968. return MSG_POOLPRIO;
  4969. }
  4970. void validate_pool_priorities(void)
  4971. {
  4972. // TODO: this should probably do some sort of logging
  4973. int i, j;
  4974. bool used[total_pools];
  4975. bool valid[total_pools];
  4976. for (i = 0; i < total_pools; i++)
  4977. used[i] = valid[i] = false;
  4978. for (i = 0; i < total_pools; i++) {
  4979. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  4980. if (!used[pools[i]->prio]) {
  4981. valid[i] = true;
  4982. used[pools[i]->prio] = true;
  4983. }
  4984. }
  4985. }
  4986. for (i = 0; i < total_pools; i++) {
  4987. if (!valid[i]) {
  4988. for (j = 0; j < total_pools; j++) {
  4989. if (!used[j]) {
  4990. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  4991. pools[i]->prio = j;
  4992. used[j] = true;
  4993. break;
  4994. }
  4995. }
  4996. }
  4997. }
  4998. }
  4999. static void clear_pool_work(struct pool *pool);
  5000. /* Specifies whether we can switch to this pool or not. */
  5001. static bool pool_unusable(struct pool *pool)
  5002. {
  5003. if (pool->idle)
  5004. return true;
  5005. if (pool->enabled != POOL_ENABLED)
  5006. return true;
  5007. return false;
  5008. }
  5009. void switch_pools(struct pool *selected)
  5010. {
  5011. struct pool *pool, *last_pool;
  5012. int i, pool_no, next_pool;
  5013. cg_wlock(&control_lock);
  5014. last_pool = currentpool;
  5015. pool_no = currentpool->pool_no;
  5016. /* Switch selected to pool number 0 and move the rest down */
  5017. if (selected) {
  5018. if (selected->prio != 0) {
  5019. for (i = 0; i < total_pools; i++) {
  5020. pool = pools[i];
  5021. if (pool->prio < selected->prio)
  5022. pool->prio++;
  5023. }
  5024. selected->prio = 0;
  5025. }
  5026. }
  5027. switch (pool_strategy) {
  5028. /* All of these set to the master pool */
  5029. case POOL_BALANCE:
  5030. case POOL_FAILOVER:
  5031. case POOL_LOADBALANCE:
  5032. for (i = 0; i < total_pools; i++) {
  5033. pool = priority_pool(i);
  5034. if (pool_unusable(pool))
  5035. continue;
  5036. pool_no = pool->pool_no;
  5037. break;
  5038. }
  5039. break;
  5040. /* Both of these simply increment and cycle */
  5041. case POOL_ROUNDROBIN:
  5042. case POOL_ROTATE:
  5043. if (selected && !selected->idle) {
  5044. pool_no = selected->pool_no;
  5045. break;
  5046. }
  5047. next_pool = pool_no;
  5048. /* Select the next alive pool */
  5049. for (i = 1; i < total_pools; i++) {
  5050. next_pool++;
  5051. if (next_pool >= total_pools)
  5052. next_pool = 0;
  5053. pool = pools[next_pool];
  5054. if (pool_unusable(pool))
  5055. continue;
  5056. pool_no = next_pool;
  5057. break;
  5058. }
  5059. break;
  5060. default:
  5061. break;
  5062. }
  5063. currentpool = pools[pool_no];
  5064. pool = currentpool;
  5065. cg_wunlock(&control_lock);
  5066. /* Set the lagging flag to avoid pool not providing work fast enough
  5067. * messages in failover only mode since we have to get all fresh work
  5068. * as in restart_threads */
  5069. if (opt_fail_only)
  5070. pool_tset(pool, &pool->lagging);
  5071. if (pool != last_pool)
  5072. {
  5073. pool->block_id = 0;
  5074. if (pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5075. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  5076. if (pool_localgen(pool) || opt_fail_only)
  5077. clear_pool_work(last_pool);
  5078. }
  5079. }
  5080. mutex_lock(&lp_lock);
  5081. pthread_cond_broadcast(&lp_cond);
  5082. mutex_unlock(&lp_lock);
  5083. }
  5084. static void discard_work(struct work *work)
  5085. {
  5086. if (!work->clone && !work->rolls && !work->mined) {
  5087. if (work->pool) {
  5088. work->pool->discarded_work++;
  5089. work->pool->quota_used--;
  5090. work->pool->works--;
  5091. }
  5092. total_discarded++;
  5093. applog(LOG_DEBUG, "Discarded work");
  5094. } else
  5095. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  5096. free_work(work);
  5097. }
  5098. static void wake_gws(void)
  5099. {
  5100. mutex_lock(stgd_lock);
  5101. pthread_cond_signal(&gws_cond);
  5102. mutex_unlock(stgd_lock);
  5103. }
  5104. static void discard_stale(void)
  5105. {
  5106. struct work *work, *tmp;
  5107. int stale = 0;
  5108. mutex_lock(stgd_lock);
  5109. HASH_ITER(hh, staged_work, work, tmp) {
  5110. if (stale_work(work, false)) {
  5111. HASH_DEL(staged_work, work);
  5112. discard_work(work);
  5113. stale++;
  5114. staged_full = false;
  5115. }
  5116. }
  5117. pthread_cond_signal(&gws_cond);
  5118. mutex_unlock(stgd_lock);
  5119. if (stale)
  5120. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  5121. }
  5122. bool stale_work_future(struct work *work, bool share, unsigned long ustime)
  5123. {
  5124. bool rv;
  5125. struct timeval tv, orig;
  5126. ldiv_t d;
  5127. d = ldiv(ustime, 1000000);
  5128. tv = (struct timeval){
  5129. .tv_sec = d.quot,
  5130. .tv_usec = d.rem,
  5131. };
  5132. orig = work->tv_staged;
  5133. timersub(&orig, &tv, &work->tv_staged);
  5134. rv = stale_work(work, share);
  5135. work->tv_staged = orig;
  5136. return rv;
  5137. }
  5138. static void restart_threads(void)
  5139. {
  5140. struct pool *cp = current_pool();
  5141. int i;
  5142. struct thr_info *thr;
  5143. /* Artificially set the lagging flag to avoid pool not providing work
  5144. * fast enough messages after every long poll */
  5145. pool_tset(cp, &cp->lagging);
  5146. /* Discard staged work that is now stale */
  5147. discard_stale();
  5148. rd_lock(&mining_thr_lock);
  5149. for (i = 0; i < mining_threads; i++)
  5150. {
  5151. thr = mining_thr[i];
  5152. thr->work_restart = true;
  5153. }
  5154. for (i = 0; i < mining_threads; i++)
  5155. {
  5156. thr = mining_thr[i];
  5157. notifier_wake(thr->work_restart_notifier);
  5158. }
  5159. rd_unlock(&mining_thr_lock);
  5160. }
  5161. static
  5162. void blkhashstr(char *rv, const unsigned char *hash)
  5163. {
  5164. unsigned char hash_swap[32];
  5165. swap256(hash_swap, hash);
  5166. swap32tole(hash_swap, hash_swap, 32 / 4);
  5167. bin2hex(rv, hash_swap, 32);
  5168. }
  5169. static void set_curblock(char *hexstr, unsigned char *hash)
  5170. {
  5171. unsigned char hash_swap[32];
  5172. current_block_id = ((uint32_t*)hash)[0];
  5173. strcpy(current_block, hexstr);
  5174. swap256(hash_swap, hash);
  5175. swap32tole(hash_swap, hash_swap, 32 / 4);
  5176. cg_wlock(&ch_lock);
  5177. block_time = time(NULL);
  5178. __update_block_title(hash_swap);
  5179. free(current_fullhash);
  5180. current_fullhash = malloc(65);
  5181. bin2hex(current_fullhash, hash_swap, 32);
  5182. get_timestamp(blocktime, sizeof(blocktime), block_time);
  5183. cg_wunlock(&ch_lock);
  5184. applog(LOG_INFO, "New block: %s diff %s (%s)", current_hash, block_diff, net_hashrate);
  5185. }
  5186. /* Search to see if this string is from a block that has been seen before */
  5187. static bool block_exists(char *hexstr)
  5188. {
  5189. struct block *s;
  5190. rd_lock(&blk_lock);
  5191. HASH_FIND_STR(blocks, hexstr, s);
  5192. rd_unlock(&blk_lock);
  5193. if (s)
  5194. return true;
  5195. return false;
  5196. }
  5197. /* Tests if this work is from a block that has been seen before */
  5198. static inline bool from_existing_block(struct work *work)
  5199. {
  5200. char hexstr[37];
  5201. bool ret;
  5202. bin2hex(hexstr, work->data + 8, 18);
  5203. ret = block_exists(hexstr);
  5204. return ret;
  5205. }
  5206. static int block_sort(struct block *blocka, struct block *blockb)
  5207. {
  5208. return blocka->block_no - blockb->block_no;
  5209. }
  5210. static void set_blockdiff(const struct work *work)
  5211. {
  5212. unsigned char target[32];
  5213. double diff;
  5214. uint64_t diff64;
  5215. real_block_target(target, work->data);
  5216. diff = target_diff(target);
  5217. diff64 = diff;
  5218. suffix_string(diff64, block_diff, sizeof(block_diff), 0);
  5219. format_unit2(net_hashrate, sizeof(net_hashrate),
  5220. true, "h/s", H2B_SHORT, diff * 7158278, -1);
  5221. if (unlikely(current_diff != diff))
  5222. applog(LOG_NOTICE, "Network difficulty changed to %s (%s)", block_diff, net_hashrate);
  5223. current_diff = diff;
  5224. }
  5225. static bool test_work_current(struct work *work)
  5226. {
  5227. bool ret = true;
  5228. char hexstr[65];
  5229. if (work->mandatory)
  5230. return ret;
  5231. uint32_t block_id = ((uint32_t*)(work->data))[1];
  5232. /* Hack to work around dud work sneaking into test */
  5233. bin2hex(hexstr, work->data + 8, 18);
  5234. if (!strncmp(hexstr, "000000000000000000000000000000000000", 36))
  5235. goto out_free;
  5236. /* Search to see if this block exists yet and if not, consider it a
  5237. * new block and set the current block details to this one */
  5238. if (!block_exists(hexstr)) {
  5239. struct block *s = calloc(sizeof(struct block), 1);
  5240. int deleted_block = 0;
  5241. ret = false;
  5242. if (unlikely(!s))
  5243. quit (1, "test_work_current OOM");
  5244. strcpy(s->hash, hexstr);
  5245. s->block_no = new_blocks++;
  5246. wr_lock(&blk_lock);
  5247. /* Only keep the last hour's worth of blocks in memory since
  5248. * work from blocks before this is virtually impossible and we
  5249. * want to prevent memory usage from continually rising */
  5250. if (HASH_COUNT(blocks) > 6) {
  5251. struct block *oldblock;
  5252. HASH_SORT(blocks, block_sort);
  5253. oldblock = blocks;
  5254. deleted_block = oldblock->block_no;
  5255. HASH_DEL(blocks, oldblock);
  5256. free(oldblock);
  5257. }
  5258. HASH_ADD_STR(blocks, hash, s);
  5259. set_blockdiff(work);
  5260. wr_unlock(&blk_lock);
  5261. work->pool->block_id = block_id;
  5262. if (deleted_block)
  5263. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  5264. #if BLKMAKER_VERSION > 1
  5265. template_nonce = 0;
  5266. #endif
  5267. set_curblock(hexstr, &work->data[4]);
  5268. if (unlikely(new_blocks == 1))
  5269. goto out_free;
  5270. if (!work->stratum) {
  5271. if (work->longpoll) {
  5272. applog(LOG_NOTICE, "Longpoll from pool %d detected new block",
  5273. work->pool->pool_no);
  5274. } else if (have_longpoll)
  5275. applog(LOG_NOTICE, "New block detected on network before longpoll");
  5276. else
  5277. applog(LOG_NOTICE, "New block detected on network");
  5278. }
  5279. restart_threads();
  5280. } else {
  5281. bool restart = false;
  5282. struct pool *curpool = NULL;
  5283. if (unlikely(work->pool->block_id != block_id)) {
  5284. bool was_active = work->pool->block_id != 0;
  5285. work->pool->block_id = block_id;
  5286. if (!work->longpoll)
  5287. update_last_work(work);
  5288. if (was_active) { // Pool actively changed block
  5289. if (work->pool == (curpool = current_pool()))
  5290. restart = true;
  5291. if (block_id == current_block_id) {
  5292. // Caught up, only announce if this pool is the one in use
  5293. if (restart)
  5294. applog(LOG_NOTICE, "%s %d caught up to new block",
  5295. work->longpoll ? "Longpoll from pool" : "Pool",
  5296. work->pool->pool_no);
  5297. } else {
  5298. // Switched to a block we know, but not the latest... why?
  5299. // This might detect pools trying to double-spend or 51%,
  5300. // but let's not make any accusations until it's had time
  5301. // in the real world.
  5302. blkhashstr(hexstr, &work->data[4]);
  5303. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  5304. work->longpoll ? "Longpoll from pool" : "Pool",
  5305. work->pool->pool_no,
  5306. hexstr);
  5307. }
  5308. }
  5309. }
  5310. if (work->longpoll) {
  5311. ++work->pool->work_restart_id;
  5312. update_last_work(work);
  5313. if ((!restart) && work->pool == current_pool()) {
  5314. applog(
  5315. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  5316. "Longpoll from pool %d requested work update",
  5317. work->pool->pool_no);
  5318. restart = true;
  5319. }
  5320. }
  5321. if (restart)
  5322. restart_threads();
  5323. }
  5324. work->longpoll = false;
  5325. out_free:
  5326. return ret;
  5327. }
  5328. static int tv_sort(struct work *worka, struct work *workb)
  5329. {
  5330. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  5331. }
  5332. static bool work_rollable(struct work *work)
  5333. {
  5334. return (!work->clone && work->rolltime);
  5335. }
  5336. static bool hash_push(struct work *work)
  5337. {
  5338. bool rc = true;
  5339. mutex_lock(stgd_lock);
  5340. if (work_rollable(work))
  5341. staged_rollable++;
  5342. if (likely(!getq->frozen)) {
  5343. HASH_ADD_INT(staged_work, id, work);
  5344. HASH_SORT(staged_work, tv_sort);
  5345. } else
  5346. rc = false;
  5347. pthread_cond_broadcast(&getq->cond);
  5348. mutex_unlock(stgd_lock);
  5349. return rc;
  5350. }
  5351. static void stage_work(struct work *work)
  5352. {
  5353. applog(LOG_DEBUG, "Pushing work %d from pool %d to hash queue",
  5354. work->id, work->pool->pool_no);
  5355. work->work_restart_id = work->pool->work_restart_id;
  5356. work->pool->last_work_time = time(NULL);
  5357. cgtime(&work->pool->tv_last_work_time);
  5358. test_work_current(work);
  5359. work->pool->works++;
  5360. hash_push(work);
  5361. }
  5362. #ifdef HAVE_CURSES
  5363. int curses_int(const char *query)
  5364. {
  5365. int ret;
  5366. char *cvar;
  5367. cvar = curses_input(query);
  5368. if (unlikely(!cvar))
  5369. return -1;
  5370. ret = atoi(cvar);
  5371. free(cvar);
  5372. return ret;
  5373. }
  5374. #endif
  5375. #ifdef HAVE_CURSES
  5376. static bool input_pool(bool live);
  5377. #endif
  5378. #ifdef HAVE_CURSES
  5379. static void display_pool_summary(struct pool *pool)
  5380. {
  5381. double efficiency = 0.0;
  5382. char xfer[17], bw[19];
  5383. int pool_secs;
  5384. if (curses_active_locked()) {
  5385. wlog("Pool: %s\n", pool->rpc_url);
  5386. if (pool->solved)
  5387. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  5388. if (!pool->has_stratum)
  5389. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  5390. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  5391. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  5392. wlog(" Accepted shares: %d\n", pool->accepted);
  5393. wlog(" Rejected shares: %d + %d stale (%.2f%%)\n",
  5394. pool->rejected, pool->stale_shares,
  5395. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  5396. );
  5397. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  5398. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  5399. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  5400. wlog(" Network transfer: %s (%s)\n",
  5401. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  5402. (float)pool->cgminer_pool_stats.net_bytes_received,
  5403. (float)pool->cgminer_pool_stats.net_bytes_sent),
  5404. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  5405. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  5406. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  5407. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  5408. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  5409. wlog(" Efficiency (accepted * difficulty / 2 KB): %.2f\n", efficiency);
  5410. wlog(" Items worked on: %d\n", pool->works);
  5411. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  5412. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  5413. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  5414. unlock_curses();
  5415. }
  5416. }
  5417. #endif
  5418. /* We can't remove the memory used for this struct pool because there may
  5419. * still be work referencing it. We just remove it from the pools list */
  5420. void remove_pool(struct pool *pool)
  5421. {
  5422. int i, last_pool = total_pools - 1;
  5423. struct pool *other;
  5424. /* Boost priority of any lower prio than this one */
  5425. for (i = 0; i < total_pools; i++) {
  5426. other = pools[i];
  5427. if (other->prio > pool->prio)
  5428. other->prio--;
  5429. }
  5430. if (pool->pool_no < last_pool) {
  5431. /* Swap the last pool for this one */
  5432. (pools[last_pool])->pool_no = pool->pool_no;
  5433. pools[pool->pool_no] = pools[last_pool];
  5434. }
  5435. /* Give it an invalid number */
  5436. pool->pool_no = total_pools;
  5437. pool->removed = true;
  5438. pool->has_stratum = false;
  5439. total_pools--;
  5440. }
  5441. /* add a mutex if this needs to be thread safe in the future */
  5442. static struct JE {
  5443. char *buf;
  5444. struct JE *next;
  5445. } *jedata = NULL;
  5446. static void json_escape_free()
  5447. {
  5448. struct JE *jeptr = jedata;
  5449. struct JE *jenext;
  5450. jedata = NULL;
  5451. while (jeptr) {
  5452. jenext = jeptr->next;
  5453. free(jeptr->buf);
  5454. free(jeptr);
  5455. jeptr = jenext;
  5456. }
  5457. }
  5458. static
  5459. char *json_escape(const char *str)
  5460. {
  5461. struct JE *jeptr;
  5462. char *buf, *ptr;
  5463. /* 2x is the max, may as well just allocate that */
  5464. ptr = buf = malloc(strlen(str) * 2 + 1);
  5465. jeptr = malloc(sizeof(*jeptr));
  5466. jeptr->buf = buf;
  5467. jeptr->next = jedata;
  5468. jedata = jeptr;
  5469. while (*str) {
  5470. if (*str == '\\' || *str == '"')
  5471. *(ptr++) = '\\';
  5472. *(ptr++) = *(str++);
  5473. }
  5474. *ptr = '\0';
  5475. return buf;
  5476. }
  5477. void _write_config_temps(FILE *fcfg, const char *configname, size_t settingoffset, size_t defoffset)
  5478. {
  5479. int i, commas;
  5480. int *setp, allset;
  5481. uint8_t *defp;
  5482. for (i = 0; ; ++i)
  5483. {
  5484. if (i == total_devices)
  5485. // All defaults
  5486. return;
  5487. setp = ((void*)devices[i]) + settingoffset;
  5488. defp = ((void*)devices[i]) + defoffset;
  5489. allset = *setp;
  5490. if (*setp != *defp)
  5491. break;
  5492. }
  5493. fprintf(fcfg, ",\n\"%s\" : \"", configname);
  5494. for (i = 1; ; ++i)
  5495. {
  5496. if (i == total_devices)
  5497. {
  5498. // All the same
  5499. fprintf(fcfg, "%d\"", allset);
  5500. return;
  5501. }
  5502. setp = ((void*)devices[i]) + settingoffset;
  5503. if (allset != *setp)
  5504. break;
  5505. }
  5506. commas = 0;
  5507. for (i = 0; i < total_devices; ++i)
  5508. {
  5509. setp = ((void*)devices[i]) + settingoffset;
  5510. defp = ((void*)devices[i]) + defoffset;
  5511. if (*setp != *defp)
  5512. {
  5513. for ( ; commas; --commas)
  5514. fputs(",", fcfg);
  5515. fprintf(fcfg, "%d", *setp);
  5516. }
  5517. ++commas;
  5518. }
  5519. fputs("\"", fcfg);
  5520. }
  5521. #define write_config_temps(fcfg, configname, settingname) \
  5522. _write_config_temps(fcfg, configname, offsetof(struct cgpu_info, settingname), offsetof(struct cgpu_info, settingname ## _default))
  5523. static
  5524. void _write_config_string_elist(FILE *fcfg, const char *configname, struct string_elist * const elist)
  5525. {
  5526. if (!elist)
  5527. return;
  5528. static struct string_elist *entry;
  5529. fprintf(fcfg, ",\n\"%s\" : [", configname);
  5530. bool first = true;
  5531. DL_FOREACH(elist, entry)
  5532. {
  5533. const char * const s = entry->string;
  5534. fprintf(fcfg, "%s\n\t\"%s\"", first ? "" : ",", json_escape(s));
  5535. first = false;
  5536. }
  5537. fprintf(fcfg, "\n]");
  5538. }
  5539. void write_config(FILE *fcfg)
  5540. {
  5541. int i;
  5542. /* Write pool values */
  5543. fputs("{\n\"pools\" : [", fcfg);
  5544. for(i = 0; i < total_pools; i++) {
  5545. struct pool *pool = pools[i];
  5546. if (pool->quota != 1) {
  5547. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%d;%s\",", i > 0 ? "," : "",
  5548. pool->quota,
  5549. json_escape(pool->rpc_url));
  5550. } else {
  5551. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "",
  5552. json_escape(pool->rpc_url));
  5553. }
  5554. if (pool->rpc_proxy)
  5555. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pool->rpc_proxy));
  5556. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  5557. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pool->rpc_pass));
  5558. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"", pool->prio);
  5559. if (pool->force_rollntime)
  5560. fprintf(fcfg, ",\n\t\t\"force-rollntime\" : %d", pool->force_rollntime);
  5561. fprintf(fcfg, "\n\t}");
  5562. }
  5563. fputs("\n]\n", fcfg);
  5564. write_config_temps(fcfg, "temp-cutoff", cutofftemp);
  5565. write_config_temps(fcfg, "temp-target", targettemp);
  5566. #ifdef HAVE_OPENCL
  5567. if (nDevs) {
  5568. /* Write GPU device values */
  5569. fputs(",\n\"intensity\" : \"", fcfg);
  5570. for(i = 0; i < nDevs; i++)
  5571. {
  5572. if (i > 0)
  5573. fputc(',', fcfg);
  5574. if (gpus[i].dynamic)
  5575. fputc('d', fcfg);
  5576. else
  5577. fprintf(fcfg, "%d", gpus[i].intensity);
  5578. }
  5579. fputs("\",\n\"vectors\" : \"", fcfg);
  5580. for(i = 0; i < nDevs; i++)
  5581. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5582. gpus[i].vwidth);
  5583. fputs("\",\n\"worksize\" : \"", fcfg);
  5584. for(i = 0; i < nDevs; i++)
  5585. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5586. (int)gpus[i].work_size);
  5587. fputs("\",\n\"kernel\" : \"", fcfg);
  5588. for(i = 0; i < nDevs; i++) {
  5589. fprintf(fcfg, "%s", i > 0 ? "," : "");
  5590. switch (gpus[i].kernel) {
  5591. case KL_NONE: // Shouldn't happen
  5592. break;
  5593. case KL_POCLBM:
  5594. fprintf(fcfg, "poclbm");
  5595. break;
  5596. case KL_PHATK:
  5597. fprintf(fcfg, "phatk");
  5598. break;
  5599. case KL_DIAKGCN:
  5600. fprintf(fcfg, "diakgcn");
  5601. break;
  5602. case KL_DIABLO:
  5603. fprintf(fcfg, "diablo");
  5604. break;
  5605. case KL_SCRYPT:
  5606. fprintf(fcfg, "scrypt");
  5607. break;
  5608. }
  5609. }
  5610. #ifdef USE_SCRYPT
  5611. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  5612. for(i = 0; i < nDevs; i++)
  5613. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5614. (int)gpus[i].opt_lg);
  5615. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  5616. for(i = 0; i < nDevs; i++)
  5617. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5618. (int)gpus[i].opt_tc);
  5619. fputs("\",\n\"shaders\" : \"", fcfg);
  5620. for(i = 0; i < nDevs; i++)
  5621. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  5622. (int)gpus[i].shaders);
  5623. #endif
  5624. #ifdef HAVE_ADL
  5625. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  5626. for(i = 0; i < nDevs; i++)
  5627. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  5628. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  5629. for(i = 0; i < nDevs; i++)
  5630. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  5631. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  5632. for(i = 0; i < nDevs; i++)
  5633. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  5634. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  5635. for(i = 0; i < nDevs; i++)
  5636. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  5637. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  5638. for(i = 0; i < nDevs; i++)
  5639. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  5640. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  5641. for(i = 0; i < nDevs; i++)
  5642. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  5643. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  5644. for(i = 0; i < nDevs; i++)
  5645. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  5646. #endif
  5647. fputs("\"", fcfg);
  5648. }
  5649. #endif
  5650. #ifdef HAVE_ADL
  5651. if (opt_reorder)
  5652. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  5653. #endif
  5654. #ifdef WANT_CPUMINE
  5655. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  5656. #endif
  5657. /* Simple bool and int options */
  5658. struct opt_table *opt;
  5659. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  5660. char *p, *name = strdup(opt->names);
  5661. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  5662. if (p[1] != '-')
  5663. continue;
  5664. if (opt->type & OPT_NOARG &&
  5665. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  5666. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  5667. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  5668. if (opt->type & OPT_HASARG &&
  5669. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  5670. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  5671. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  5672. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  5673. opt->desc != opt_hidden &&
  5674. 0 <= *(int *)opt->u.arg)
  5675. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  5676. }
  5677. }
  5678. /* Special case options */
  5679. if (request_target_str)
  5680. {
  5681. if (request_pdiff == (long)request_pdiff)
  5682. fprintf(fcfg, ",\n\"request-diff\" : %ld", (long)request_pdiff);
  5683. else
  5684. fprintf(fcfg, ",\n\"request-diff\" : %f", request_pdiff);
  5685. }
  5686. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  5687. if (pool_strategy == POOL_BALANCE)
  5688. fputs(",\n\"balance\" : true", fcfg);
  5689. if (pool_strategy == POOL_LOADBALANCE)
  5690. fputs(",\n\"load-balance\" : true", fcfg);
  5691. if (pool_strategy == POOL_ROUNDROBIN)
  5692. fputs(",\n\"round-robin\" : true", fcfg);
  5693. if (pool_strategy == POOL_ROTATE)
  5694. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  5695. #if defined(unix) || defined(__APPLE__)
  5696. if (opt_stderr_cmd && *opt_stderr_cmd)
  5697. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  5698. #endif // defined(unix)
  5699. if (opt_kernel_path && *opt_kernel_path) {
  5700. char *kpath = strdup(opt_kernel_path);
  5701. if (kpath[strlen(kpath)-1] == '/')
  5702. kpath[strlen(kpath)-1] = 0;
  5703. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  5704. free(kpath);
  5705. }
  5706. if (schedstart.enable)
  5707. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5708. if (schedstop.enable)
  5709. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5710. if (opt_socks_proxy && *opt_socks_proxy)
  5711. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  5712. _write_config_string_elist(fcfg, "scan", scan_devices);
  5713. _write_config_string_elist(fcfg, "device", opt_devices_enabled_list);
  5714. _write_config_string_elist(fcfg, "set-device", opt_set_device_list);
  5715. if (opt_api_allow)
  5716. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  5717. if (strcmp(opt_api_mcast_addr, API_MCAST_ADDR) != 0)
  5718. fprintf(fcfg, ",\n\"api-mcast-addr\" : \"%s\"", json_escape(opt_api_mcast_addr));
  5719. if (strcmp(opt_api_mcast_code, API_MCAST_CODE) != 0)
  5720. fprintf(fcfg, ",\n\"api-mcast-code\" : \"%s\"", json_escape(opt_api_mcast_code));
  5721. if (*opt_api_mcast_des)
  5722. fprintf(fcfg, ",\n\"api-mcast-des\" : \"%s\"", json_escape(opt_api_mcast_des));
  5723. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  5724. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  5725. if (opt_api_groups)
  5726. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  5727. if (opt_icarus_options)
  5728. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  5729. if (opt_icarus_timing)
  5730. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  5731. #ifdef USE_KLONDIKE
  5732. if (opt_klondike_options)
  5733. fprintf(fcfg, ",\n\"klondike-options\" : \"%s\"", json_escape(opt_klondike_options));
  5734. #endif
  5735. fputs("\n}\n", fcfg);
  5736. json_escape_free();
  5737. }
  5738. void zero_bestshare(void)
  5739. {
  5740. int i;
  5741. best_diff = 0;
  5742. memset(best_share, 0, 8);
  5743. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  5744. for (i = 0; i < total_pools; i++) {
  5745. struct pool *pool = pools[i];
  5746. pool->best_diff = 0;
  5747. }
  5748. }
  5749. void zero_stats(void)
  5750. {
  5751. int i;
  5752. applog(LOG_DEBUG, "Zeroing stats");
  5753. cgtime(&total_tv_start);
  5754. miner_started = total_tv_start;
  5755. total_rolling = 0;
  5756. total_mhashes_done = 0;
  5757. total_getworks = 0;
  5758. total_accepted = 0;
  5759. total_rejected = 0;
  5760. hw_errors = 0;
  5761. total_stale = 0;
  5762. total_discarded = 0;
  5763. total_bytes_rcvd = total_bytes_sent = 0;
  5764. new_blocks = 0;
  5765. local_work = 0;
  5766. total_go = 0;
  5767. total_ro = 0;
  5768. total_secs = 1.0;
  5769. total_diff1 = 0;
  5770. total_bad_nonces = 0;
  5771. found_blocks = 0;
  5772. total_diff_accepted = 0;
  5773. total_diff_rejected = 0;
  5774. total_diff_stale = 0;
  5775. #ifdef HAVE_CURSES
  5776. awidth = rwidth = swidth = hwwidth = 1;
  5777. #endif
  5778. for (i = 0; i < total_pools; i++) {
  5779. struct pool *pool = pools[i];
  5780. pool->getwork_requested = 0;
  5781. pool->accepted = 0;
  5782. pool->rejected = 0;
  5783. pool->solved = 0;
  5784. pool->getwork_requested = 0;
  5785. pool->stale_shares = 0;
  5786. pool->discarded_work = 0;
  5787. pool->getfail_occasions = 0;
  5788. pool->remotefail_occasions = 0;
  5789. pool->last_share_time = 0;
  5790. pool->diff1 = 0;
  5791. pool->diff_accepted = 0;
  5792. pool->diff_rejected = 0;
  5793. pool->diff_stale = 0;
  5794. pool->last_share_diff = 0;
  5795. pool->cgminer_stats.start_tv = total_tv_start;
  5796. pool->cgminer_stats.getwork_calls = 0;
  5797. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5798. pool->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5799. pool->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5800. pool->cgminer_pool_stats.getwork_calls = 0;
  5801. pool->cgminer_pool_stats.getwork_attempts = 0;
  5802. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5803. pool->cgminer_pool_stats.getwork_wait_max.tv_sec = 0;
  5804. pool->cgminer_pool_stats.getwork_wait_max.tv_usec = 0;
  5805. pool->cgminer_pool_stats.min_diff = 0;
  5806. pool->cgminer_pool_stats.max_diff = 0;
  5807. pool->cgminer_pool_stats.min_diff_count = 0;
  5808. pool->cgminer_pool_stats.max_diff_count = 0;
  5809. pool->cgminer_pool_stats.times_sent = 0;
  5810. pool->cgminer_pool_stats.bytes_sent = 0;
  5811. pool->cgminer_pool_stats.net_bytes_sent = 0;
  5812. pool->cgminer_pool_stats.times_received = 0;
  5813. pool->cgminer_pool_stats.bytes_received = 0;
  5814. pool->cgminer_pool_stats.net_bytes_received = 0;
  5815. }
  5816. zero_bestshare();
  5817. for (i = 0; i < total_devices; ++i) {
  5818. struct cgpu_info *cgpu = get_devices(i);
  5819. mutex_lock(&hash_lock);
  5820. cgpu->total_mhashes = 0;
  5821. cgpu->accepted = 0;
  5822. cgpu->rejected = 0;
  5823. cgpu->stale = 0;
  5824. cgpu->hw_errors = 0;
  5825. cgpu->utility = 0.0;
  5826. cgpu->utility_diff1 = 0;
  5827. cgpu->last_share_pool_time = 0;
  5828. cgpu->bad_nonces = 0;
  5829. cgpu->diff1 = 0;
  5830. cgpu->diff_accepted = 0;
  5831. cgpu->diff_rejected = 0;
  5832. cgpu->diff_stale = 0;
  5833. cgpu->last_share_diff = 0;
  5834. cgpu->thread_fail_init_count = 0;
  5835. cgpu->thread_zero_hash_count = 0;
  5836. cgpu->thread_fail_queue_count = 0;
  5837. cgpu->dev_sick_idle_60_count = 0;
  5838. cgpu->dev_dead_idle_600_count = 0;
  5839. cgpu->dev_nostart_count = 0;
  5840. cgpu->dev_over_heat_count = 0;
  5841. cgpu->dev_thermal_cutoff_count = 0;
  5842. cgpu->dev_comms_error_count = 0;
  5843. cgpu->dev_throttle_count = 0;
  5844. cgpu->cgminer_stats.start_tv = total_tv_start;
  5845. cgpu->cgminer_stats.getwork_calls = 0;
  5846. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5847. cgpu->cgminer_stats.getwork_wait_max.tv_sec = 0;
  5848. cgpu->cgminer_stats.getwork_wait_max.tv_usec = 0;
  5849. mutex_unlock(&hash_lock);
  5850. }
  5851. }
  5852. #ifdef HAVE_CURSES
  5853. static void display_pools(void)
  5854. {
  5855. struct pool *pool;
  5856. int selected, i, j;
  5857. char input;
  5858. opt_loginput = true;
  5859. immedok(logwin, true);
  5860. clear_logwin();
  5861. updated:
  5862. for (j = 0; j < total_pools; j++) {
  5863. for (i = 0; i < total_pools; i++) {
  5864. pool = pools[i];
  5865. if (pool->prio != j)
  5866. continue;
  5867. if (pool == current_pool())
  5868. wattron(logwin, A_BOLD);
  5869. if (pool->enabled != POOL_ENABLED)
  5870. wattron(logwin, A_DIM);
  5871. wlogprint("%d: ", pool->prio);
  5872. switch (pool->enabled) {
  5873. case POOL_ENABLED:
  5874. wlogprint("Enabled ");
  5875. break;
  5876. case POOL_DISABLED:
  5877. wlogprint("Disabled ");
  5878. break;
  5879. case POOL_REJECTING:
  5880. wlogprint("Rejectin ");
  5881. break;
  5882. }
  5883. if (pool->idle)
  5884. wlogprint("Dead ");
  5885. else
  5886. if (pool->has_stratum)
  5887. wlogprint("Strtm");
  5888. else
  5889. if (pool->lp_url && pool->proto != pool->lp_proto)
  5890. wlogprint("Mixed");
  5891. else
  5892. switch (pool->proto) {
  5893. case PLP_GETBLOCKTEMPLATE:
  5894. wlogprint(" GBT ");
  5895. break;
  5896. case PLP_GETWORK:
  5897. wlogprint("GWork");
  5898. break;
  5899. default:
  5900. wlogprint("Alive");
  5901. }
  5902. wlogprint(" Quota %d Pool %d: %s User:%s\n",
  5903. pool->quota,
  5904. pool->pool_no,
  5905. pool->rpc_url, pool->rpc_user);
  5906. wattroff(logwin, A_BOLD | A_DIM);
  5907. break; //for (i = 0; i < total_pools; i++)
  5908. }
  5909. }
  5910. retry:
  5911. wlogprint("\nCurrent pool management strategy: %s\n",
  5912. strategies[pool_strategy].s);
  5913. if (pool_strategy == POOL_ROTATE)
  5914. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  5915. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  5916. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [P]rioritize [Q]uota change\n");
  5917. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  5918. wlogprint("Or press any other key to continue\n");
  5919. logwin_update();
  5920. input = getch();
  5921. if (!strncasecmp(&input, "a", 1)) {
  5922. input_pool(true);
  5923. goto updated;
  5924. } else if (!strncasecmp(&input, "r", 1)) {
  5925. if (total_pools <= 1) {
  5926. wlogprint("Cannot remove last pool");
  5927. goto retry;
  5928. }
  5929. selected = curses_int("Select pool number");
  5930. if (selected < 0 || selected >= total_pools) {
  5931. wlogprint("Invalid selection\n");
  5932. goto retry;
  5933. }
  5934. pool = pools[selected];
  5935. if (pool == current_pool())
  5936. switch_pools(NULL);
  5937. if (pool == current_pool()) {
  5938. wlogprint("Unable to remove pool due to activity\n");
  5939. goto retry;
  5940. }
  5941. disable_pool(pool);
  5942. remove_pool(pool);
  5943. goto updated;
  5944. } else if (!strncasecmp(&input, "s", 1)) {
  5945. selected = curses_int("Select pool number");
  5946. if (selected < 0 || selected >= total_pools) {
  5947. wlogprint("Invalid selection\n");
  5948. goto retry;
  5949. }
  5950. pool = pools[selected];
  5951. enable_pool(pool);
  5952. switch_pools(pool);
  5953. goto updated;
  5954. } else if (!strncasecmp(&input, "d", 1)) {
  5955. if (enabled_pools <= 1) {
  5956. wlogprint("Cannot disable last pool");
  5957. goto retry;
  5958. }
  5959. selected = curses_int("Select pool number");
  5960. if (selected < 0 || selected >= total_pools) {
  5961. wlogprint("Invalid selection\n");
  5962. goto retry;
  5963. }
  5964. pool = pools[selected];
  5965. disable_pool(pool);
  5966. if (pool == current_pool())
  5967. switch_pools(NULL);
  5968. goto updated;
  5969. } else if (!strncasecmp(&input, "e", 1)) {
  5970. selected = curses_int("Select pool number");
  5971. if (selected < 0 || selected >= total_pools) {
  5972. wlogprint("Invalid selection\n");
  5973. goto retry;
  5974. }
  5975. pool = pools[selected];
  5976. enable_pool(pool);
  5977. if (pool->prio < current_pool()->prio)
  5978. switch_pools(pool);
  5979. goto updated;
  5980. } else if (!strncasecmp(&input, "c", 1)) {
  5981. for (i = 0; i <= TOP_STRATEGY; i++)
  5982. wlogprint("%d: %s\n", i, strategies[i].s);
  5983. selected = curses_int("Select strategy number type");
  5984. if (selected < 0 || selected > TOP_STRATEGY) {
  5985. wlogprint("Invalid selection\n");
  5986. goto retry;
  5987. }
  5988. if (selected == POOL_ROTATE) {
  5989. opt_rotate_period = curses_int("Select interval in minutes");
  5990. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  5991. opt_rotate_period = 0;
  5992. wlogprint("Invalid selection\n");
  5993. goto retry;
  5994. }
  5995. }
  5996. pool_strategy = selected;
  5997. switch_pools(NULL);
  5998. goto updated;
  5999. } else if (!strncasecmp(&input, "i", 1)) {
  6000. selected = curses_int("Select pool number");
  6001. if (selected < 0 || selected >= total_pools) {
  6002. wlogprint("Invalid selection\n");
  6003. goto retry;
  6004. }
  6005. pool = pools[selected];
  6006. display_pool_summary(pool);
  6007. goto retry;
  6008. } else if (!strncasecmp(&input, "q", 1)) {
  6009. selected = curses_int("Select pool number");
  6010. if (selected < 0 || selected >= total_pools) {
  6011. wlogprint("Invalid selection\n");
  6012. goto retry;
  6013. }
  6014. pool = pools[selected];
  6015. selected = curses_int("Set quota");
  6016. if (selected < 0) {
  6017. wlogprint("Invalid negative quota\n");
  6018. goto retry;
  6019. }
  6020. pool->quota = selected;
  6021. adjust_quota_gcd();
  6022. goto updated;
  6023. } else if (!strncasecmp(&input, "f", 1)) {
  6024. opt_fail_only ^= true;
  6025. goto updated;
  6026. } else if (!strncasecmp(&input, "p", 1)) {
  6027. char *prilist = curses_input("Enter new pool priority (comma separated list)");
  6028. if (!prilist)
  6029. {
  6030. wlogprint("Not changing priorities\n");
  6031. goto retry;
  6032. }
  6033. int res = prioritize_pools(prilist, &i);
  6034. free(prilist);
  6035. switch (res) {
  6036. case MSG_NOPOOL:
  6037. wlogprint("No pools\n");
  6038. goto retry;
  6039. case MSG_MISPID:
  6040. wlogprint("Missing pool id parameter\n");
  6041. goto retry;
  6042. case MSG_INVPID:
  6043. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  6044. goto retry;
  6045. case MSG_DUPPID:
  6046. wlogprint("Duplicate pool specified %d\n", i);
  6047. goto retry;
  6048. case MSG_POOLPRIO:
  6049. default:
  6050. goto updated;
  6051. }
  6052. } else
  6053. clear_logwin();
  6054. immedok(logwin, false);
  6055. opt_loginput = false;
  6056. }
  6057. static const char *summary_detail_level_str(void)
  6058. {
  6059. if (opt_compact)
  6060. return "compact";
  6061. if (opt_show_procs)
  6062. return "processors";
  6063. return "devices";
  6064. }
  6065. static void display_options(void)
  6066. {
  6067. int selected;
  6068. char input;
  6069. opt_loginput = true;
  6070. immedok(logwin, true);
  6071. retry:
  6072. clear_logwin();
  6073. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  6074. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  6075. "[R]PC debug:%s\n[W]orkTime details:%s\nsu[M]mary detail level:%s\n"
  6076. "[L]og interval:%d\n[Z]ero statistics\n",
  6077. opt_debug_console ? "on" : "off",
  6078. want_per_device_stats? "on" : "off",
  6079. opt_quiet ? "on" : "off",
  6080. opt_log_output ? "on" : "off",
  6081. opt_protocol ? "on" : "off",
  6082. opt_worktime ? "on" : "off",
  6083. summary_detail_level_str(),
  6084. opt_log_interval);
  6085. wlogprint("Select an option or any other key to return\n");
  6086. logwin_update();
  6087. input = getch();
  6088. if (!strncasecmp(&input, "q", 1)) {
  6089. opt_quiet ^= true;
  6090. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  6091. goto retry;
  6092. } else if (!strncasecmp(&input, "v", 1)) {
  6093. opt_log_output ^= true;
  6094. if (opt_log_output)
  6095. opt_quiet = false;
  6096. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  6097. goto retry;
  6098. } else if (!strncasecmp(&input, "n", 1)) {
  6099. opt_log_output = false;
  6100. opt_debug_console = false;
  6101. opt_quiet = false;
  6102. opt_protocol = false;
  6103. opt_compact = false;
  6104. opt_show_procs = false;
  6105. devsummaryYOffset = 0;
  6106. want_per_device_stats = false;
  6107. wlogprint("Output mode reset to normal\n");
  6108. switch_logsize();
  6109. goto retry;
  6110. } else if (!strncasecmp(&input, "d", 1)) {
  6111. opt_debug = true;
  6112. opt_debug_console ^= true;
  6113. opt_log_output = opt_debug_console;
  6114. if (opt_debug_console)
  6115. opt_quiet = false;
  6116. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  6117. goto retry;
  6118. } else if (!strncasecmp(&input, "m", 1)) {
  6119. if (opt_compact)
  6120. opt_compact = false;
  6121. else
  6122. if (!opt_show_procs)
  6123. opt_show_procs = true;
  6124. else
  6125. {
  6126. opt_compact = true;
  6127. opt_show_procs = false;
  6128. devsummaryYOffset = 0;
  6129. }
  6130. wlogprint("su[M]mary detail level changed to: %s\n", summary_detail_level_str());
  6131. switch_logsize();
  6132. goto retry;
  6133. } else if (!strncasecmp(&input, "p", 1)) {
  6134. want_per_device_stats ^= true;
  6135. opt_log_output = want_per_device_stats;
  6136. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  6137. goto retry;
  6138. } else if (!strncasecmp(&input, "r", 1)) {
  6139. opt_protocol ^= true;
  6140. if (opt_protocol)
  6141. opt_quiet = false;
  6142. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  6143. goto retry;
  6144. } else if (!strncasecmp(&input, "c", 1))
  6145. clear_logwin();
  6146. else if (!strncasecmp(&input, "l", 1)) {
  6147. selected = curses_int("Interval in seconds");
  6148. if (selected < 0 || selected > 9999) {
  6149. wlogprint("Invalid selection\n");
  6150. goto retry;
  6151. }
  6152. opt_log_interval = selected;
  6153. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  6154. goto retry;
  6155. } else if (!strncasecmp(&input, "s", 1)) {
  6156. opt_realquiet = true;
  6157. } else if (!strncasecmp(&input, "w", 1)) {
  6158. opt_worktime ^= true;
  6159. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  6160. goto retry;
  6161. } else if (!strncasecmp(&input, "z", 1)) {
  6162. zero_stats();
  6163. goto retry;
  6164. } else
  6165. clear_logwin();
  6166. immedok(logwin, false);
  6167. opt_loginput = false;
  6168. }
  6169. #endif
  6170. void default_save_file(char *filename)
  6171. {
  6172. #if defined(unix) || defined(__APPLE__)
  6173. if (getenv("HOME") && *getenv("HOME")) {
  6174. strcpy(filename, getenv("HOME"));
  6175. strcat(filename, "/");
  6176. }
  6177. else
  6178. strcpy(filename, "");
  6179. strcat(filename, ".bfgminer/");
  6180. mkdir(filename, 0777);
  6181. #else
  6182. strcpy(filename, "");
  6183. #endif
  6184. strcat(filename, def_conf);
  6185. }
  6186. #ifdef HAVE_CURSES
  6187. static void set_options(void)
  6188. {
  6189. int selected;
  6190. char input;
  6191. opt_loginput = true;
  6192. immedok(logwin, true);
  6193. clear_logwin();
  6194. retry:
  6195. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  6196. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  6197. "[W]rite config file\n[B]FGMiner restart\n",
  6198. opt_queue, opt_scantime, opt_expiry, opt_retries);
  6199. wlogprint("Select an option or any other key to return\n");
  6200. logwin_update();
  6201. input = getch();
  6202. if (!strncasecmp(&input, "q", 1)) {
  6203. selected = curses_int("Extra work items to queue");
  6204. if (selected < 0 || selected > 9999) {
  6205. wlogprint("Invalid selection\n");
  6206. goto retry;
  6207. }
  6208. opt_queue = selected;
  6209. goto retry;
  6210. } else if (!strncasecmp(&input, "l", 1)) {
  6211. if (want_longpoll)
  6212. stop_longpoll();
  6213. else
  6214. start_longpoll();
  6215. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  6216. goto retry;
  6217. } else if (!strncasecmp(&input, "s", 1)) {
  6218. selected = curses_int("Set scantime in seconds");
  6219. if (selected < 0 || selected > 9999) {
  6220. wlogprint("Invalid selection\n");
  6221. goto retry;
  6222. }
  6223. opt_scantime = selected;
  6224. goto retry;
  6225. } else if (!strncasecmp(&input, "e", 1)) {
  6226. selected = curses_int("Set expiry time in seconds");
  6227. if (selected < 0 || selected > 9999) {
  6228. wlogprint("Invalid selection\n");
  6229. goto retry;
  6230. }
  6231. opt_expiry = selected;
  6232. goto retry;
  6233. } else if (!strncasecmp(&input, "r", 1)) {
  6234. selected = curses_int("Retries before failing (-1 infinite)");
  6235. if (selected < -1 || selected > 9999) {
  6236. wlogprint("Invalid selection\n");
  6237. goto retry;
  6238. }
  6239. opt_retries = selected;
  6240. goto retry;
  6241. } else if (!strncasecmp(&input, "w", 1)) {
  6242. FILE *fcfg;
  6243. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  6244. default_save_file(filename);
  6245. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  6246. str = curses_input(prompt);
  6247. if (str) {
  6248. struct stat statbuf;
  6249. strcpy(filename, str);
  6250. free(str);
  6251. if (!stat(filename, &statbuf)) {
  6252. wlogprint("File exists, overwrite?\n");
  6253. input = getch();
  6254. if (strncasecmp(&input, "y", 1))
  6255. goto retry;
  6256. }
  6257. }
  6258. fcfg = fopen(filename, "w");
  6259. if (!fcfg) {
  6260. wlogprint("Cannot open or create file\n");
  6261. goto retry;
  6262. }
  6263. write_config(fcfg);
  6264. fclose(fcfg);
  6265. goto retry;
  6266. } else if (!strncasecmp(&input, "b", 1)) {
  6267. wlogprint("Are you sure?\n");
  6268. input = getch();
  6269. if (!strncasecmp(&input, "y", 1))
  6270. app_restart();
  6271. else
  6272. clear_logwin();
  6273. } else
  6274. clear_logwin();
  6275. immedok(logwin, false);
  6276. opt_loginput = false;
  6277. }
  6278. int scan_serial(const char *);
  6279. static
  6280. void _managetui_msg(const char *repr, const char **msg)
  6281. {
  6282. if (*msg)
  6283. {
  6284. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": %s", repr, *msg);
  6285. wattron(logwin, A_BOLD);
  6286. wlogprint("%s", *msg);
  6287. wattroff(logwin, A_BOLD);
  6288. *msg = NULL;
  6289. }
  6290. logwin_update();
  6291. }
  6292. void manage_device(void)
  6293. {
  6294. char logline[256];
  6295. const char *msg = NULL;
  6296. struct cgpu_info *cgpu;
  6297. const struct device_drv *drv;
  6298. opt_loginput = true;
  6299. selecting_device = true;
  6300. immedok(logwin, true);
  6301. devchange:
  6302. if (unlikely(!total_devices))
  6303. {
  6304. clear_logwin();
  6305. wlogprint("(no devices)\n");
  6306. wlogprint("[Plus] Add device(s) [Enter] Close device manager\n");
  6307. _managetui_msg("(none)", &msg);
  6308. int input = getch();
  6309. switch (input)
  6310. {
  6311. case '+': case '=': // add new device
  6312. goto addnew;
  6313. default:
  6314. goto out;
  6315. }
  6316. }
  6317. cgpu = devices[selected_device];
  6318. drv = cgpu->drv;
  6319. refresh_devstatus();
  6320. refresh:
  6321. clear_logwin();
  6322. wlogprint("Select processor to manage using up/down arrow keys\n");
  6323. get_statline3(logline, sizeof(logline), cgpu, true, true);
  6324. wattron(logwin, A_BOLD);
  6325. wlogprint("%s", logline);
  6326. wattroff(logwin, A_BOLD);
  6327. wlogprint("\n");
  6328. if (cgpu->dev_manufacturer)
  6329. wlogprint(" %s from %s\n", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  6330. else
  6331. if (cgpu->dev_product)
  6332. wlogprint(" %s\n", cgpu->dev_product);
  6333. if (cgpu->dev_serial)
  6334. wlogprint("Serial: %s\n", cgpu->dev_serial);
  6335. if (cgpu->kname)
  6336. wlogprint("Kernel: %s\n", cgpu->kname);
  6337. if (drv->proc_wlogprint_status && likely(cgpu->status != LIFE_INIT))
  6338. drv->proc_wlogprint_status(cgpu);
  6339. wlogprint("\n");
  6340. // TODO: Last share at TIMESTAMP on pool N
  6341. // TODO: Custom device info/commands
  6342. if (cgpu->deven != DEV_ENABLED)
  6343. wlogprint("[E]nable ");
  6344. if (cgpu->deven != DEV_DISABLED)
  6345. wlogprint("[D]isable ");
  6346. if (drv->identify_device)
  6347. wlogprint("[I]dentify ");
  6348. if (drv->proc_tui_wlogprint_choices && likely(cgpu->status != LIFE_INIT))
  6349. drv->proc_tui_wlogprint_choices(cgpu);
  6350. wlogprint("\n");
  6351. wlogprint("[Slash] Find processor [Plus] Add device(s) [Enter] Close device manager\n");
  6352. _managetui_msg(cgpu->proc_repr, &msg);
  6353. while (true)
  6354. {
  6355. int input = getch();
  6356. applog(LOG_DEBUG, "ManageTUI: %"PRIpreprv": (choice %d)", cgpu->proc_repr, input);
  6357. switch (input) {
  6358. case 'd': case 'D':
  6359. if (cgpu->deven == DEV_DISABLED)
  6360. msg = "Processor already disabled\n";
  6361. else
  6362. {
  6363. cgpu->deven = DEV_DISABLED;
  6364. msg = "Processor being disabled\n";
  6365. }
  6366. goto refresh;
  6367. case 'e': case 'E':
  6368. if (cgpu->deven == DEV_ENABLED)
  6369. msg = "Processor already enabled\n";
  6370. else
  6371. {
  6372. proc_enable(cgpu);
  6373. msg = "Processor being enabled\n";
  6374. }
  6375. goto refresh;
  6376. case 'i': case 'I':
  6377. if (drv->identify_device && drv->identify_device(cgpu))
  6378. msg = "Identify command sent\n";
  6379. else
  6380. goto key_default;
  6381. goto refresh;
  6382. case KEY_DOWN:
  6383. if (selected_device >= total_devices - 1)
  6384. break;
  6385. ++selected_device;
  6386. goto devchange;
  6387. case KEY_UP:
  6388. if (selected_device <= 0)
  6389. break;
  6390. --selected_device;
  6391. goto devchange;
  6392. case KEY_NPAGE:
  6393. {
  6394. if (selected_device >= total_devices - 1)
  6395. break;
  6396. struct cgpu_info *mdev = devices[selected_device]->device;
  6397. do {
  6398. ++selected_device;
  6399. } while (devices[selected_device]->device == mdev && selected_device < total_devices - 1);
  6400. goto devchange;
  6401. }
  6402. case KEY_PPAGE:
  6403. {
  6404. if (selected_device <= 0)
  6405. break;
  6406. struct cgpu_info *mdev = devices[selected_device]->device;
  6407. do {
  6408. --selected_device;
  6409. } while (devices[selected_device]->device == mdev && selected_device > 0);
  6410. goto devchange;
  6411. }
  6412. case '/': case '?': // find device
  6413. {
  6414. static char *pattern = NULL;
  6415. char *newpattern = curses_input("Enter pattern");
  6416. if (newpattern)
  6417. {
  6418. free(pattern);
  6419. pattern = newpattern;
  6420. }
  6421. else
  6422. if (!pattern)
  6423. pattern = calloc(1, 1);
  6424. int match = cgpu_search(pattern, selected_device + 1);
  6425. if (match == -1)
  6426. {
  6427. msg = "Couldn't find device\n";
  6428. goto refresh;
  6429. }
  6430. selected_device = match;
  6431. goto devchange;
  6432. }
  6433. case '+': case '=': // add new device
  6434. {
  6435. addnew:
  6436. clear_logwin();
  6437. _wlogprint(
  6438. "Enter \"auto\", \"all\", or a serial port to probe for mining devices.\n"
  6439. "Prefix by a driver name and colon to only probe a specific driver.\n"
  6440. "For example: erupter:"
  6441. #ifdef WIN32
  6442. "\\\\.\\COM40"
  6443. #elif defined(__APPLE__)
  6444. "/dev/cu.SLAB_USBtoUART"
  6445. #else
  6446. "/dev/ttyUSB39"
  6447. #endif
  6448. "\n"
  6449. );
  6450. char *scanser = curses_input("Enter target");
  6451. if (scan_serial(scanser))
  6452. {
  6453. selected_device = total_devices - 1;
  6454. msg = "Device scan succeeded\n";
  6455. }
  6456. else
  6457. msg = "No new devices found\n";
  6458. goto devchange;
  6459. }
  6460. case 'Q': case 'q':
  6461. case KEY_BREAK: case KEY_BACKSPACE: case KEY_CANCEL: case KEY_CLOSE: case KEY_EXIT:
  6462. case '\x1b': // ESC
  6463. case KEY_ENTER:
  6464. case '\r': // Ctrl-M on Windows, with nonl
  6465. #ifdef PADENTER
  6466. case PADENTER: // pdcurses, used by Enter key on Windows with nonl
  6467. #endif
  6468. case '\n':
  6469. goto out;
  6470. default:
  6471. ;
  6472. key_default:
  6473. if (drv->proc_tui_handle_choice && likely(drv_ready(cgpu)))
  6474. {
  6475. msg = drv->proc_tui_handle_choice(cgpu, input);
  6476. if (msg)
  6477. goto refresh;
  6478. }
  6479. }
  6480. }
  6481. out:
  6482. selecting_device = false;
  6483. clear_logwin();
  6484. immedok(logwin, false);
  6485. opt_loginput = false;
  6486. }
  6487. void show_help(void)
  6488. {
  6489. opt_loginput = true;
  6490. clear_logwin();
  6491. // NOTE: wlogprint is a macro with a buffer limit
  6492. _wlogprint(
  6493. "ST: work in queue | F: network fails | NB: new blocks detected\n"
  6494. "AS: shares being submitted | BW: bandwidth (up/down)\n"
  6495. "E: # shares * diff per 2kB bw | U: shares/minute | BS: best share ever found\n"
  6496. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6497. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6498. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6499. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_BTEE
  6500. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6501. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6502. U8_HLINE U8_HLINE U8_HLINE U8_BTEE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6503. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6504. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6505. U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE U8_HLINE
  6506. "\n"
  6507. "devices/processors hashing (only for totals line), hottest temperature\n"
  6508. );
  6509. wlogprint(
  6510. "hashrates: %ds decaying / all-time average / all-time average (effective)\n"
  6511. , opt_log_interval);
  6512. _wlogprint(
  6513. "A: accepted shares | R: rejected+discarded(%% of total)\n"
  6514. "HW: hardware errors / %% nonces invalid\n"
  6515. "\n"
  6516. "Press any key to clear"
  6517. );
  6518. logwin_update();
  6519. getch();
  6520. clear_logwin();
  6521. opt_loginput = false;
  6522. }
  6523. static void *input_thread(void __maybe_unused *userdata)
  6524. {
  6525. RenameThread("input");
  6526. if (!curses_active)
  6527. return NULL;
  6528. while (1) {
  6529. int input;
  6530. input = getch();
  6531. switch (input) {
  6532. case 'h': case 'H': case '?':
  6533. show_help();
  6534. break;
  6535. case 'q': case 'Q':
  6536. kill_work();
  6537. return NULL;
  6538. case 'd': case 'D':
  6539. display_options();
  6540. break;
  6541. case 'm': case 'M':
  6542. manage_device();
  6543. break;
  6544. case 'p': case 'P':
  6545. display_pools();
  6546. break;
  6547. case 's': case 'S':
  6548. set_options();
  6549. break;
  6550. #ifdef HAVE_CURSES
  6551. case KEY_DOWN:
  6552. {
  6553. const int visible_lines = logcursor - devcursor;
  6554. const int invisible_lines = total_lines - visible_lines;
  6555. if (devsummaryYOffset <= -invisible_lines)
  6556. break;
  6557. devsummaryYOffset -= 2;
  6558. }
  6559. case KEY_UP:
  6560. if (devsummaryYOffset == 0)
  6561. break;
  6562. ++devsummaryYOffset;
  6563. refresh_devstatus();
  6564. break;
  6565. #endif
  6566. }
  6567. if (opt_realquiet) {
  6568. disable_curses();
  6569. break;
  6570. }
  6571. }
  6572. return NULL;
  6573. }
  6574. #endif
  6575. static void *api_thread(void *userdata)
  6576. {
  6577. struct thr_info *mythr = userdata;
  6578. pthread_detach(pthread_self());
  6579. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  6580. RenameThread("rpc");
  6581. api(api_thr_id);
  6582. mythr->has_pth = false;
  6583. return NULL;
  6584. }
  6585. void thread_reportin(struct thr_info *thr)
  6586. {
  6587. cgtime(&thr->last);
  6588. thr->cgpu->status = LIFE_WELL;
  6589. thr->getwork = 0;
  6590. thr->cgpu->device_last_well = time(NULL);
  6591. }
  6592. void thread_reportout(struct thr_info *thr)
  6593. {
  6594. thr->getwork = time(NULL);
  6595. }
  6596. static void hashmeter(int thr_id, struct timeval *diff,
  6597. uint64_t hashes_done)
  6598. {
  6599. char logstatusline[256];
  6600. struct timeval temp_tv_end, total_diff;
  6601. double secs;
  6602. double local_secs;
  6603. static double local_mhashes_done = 0;
  6604. double local_mhashes = (double)hashes_done / 1000000.0;
  6605. bool showlog = false;
  6606. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  6607. char rejpcbuf[6];
  6608. char bnbuf[6];
  6609. struct thr_info *thr;
  6610. /* Update the last time this thread reported in */
  6611. if (thr_id >= 0) {
  6612. thr = get_thread(thr_id);
  6613. cgtime(&(thr->last));
  6614. thr->cgpu->device_last_well = time(NULL);
  6615. }
  6616. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  6617. /* So we can call hashmeter from a non worker thread */
  6618. if (thr_id >= 0) {
  6619. struct cgpu_info *cgpu = thr->cgpu;
  6620. int threadobj = cgpu->threads ?: 1;
  6621. double thread_rolling = 0.0;
  6622. int i;
  6623. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  6624. thr_id, hashes_done, hashes_done / 1000 / secs);
  6625. /* Rolling average for each thread and each device */
  6626. decay_time(&thr->rolling, local_mhashes / secs, secs);
  6627. for (i = 0; i < threadobj; i++)
  6628. thread_rolling += cgpu->thr[i]->rolling;
  6629. mutex_lock(&hash_lock);
  6630. decay_time(&cgpu->rolling, thread_rolling, secs);
  6631. cgpu->total_mhashes += local_mhashes;
  6632. mutex_unlock(&hash_lock);
  6633. // If needed, output detailed, per-device stats
  6634. if (want_per_device_stats) {
  6635. struct timeval now;
  6636. struct timeval elapsed;
  6637. struct timeval *last_msg_tv = opt_show_procs ? &thr->cgpu->last_message_tv : &thr->cgpu->device->last_message_tv;
  6638. cgtime(&now);
  6639. timersub(&now, last_msg_tv, &elapsed);
  6640. if (opt_log_interval <= elapsed.tv_sec) {
  6641. struct cgpu_info *cgpu = thr->cgpu;
  6642. char logline[255];
  6643. *last_msg_tv = now;
  6644. get_statline(logline, sizeof(logline), cgpu);
  6645. if (!curses_active) {
  6646. printf("%s \r", logline);
  6647. fflush(stdout);
  6648. } else
  6649. applog(LOG_INFO, "%s", logline);
  6650. }
  6651. }
  6652. }
  6653. /* Totals are updated by all threads so can race without locking */
  6654. mutex_lock(&hash_lock);
  6655. cgtime(&temp_tv_end);
  6656. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  6657. total_mhashes_done += local_mhashes;
  6658. local_mhashes_done += local_mhashes;
  6659. /* Only update with opt_log_interval */
  6660. if (total_diff.tv_sec < opt_log_interval)
  6661. goto out_unlock;
  6662. showlog = true;
  6663. cgtime(&total_tv_end);
  6664. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  6665. decay_time(&total_rolling, local_mhashes_done / local_secs, local_secs);
  6666. global_hashrate = ((unsigned long long)lround(total_rolling)) * 1000000;
  6667. timersub(&total_tv_end, &total_tv_start, &total_diff);
  6668. total_secs = (double)total_diff.tv_sec +
  6669. ((double)total_diff.tv_usec / 1000000.0);
  6670. double wtotal = (total_diff_accepted + total_diff_rejected + total_diff_stale);
  6671. multi_format_unit_array2(
  6672. ((char*[]){cHr, aHr, uHr}),
  6673. ((size_t[]){h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_NOUNIT], h2bs_fmt_size[H2B_SPACED]}),
  6674. true, "h/s", H2B_SHORT,
  6675. 3,
  6676. 1e6*total_rolling,
  6677. 1e6*total_mhashes_done / total_secs,
  6678. utility_to_hashrate(total_diff1 * (wtotal ? (total_diff_accepted / wtotal) : 1) * 60 / total_secs));
  6679. #ifdef HAVE_CURSES
  6680. if (curses_active_locked()) {
  6681. float temp = 0;
  6682. struct cgpu_info *proc, *last_working_dev = NULL;
  6683. int i, working_devs = 0, working_procs = 0;
  6684. int divx;
  6685. bool bad = false;
  6686. // Find the highest temperature of all processors
  6687. for (i = 0; i < total_devices; ++i)
  6688. {
  6689. proc = get_devices(i);
  6690. if (proc->temp > temp)
  6691. temp = proc->temp;
  6692. if (unlikely(proc->deven == DEV_DISABLED))
  6693. ; // Just need to block it off from both conditions
  6694. else
  6695. if (likely(proc->status == LIFE_WELL && proc->deven == DEV_ENABLED))
  6696. {
  6697. if (proc->rolling > .1)
  6698. {
  6699. ++working_procs;
  6700. if (proc->device != last_working_dev)
  6701. {
  6702. ++working_devs;
  6703. last_working_dev = proc->device;
  6704. }
  6705. }
  6706. }
  6707. else
  6708. bad = true;
  6709. }
  6710. if (working_devs == working_procs)
  6711. snprintf(statusline, sizeof(statusline), "%s%d ", bad ? U8_BAD_START : "", working_devs);
  6712. else
  6713. snprintf(statusline, sizeof(statusline), "%s%d/%d ", bad ? U8_BAD_START : "", working_devs, working_procs);
  6714. divx = 7;
  6715. if (opt_show_procs && !opt_compact)
  6716. ++divx;
  6717. if (bad)
  6718. {
  6719. divx += sizeof(U8_BAD_START)-1;
  6720. strcpy(&statusline[divx], U8_BAD_END);
  6721. divx += sizeof(U8_BAD_END)-1;
  6722. }
  6723. temperature_column(&statusline[divx], sizeof(statusline)-divx, true, &temp);
  6724. format_statline(statusline, sizeof(statusline),
  6725. cHr, aHr,
  6726. uHr,
  6727. total_accepted,
  6728. total_rejected,
  6729. total_stale,
  6730. total_diff_rejected + total_diff_stale, total_diff_accepted,
  6731. hw_errors,
  6732. total_bad_nonces, total_bad_nonces + total_diff1);
  6733. unlock_curses();
  6734. }
  6735. #endif
  6736. // Add a space
  6737. memmove(&uHr[6], &uHr[5], strlen(&uHr[5]) + 1);
  6738. uHr[5] = ' ';
  6739. percentf4(rejpcbuf, sizeof(rejpcbuf), total_diff_rejected + total_diff_stale, total_diff_accepted);
  6740. percentf4(bnbuf, sizeof(bnbuf), total_bad_nonces, total_diff1);
  6741. snprintf(logstatusline, sizeof(logstatusline),
  6742. "%s%ds:%s avg:%s u:%s | A:%d R:%d+%d(%s) HW:%d/%s",
  6743. want_per_device_stats ? "ALL " : "",
  6744. opt_log_interval,
  6745. cHr, aHr,
  6746. uHr,
  6747. total_accepted,
  6748. total_rejected,
  6749. total_stale,
  6750. rejpcbuf,
  6751. hw_errors,
  6752. bnbuf
  6753. );
  6754. local_mhashes_done = 0;
  6755. out_unlock:
  6756. mutex_unlock(&hash_lock);
  6757. if (showlog) {
  6758. if (!curses_active) {
  6759. printf("%s \r", logstatusline);
  6760. fflush(stdout);
  6761. } else
  6762. applog(LOG_INFO, "%s", logstatusline);
  6763. }
  6764. }
  6765. void hashmeter2(struct thr_info *thr)
  6766. {
  6767. struct timeval tv_now, tv_elapsed;
  6768. timerclear(&thr->tv_hashes_done);
  6769. cgtime(&tv_now);
  6770. timersub(&tv_now, &thr->tv_lastupdate, &tv_elapsed);
  6771. /* Update the hashmeter at most 5 times per second */
  6772. if ((thr->hashes_done && (tv_elapsed.tv_sec > 0 || tv_elapsed.tv_usec > 200000)) ||
  6773. tv_elapsed.tv_sec >= opt_log_interval) {
  6774. hashmeter(thr->id, &tv_elapsed, thr->hashes_done);
  6775. thr->hashes_done = 0;
  6776. thr->tv_lastupdate = tv_now;
  6777. }
  6778. }
  6779. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  6780. struct stratum_share *sshare)
  6781. {
  6782. struct work *work = sshare->work;
  6783. share_result(val, res_val, err_val, work, false, "");
  6784. }
  6785. /* Parses stratum json responses and tries to find the id that the request
  6786. * matched to and treat it accordingly. */
  6787. bool parse_stratum_response(struct pool *pool, char *s)
  6788. {
  6789. json_t *val = NULL, *err_val, *res_val, *id_val;
  6790. struct stratum_share *sshare;
  6791. json_error_t err;
  6792. bool ret = false;
  6793. int id;
  6794. val = JSON_LOADS(s, &err);
  6795. if (!val) {
  6796. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  6797. goto out;
  6798. }
  6799. res_val = json_object_get(val, "result");
  6800. err_val = json_object_get(val, "error");
  6801. id_val = json_object_get(val, "id");
  6802. if (json_is_null(id_val) || !id_val) {
  6803. char *ss;
  6804. if (err_val)
  6805. ss = json_dumps(err_val, JSON_INDENT(3));
  6806. else
  6807. ss = strdup("(unknown reason)");
  6808. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  6809. free(ss);
  6810. goto out;
  6811. }
  6812. if (!json_is_integer(id_val)) {
  6813. if (json_is_string(id_val)
  6814. && !strncmp(json_string_value(id_val), "txlist", 6))
  6815. {
  6816. const bool is_array = json_is_array(res_val);
  6817. applog(LOG_DEBUG, "Received %s for pool %u job %s",
  6818. is_array ? "transaction list" : "no-transaction-list response",
  6819. pool->pool_no, &json_string_value(id_val)[6]);
  6820. if (strcmp(json_string_value(id_val) + 6, pool->swork.job_id) || !is_array)
  6821. // We only care about a transaction list for the current job id
  6822. goto fishy;
  6823. // Check that the transactions actually hash to the merkle links
  6824. {
  6825. unsigned maxtx = 1 << pool->swork.merkles;
  6826. unsigned mintx = maxtx >> 1;
  6827. --maxtx;
  6828. unsigned acttx = (unsigned)json_array_size(res_val);
  6829. if (acttx < mintx || acttx > maxtx) {
  6830. applog(LOG_WARNING, "Pool %u is sending mismatched block contents to us (%u is not %u-%u)",
  6831. pool->pool_no, acttx, mintx, maxtx);
  6832. goto fishy;
  6833. }
  6834. // TODO: Check hashes match actual merkle links
  6835. }
  6836. pool_set_opaque(pool, false);
  6837. timer_unset(&pool->swork.tv_transparency);
  6838. fishy:
  6839. ret = true;
  6840. }
  6841. goto out;
  6842. }
  6843. id = json_integer_value(id_val);
  6844. mutex_lock(&sshare_lock);
  6845. HASH_FIND_INT(stratum_shares, &id, sshare);
  6846. if (sshare)
  6847. HASH_DEL(stratum_shares, sshare);
  6848. mutex_unlock(&sshare_lock);
  6849. if (!sshare) {
  6850. double pool_diff;
  6851. /* Since the share is untracked, we can only guess at what the
  6852. * work difficulty is based on the current pool diff. */
  6853. cg_rlock(&pool->data_lock);
  6854. pool_diff = pool->swork.diff;
  6855. cg_runlock(&pool->data_lock);
  6856. if (json_is_true(res_val)) {
  6857. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  6858. /* We don't know what device this came from so we can't
  6859. * attribute the work to the relevant cgpu */
  6860. mutex_lock(&stats_lock);
  6861. total_accepted++;
  6862. pool->accepted++;
  6863. total_diff_accepted += pool_diff;
  6864. pool->diff_accepted += pool_diff;
  6865. mutex_unlock(&stats_lock);
  6866. } else {
  6867. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  6868. mutex_lock(&stats_lock);
  6869. total_rejected++;
  6870. pool->rejected++;
  6871. total_diff_rejected += pool_diff;
  6872. pool->diff_rejected += pool_diff;
  6873. mutex_unlock(&stats_lock);
  6874. }
  6875. goto out;
  6876. }
  6877. else {
  6878. mutex_lock(&submitting_lock);
  6879. --total_submitting;
  6880. mutex_unlock(&submitting_lock);
  6881. }
  6882. stratum_share_result(val, res_val, err_val, sshare);
  6883. free_work(sshare->work);
  6884. free(sshare);
  6885. ret = true;
  6886. out:
  6887. if (val)
  6888. json_decref(val);
  6889. return ret;
  6890. }
  6891. static void shutdown_stratum(struct pool *pool)
  6892. {
  6893. // Shut down Stratum as if we never had it
  6894. pool->stratum_active = false;
  6895. pool->stratum_init = false;
  6896. pool->has_stratum = false;
  6897. shutdown(pool->sock, SHUT_RDWR);
  6898. free(pool->stratum_url);
  6899. if (pool->sockaddr_url == pool->stratum_url)
  6900. pool->sockaddr_url = NULL;
  6901. pool->stratum_url = NULL;
  6902. }
  6903. void clear_stratum_shares(struct pool *pool)
  6904. {
  6905. int my_mining_threads = mining_threads; // Cached outside of locking
  6906. struct stratum_share *sshare, *tmpshare;
  6907. struct work *work;
  6908. struct cgpu_info *cgpu;
  6909. double diff_cleared = 0;
  6910. double thr_diff_cleared[my_mining_threads];
  6911. int cleared = 0;
  6912. int thr_cleared[my_mining_threads];
  6913. // NOTE: This is per-thread rather than per-device to avoid getting devices lock in stratum_shares loop
  6914. for (int i = 0; i < my_mining_threads; ++i)
  6915. {
  6916. thr_diff_cleared[i] = 0;
  6917. thr_cleared[i] = 0;
  6918. }
  6919. mutex_lock(&sshare_lock);
  6920. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6921. work = sshare->work;
  6922. if (sshare->work->pool == pool && work->thr_id < my_mining_threads) {
  6923. HASH_DEL(stratum_shares, sshare);
  6924. sharelog("disconnect", work);
  6925. diff_cleared += sshare->work->work_difficulty;
  6926. thr_diff_cleared[work->thr_id] += work->work_difficulty;
  6927. ++thr_cleared[work->thr_id];
  6928. free_work(sshare->work);
  6929. free(sshare);
  6930. cleared++;
  6931. }
  6932. }
  6933. mutex_unlock(&sshare_lock);
  6934. if (cleared) {
  6935. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  6936. mutex_lock(&stats_lock);
  6937. pool->stale_shares += cleared;
  6938. total_stale += cleared;
  6939. pool->diff_stale += diff_cleared;
  6940. total_diff_stale += diff_cleared;
  6941. for (int i = 0; i < my_mining_threads; ++i)
  6942. if (thr_cleared[i])
  6943. {
  6944. cgpu = get_thr_cgpu(i);
  6945. cgpu->diff_stale += thr_diff_cleared[i];
  6946. cgpu->stale += thr_cleared[i];
  6947. }
  6948. mutex_unlock(&stats_lock);
  6949. mutex_lock(&submitting_lock);
  6950. total_submitting -= cleared;
  6951. mutex_unlock(&submitting_lock);
  6952. }
  6953. }
  6954. static void resubmit_stratum_shares(struct pool *pool)
  6955. {
  6956. struct stratum_share *sshare, *tmpshare;
  6957. struct work *work;
  6958. unsigned resubmitted = 0;
  6959. mutex_lock(&sshare_lock);
  6960. mutex_lock(&submitting_lock);
  6961. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  6962. if (sshare->work->pool != pool)
  6963. continue;
  6964. HASH_DEL(stratum_shares, sshare);
  6965. work = sshare->work;
  6966. DL_APPEND(submit_waiting, work);
  6967. free(sshare);
  6968. ++resubmitted;
  6969. }
  6970. mutex_unlock(&submitting_lock);
  6971. mutex_unlock(&sshare_lock);
  6972. if (resubmitted) {
  6973. notifier_wake(submit_waiting_notifier);
  6974. applog(LOG_DEBUG, "Resubmitting %u shares due to stratum disconnect on pool %u", resubmitted, pool->pool_no);
  6975. }
  6976. }
  6977. static void clear_pool_work(struct pool *pool)
  6978. {
  6979. struct work *work, *tmp;
  6980. int cleared = 0;
  6981. mutex_lock(stgd_lock);
  6982. HASH_ITER(hh, staged_work, work, tmp) {
  6983. if (work->pool == pool) {
  6984. HASH_DEL(staged_work, work);
  6985. free_work(work);
  6986. cleared++;
  6987. staged_full = false;
  6988. }
  6989. }
  6990. mutex_unlock(stgd_lock);
  6991. }
  6992. static int cp_prio(void)
  6993. {
  6994. int prio;
  6995. cg_rlock(&control_lock);
  6996. prio = currentpool->prio;
  6997. cg_runlock(&control_lock);
  6998. return prio;
  6999. }
  7000. /* We only need to maintain a secondary pool connection when we need the
  7001. * capacity to get work from the backup pools while still on the primary */
  7002. static bool cnx_needed(struct pool *pool)
  7003. {
  7004. struct pool *cp;
  7005. if (pool->enabled != POOL_ENABLED)
  7006. return false;
  7007. /* Balance strategies need all pools online */
  7008. if (pool_strategy == POOL_BALANCE)
  7009. return true;
  7010. if (pool_strategy == POOL_LOADBALANCE)
  7011. return true;
  7012. /* Idle stratum pool needs something to kick it alive again */
  7013. if (pool->has_stratum && pool->idle)
  7014. return true;
  7015. /* Getwork pools without opt_fail_only need backup pools up to be able
  7016. * to leak shares */
  7017. cp = current_pool();
  7018. if (cp == pool)
  7019. return true;
  7020. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  7021. return true;
  7022. /* Keep the connection open to allow any stray shares to be submitted
  7023. * on switching pools for 2 minutes. */
  7024. if (!timer_passed(&pool->tv_last_work_time, NULL))
  7025. return true;
  7026. /* If the pool has only just come to life and is higher priority than
  7027. * the current pool keep the connection open so we can fail back to
  7028. * it. */
  7029. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7030. return true;
  7031. if (pool_unworkable(cp))
  7032. return true;
  7033. /* We've run out of work, bring anything back to life. */
  7034. if (no_work)
  7035. return true;
  7036. return false;
  7037. }
  7038. static void wait_lpcurrent(struct pool *pool);
  7039. static void pool_resus(struct pool *pool);
  7040. static void gen_stratum_work(struct pool *pool, struct work *work);
  7041. static void stratum_resumed(struct pool *pool)
  7042. {
  7043. if (!pool->stratum_notify)
  7044. return;
  7045. if (pool_tclear(pool, &pool->idle)) {
  7046. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  7047. pool_resus(pool);
  7048. }
  7049. }
  7050. static bool supports_resume(struct pool *pool)
  7051. {
  7052. bool ret;
  7053. cg_rlock(&pool->data_lock);
  7054. ret = (pool->sessionid != NULL);
  7055. cg_runlock(&pool->data_lock);
  7056. return ret;
  7057. }
  7058. /* One stratum thread per pool that has stratum waits on the socket checking
  7059. * for new messages and for the integrity of the socket connection. We reset
  7060. * the connection based on the integrity of the receive side only as the send
  7061. * side will eventually expire data it fails to send. */
  7062. static void *stratum_thread(void *userdata)
  7063. {
  7064. struct pool *pool = (struct pool *)userdata;
  7065. pthread_detach(pthread_self());
  7066. char threadname[20];
  7067. snprintf(threadname, 20, "stratum%u", pool->pool_no);
  7068. RenameThread(threadname);
  7069. srand(time(NULL) + (intptr_t)userdata);
  7070. while (42) {
  7071. struct timeval timeout;
  7072. int sel_ret;
  7073. fd_set rd;
  7074. char *s;
  7075. int sock;
  7076. if (unlikely(!pool->has_stratum))
  7077. break;
  7078. sock = pool->sock;
  7079. /* Check to see whether we need to maintain this connection
  7080. * indefinitely or just bring it up when we switch to this
  7081. * pool */
  7082. if (sock == INVSOCK || (!sock_full(pool) && !cnx_needed(pool))) {
  7083. suspend_stratum(pool);
  7084. clear_stratum_shares(pool);
  7085. clear_pool_work(pool);
  7086. wait_lpcurrent(pool);
  7087. if (!restart_stratum(pool)) {
  7088. pool_died(pool);
  7089. while (!restart_stratum(pool)) {
  7090. if (pool->removed)
  7091. goto out;
  7092. cgsleep_ms(30000);
  7093. }
  7094. }
  7095. }
  7096. FD_ZERO(&rd);
  7097. FD_SET(sock, &rd);
  7098. timeout.tv_sec = 120;
  7099. timeout.tv_usec = 0;
  7100. /* If we fail to receive any notify messages for 2 minutes we
  7101. * assume the connection has been dropped and treat this pool
  7102. * as dead */
  7103. if (!sock_full(pool) && (sel_ret = select(sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  7104. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  7105. s = NULL;
  7106. } else
  7107. s = recv_line(pool);
  7108. if (!s) {
  7109. if (!pool->has_stratum)
  7110. break;
  7111. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  7112. pool->getfail_occasions++;
  7113. total_go++;
  7114. mutex_lock(&pool->stratum_lock);
  7115. pool->stratum_active = pool->stratum_notify = false;
  7116. pool->sock = INVSOCK;
  7117. mutex_unlock(&pool->stratum_lock);
  7118. /* If the socket to our stratum pool disconnects, all
  7119. * submissions need to be discarded or resent. */
  7120. if (!supports_resume(pool))
  7121. clear_stratum_shares(pool);
  7122. else
  7123. resubmit_stratum_shares(pool);
  7124. clear_pool_work(pool);
  7125. if (pool == current_pool())
  7126. restart_threads();
  7127. if (restart_stratum(pool))
  7128. continue;
  7129. shutdown_stratum(pool);
  7130. pool_died(pool);
  7131. break;
  7132. }
  7133. /* Check this pool hasn't died while being a backup pool and
  7134. * has not had its idle flag cleared */
  7135. stratum_resumed(pool);
  7136. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  7137. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  7138. free(s);
  7139. if (pool->swork.clean) {
  7140. struct work *work = make_work();
  7141. /* Generate a single work item to update the current
  7142. * block database */
  7143. pool->swork.clean = false;
  7144. gen_stratum_work(pool, work);
  7145. /* Try to extract block height from coinbase scriptSig */
  7146. uint8_t *bin_height = &bytes_buf(&pool->swork.coinbase)[4 /*version*/ + 1 /*txin count*/ + 36 /*prevout*/ + 1 /*scriptSig len*/ + 1 /*push opcode*/];
  7147. unsigned char cb_height_sz;
  7148. cb_height_sz = bin_height[-1];
  7149. if (cb_height_sz == 3) {
  7150. // FIXME: The block number will overflow this by AD 2173
  7151. uint32_t block_id = ((uint32_t*)work->data)[1];
  7152. uint32_t height = 0;
  7153. memcpy(&height, bin_height, 3);
  7154. height = le32toh(height);
  7155. have_block_height(block_id, height);
  7156. }
  7157. ++pool->work_restart_id;
  7158. if (test_work_current(work)) {
  7159. /* Only accept a work update if this stratum
  7160. * connection is from the current pool */
  7161. if (pool == current_pool()) {
  7162. restart_threads();
  7163. applog(
  7164. (opt_quiet_work_updates ? LOG_DEBUG : LOG_NOTICE),
  7165. "Stratum from pool %d requested work update", pool->pool_no);
  7166. }
  7167. } else
  7168. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  7169. free_work(work);
  7170. }
  7171. if (timer_passed(&pool->swork.tv_transparency, NULL)) {
  7172. // More than 4 timmills past since requested transactions
  7173. timer_unset(&pool->swork.tv_transparency);
  7174. pool_set_opaque(pool, true);
  7175. }
  7176. }
  7177. out:
  7178. return NULL;
  7179. }
  7180. static void init_stratum_thread(struct pool *pool)
  7181. {
  7182. have_longpoll = true;
  7183. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  7184. quit(1, "Failed to create stratum thread");
  7185. }
  7186. static void *longpoll_thread(void *userdata);
  7187. static bool stratum_works(struct pool *pool)
  7188. {
  7189. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  7190. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  7191. return false;
  7192. if (pool->stratum_active)
  7193. return true;
  7194. if (!initiate_stratum(pool))
  7195. return false;
  7196. return true;
  7197. }
  7198. static bool pool_active(struct pool *pool, bool pinging)
  7199. {
  7200. struct timeval tv_getwork, tv_getwork_reply;
  7201. bool ret = false;
  7202. json_t *val;
  7203. CURL *curl;
  7204. int rolltime;
  7205. char *rpc_req;
  7206. struct work *work;
  7207. enum pool_protocol proto;
  7208. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  7209. /* This is the central point we activate stratum when we can */
  7210. curl = curl_easy_init();
  7211. if (unlikely(!curl)) {
  7212. applog(LOG_ERR, "CURL initialisation failed");
  7213. return false;
  7214. }
  7215. if (!(want_gbt || want_getwork))
  7216. goto nohttp;
  7217. work = make_work();
  7218. /* Probe for GBT support on first pass */
  7219. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  7220. tryagain:
  7221. rpc_req = prepare_rpc_req_probe(work, proto, NULL);
  7222. work->pool = pool;
  7223. if (!rpc_req)
  7224. goto out;
  7225. pool->probed = false;
  7226. cgtime(&tv_getwork);
  7227. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  7228. true, false, &rolltime, pool, false);
  7229. cgtime(&tv_getwork_reply);
  7230. free(rpc_req);
  7231. /* Detect if a http getwork pool has an X-Stratum header at startup,
  7232. * and if so, switch to that in preference to getwork if it works */
  7233. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  7234. if (!pool->has_stratum) {
  7235. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  7236. if (!pool->rpc_url)
  7237. pool->rpc_url = strdup(pool->stratum_url);
  7238. pool->has_stratum = true;
  7239. }
  7240. free_work(work);
  7241. if (val)
  7242. json_decref(val);
  7243. retry_stratum:
  7244. curl_easy_cleanup(curl);
  7245. /* We create the stratum thread for each pool just after
  7246. * successful authorisation. Once the init flag has been set
  7247. * we never unset it and the stratum thread is responsible for
  7248. * setting/unsetting the active flag */
  7249. bool init = pool_tset(pool, &pool->stratum_init);
  7250. if (!init) {
  7251. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  7252. if (ret)
  7253. {
  7254. detect_algo = 2;
  7255. init_stratum_thread(pool);
  7256. }
  7257. else
  7258. pool_tclear(pool, &pool->stratum_init);
  7259. return ret;
  7260. }
  7261. return pool->stratum_active;
  7262. }
  7263. else if (pool->has_stratum)
  7264. shutdown_stratum(pool);
  7265. if (val) {
  7266. bool rc;
  7267. json_t *res;
  7268. res = json_object_get(val, "result");
  7269. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  7270. goto badwork;
  7271. work->rolltime = rolltime;
  7272. rc = work_decode(pool, work, val);
  7273. if (rc) {
  7274. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  7275. pool->pool_no, pool->rpc_url);
  7276. work->pool = pool;
  7277. copy_time(&work->tv_getwork, &tv_getwork);
  7278. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  7279. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  7280. calc_diff(work, 0);
  7281. update_last_work(work);
  7282. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  7283. stage_work(work);
  7284. total_getworks++;
  7285. pool->getwork_requested++;
  7286. ret = true;
  7287. cgtime(&pool->tv_idle);
  7288. } else {
  7289. badwork:
  7290. json_decref(val);
  7291. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  7292. pool->pool_no, pool->rpc_url);
  7293. pool->proto = proto = pool_protocol_fallback(proto);
  7294. if (PLP_NONE != proto)
  7295. goto tryagain;
  7296. free_work(work);
  7297. goto out;
  7298. }
  7299. json_decref(val);
  7300. if (proto != pool->proto) {
  7301. pool->proto = proto;
  7302. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  7303. }
  7304. if (pool->lp_url)
  7305. goto out;
  7306. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  7307. const struct blktmpl_longpoll_req *lp;
  7308. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  7309. // NOTE: work_decode takes care of lp id
  7310. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  7311. if (!pool->lp_url)
  7312. {
  7313. ret = false;
  7314. goto out;
  7315. }
  7316. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  7317. }
  7318. else
  7319. if (pool->hdr_path && want_getwork) {
  7320. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  7321. if (!pool->lp_url)
  7322. {
  7323. ret = false;
  7324. goto out;
  7325. }
  7326. pool->lp_proto = PLP_GETWORK;
  7327. } else
  7328. pool->lp_url = NULL;
  7329. if (want_longpoll && !pool->lp_started) {
  7330. pool->lp_started = true;
  7331. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  7332. quit(1, "Failed to create pool longpoll thread");
  7333. }
  7334. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  7335. pool->proto = proto;
  7336. goto tryagain;
  7337. } else {
  7338. free_work(work);
  7339. nohttp:
  7340. /* If we failed to parse a getwork, this could be a stratum
  7341. * url without the prefix stratum+tcp:// so let's check it */
  7342. if (extract_sockaddr(pool->rpc_url, &pool->sockaddr_url, &pool->stratum_port) && initiate_stratum(pool)) {
  7343. pool->has_stratum = true;
  7344. goto retry_stratum;
  7345. }
  7346. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  7347. pool->pool_no, pool->rpc_url);
  7348. if (!pinging)
  7349. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  7350. }
  7351. out:
  7352. curl_easy_cleanup(curl);
  7353. return ret;
  7354. }
  7355. static void pool_resus(struct pool *pool)
  7356. {
  7357. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  7358. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  7359. else
  7360. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  7361. }
  7362. static struct work *hash_pop(void)
  7363. {
  7364. struct work *work = NULL, *tmp;
  7365. int hc;
  7366. struct timespec ts;
  7367. retry:
  7368. mutex_lock(stgd_lock);
  7369. while (!HASH_COUNT(staged_work))
  7370. {
  7371. if (unlikely(staged_full))
  7372. {
  7373. if (likely(opt_queue < 10 + mining_threads))
  7374. {
  7375. ++opt_queue;
  7376. applog(LOG_WARNING, "Staged work underrun; increasing queue minimum to %d", opt_queue);
  7377. }
  7378. else
  7379. applog(LOG_WARNING, "Staged work underrun; not automatically increasing above %d", opt_queue);
  7380. staged_full = false; // Let it fill up before triggering an underrun again
  7381. no_work = true;
  7382. }
  7383. ts = (struct timespec){ .tv_sec = opt_log_interval, };
  7384. pthread_cond_signal(&gws_cond);
  7385. if (ETIMEDOUT == pthread_cond_timedwait(&getq->cond, stgd_lock, &ts))
  7386. {
  7387. run_cmd(cmd_idle);
  7388. pthread_cond_signal(&gws_cond);
  7389. pthread_cond_wait(&getq->cond, stgd_lock);
  7390. }
  7391. }
  7392. no_work = false;
  7393. hc = HASH_COUNT(staged_work);
  7394. /* Find clone work if possible, to allow masters to be reused */
  7395. if (hc > staged_rollable) {
  7396. HASH_ITER(hh, staged_work, work, tmp) {
  7397. if (!work_rollable(work))
  7398. break;
  7399. }
  7400. } else
  7401. work = staged_work;
  7402. if (can_roll(work) && should_roll(work))
  7403. {
  7404. // Instead of consuming it, force it to be cloned and grab the clone
  7405. mutex_unlock(stgd_lock);
  7406. clone_available();
  7407. goto retry;
  7408. }
  7409. HASH_DEL(staged_work, work);
  7410. if (work_rollable(work))
  7411. staged_rollable--;
  7412. /* Signal the getwork scheduler to look for more work */
  7413. pthread_cond_signal(&gws_cond);
  7414. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  7415. pthread_cond_signal(&getq->cond);
  7416. mutex_unlock(stgd_lock);
  7417. work->pool->last_work_time = time(NULL);
  7418. cgtime(&work->pool->tv_last_work_time);
  7419. return work;
  7420. }
  7421. /* Clones work by rolling it if possible, and returning a clone instead of the
  7422. * original work item which gets staged again to possibly be rolled again in
  7423. * the future */
  7424. static struct work *clone_work(struct work *work)
  7425. {
  7426. int mrs = mining_threads + opt_queue - total_staged();
  7427. struct work *work_clone;
  7428. bool cloned;
  7429. if (mrs < 1)
  7430. return work;
  7431. cloned = false;
  7432. work_clone = make_clone(work);
  7433. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  7434. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  7435. stage_work(work_clone);
  7436. roll_work(work);
  7437. work_clone = make_clone(work);
  7438. /* Roll it again to prevent duplicates should this be used
  7439. * directly later on */
  7440. roll_work(work);
  7441. cloned = true;
  7442. }
  7443. if (cloned) {
  7444. stage_work(work);
  7445. return work_clone;
  7446. }
  7447. free_work(work_clone);
  7448. return work;
  7449. }
  7450. void gen_hash(unsigned char *data, unsigned char *hash, int len)
  7451. {
  7452. unsigned char hash1[32];
  7453. sha256(data, len, hash1);
  7454. sha256(hash1, 32, hash);
  7455. }
  7456. /* Diff 1 is a 256 bit unsigned integer of
  7457. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  7458. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  7459. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  7460. static void bdiff_target_leadzero(unsigned char *target, double diff)
  7461. {
  7462. uint64_t *data64, h64;
  7463. double d64;
  7464. d64 = diffone;
  7465. d64 /= diff;
  7466. d64 = ceil(d64);
  7467. h64 = d64;
  7468. memset(target, 0, 32);
  7469. if (d64 < 18446744073709551616.0) {
  7470. unsigned char *rtarget = target;
  7471. memset(rtarget, 0, 32);
  7472. if (opt_scrypt)
  7473. data64 = (uint64_t *)(rtarget + 2);
  7474. else
  7475. data64 = (uint64_t *)(rtarget + 4);
  7476. *data64 = htobe64(h64);
  7477. } else {
  7478. /* Support for the classic all FFs just-below-1 diff */
  7479. if (opt_scrypt)
  7480. memset(&target[2], 0xff, 30);
  7481. else
  7482. memset(&target[4], 0xff, 28);
  7483. }
  7484. }
  7485. void set_target(unsigned char *dest_target, double diff)
  7486. {
  7487. unsigned char rtarget[32];
  7488. bdiff_target_leadzero(rtarget, diff);
  7489. swab256(dest_target, rtarget);
  7490. if (opt_debug) {
  7491. char htarget[65];
  7492. bin2hex(htarget, rtarget, 32);
  7493. applog(LOG_DEBUG, "Generated target %s", htarget);
  7494. }
  7495. }
  7496. void stratum_work_cpy(struct stratum_work * const dst, const struct stratum_work * const src)
  7497. {
  7498. *dst = *src;
  7499. dst->job_id = strdup(src->job_id);
  7500. bytes_cpy(&dst->coinbase, &src->coinbase);
  7501. bytes_cpy(&dst->merkle_bin, &src->merkle_bin);
  7502. }
  7503. void stratum_work_clean(struct stratum_work * const swork)
  7504. {
  7505. free(swork->job_id);
  7506. bytes_free(&swork->coinbase);
  7507. bytes_free(&swork->merkle_bin);
  7508. }
  7509. /* Generates stratum based work based on the most recent notify information
  7510. * from the pool. This will keep generating work while a pool is down so we use
  7511. * other means to detect when the pool has died in stratum_thread */
  7512. static void gen_stratum_work(struct pool *pool, struct work *work)
  7513. {
  7514. clean_work(work);
  7515. cg_wlock(&pool->data_lock);
  7516. pool->swork.data_lock_p = &pool->data_lock;
  7517. bytes_resize(&work->nonce2, pool->n2size);
  7518. if (pool->nonce2sz < pool->n2size)
  7519. memset(&bytes_buf(&work->nonce2)[pool->nonce2sz], 0, pool->n2size - pool->nonce2sz);
  7520. memcpy(bytes_buf(&work->nonce2),
  7521. #ifdef WORDS_BIGENDIAN
  7522. // NOTE: On big endian, the most significant bits are stored at the end, so skip the LSBs
  7523. &((char*)&pool->nonce2)[pool->nonce2off],
  7524. #else
  7525. &pool->nonce2,
  7526. #endif
  7527. pool->nonce2sz);
  7528. pool->nonce2++;
  7529. work->pool = pool;
  7530. work->work_restart_id = work->pool->work_restart_id;
  7531. gen_stratum_work2(work, &pool->swork, pool->nonce1);
  7532. cgtime(&work->tv_staged);
  7533. }
  7534. void gen_stratum_work2(struct work *work, struct stratum_work *swork, const char *nonce1)
  7535. {
  7536. unsigned char *coinbase, merkle_root[32], merkle_sha[64];
  7537. uint8_t *merkle_bin;
  7538. uint32_t *data32, *swap32;
  7539. int i;
  7540. /* Generate coinbase */
  7541. coinbase = bytes_buf(&swork->coinbase);
  7542. memcpy(&coinbase[swork->nonce2_offset], bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7543. /* Downgrade to a read lock to read off the variables */
  7544. if (swork->data_lock_p)
  7545. cg_dwlock(swork->data_lock_p);
  7546. /* Generate merkle root */
  7547. gen_hash(coinbase, merkle_root, bytes_len(&swork->coinbase));
  7548. memcpy(merkle_sha, merkle_root, 32);
  7549. merkle_bin = bytes_buf(&swork->merkle_bin);
  7550. for (i = 0; i < swork->merkles; ++i, merkle_bin += 32) {
  7551. memcpy(merkle_sha + 32, merkle_bin, 32);
  7552. gen_hash(merkle_sha, merkle_root, 64);
  7553. memcpy(merkle_sha, merkle_root, 32);
  7554. }
  7555. data32 = (uint32_t *)merkle_sha;
  7556. swap32 = (uint32_t *)merkle_root;
  7557. flip32(swap32, data32);
  7558. memcpy(&work->data[0], swork->header1, 36);
  7559. memcpy(&work->data[36], merkle_root, 32);
  7560. *((uint32_t*)&work->data[68]) = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  7561. memcpy(&work->data[72], swork->diffbits, 4);
  7562. memset(&work->data[76], 0, 4); // nonce
  7563. memcpy(&work->data[80], workpadding_bin, 48);
  7564. /* Store the stratum work diff to check it still matches the pool's
  7565. * stratum diff when submitting shares */
  7566. work->sdiff = swork->diff;
  7567. /* Copy parameters required for share submission */
  7568. work->job_id = strdup(swork->job_id);
  7569. work->nonce1 = strdup(nonce1);
  7570. if (swork->data_lock_p)
  7571. cg_runlock(swork->data_lock_p);
  7572. if (opt_debug)
  7573. {
  7574. char header[161];
  7575. char nonce2hex[(bytes_len(&work->nonce2) * 2) + 1];
  7576. bin2hex(header, work->data, 80);
  7577. bin2hex(nonce2hex, bytes_buf(&work->nonce2), bytes_len(&work->nonce2));
  7578. applog(LOG_DEBUG, "Generated stratum header %s", header);
  7579. applog(LOG_DEBUG, "Work job_id %s nonce2 %s", work->job_id, nonce2hex);
  7580. }
  7581. calc_midstate(work);
  7582. set_target(work->target, work->sdiff);
  7583. local_work++;
  7584. work->stratum = true;
  7585. work->blk.nonce = 0;
  7586. work->id = total_work++;
  7587. work->longpoll = false;
  7588. work->getwork_mode = GETWORK_MODE_STRATUM;
  7589. /* Nominally allow a driver to ntime roll 60 seconds */
  7590. work->drv_rolllimit = 60;
  7591. calc_diff(work, 0);
  7592. }
  7593. void request_work(struct thr_info *thr)
  7594. {
  7595. struct cgpu_info *cgpu = thr->cgpu;
  7596. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7597. /* Tell the watchdog thread this thread is waiting on getwork and
  7598. * should not be restarted */
  7599. thread_reportout(thr);
  7600. // HACK: Since get_work still blocks, reportout all processors dependent on this thread
  7601. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7602. {
  7603. if (proc->threads)
  7604. break;
  7605. thread_reportout(proc->thr[0]);
  7606. }
  7607. cgtime(&dev_stats->_get_start);
  7608. }
  7609. // FIXME: Make this non-blocking (and remove HACK above)
  7610. struct work *get_work(struct thr_info *thr)
  7611. {
  7612. const int thr_id = thr->id;
  7613. struct cgpu_info *cgpu = thr->cgpu;
  7614. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  7615. struct cgminer_stats *pool_stats;
  7616. struct timeval tv_get;
  7617. struct work *work = NULL;
  7618. applog(LOG_DEBUG, "%"PRIpreprv": Popping work from get queue to get work", cgpu->proc_repr);
  7619. while (!work) {
  7620. work = hash_pop();
  7621. if (stale_work(work, false)) {
  7622. staged_full = false; // It wasn't really full, since it was stale :(
  7623. discard_work(work);
  7624. work = NULL;
  7625. wake_gws();
  7626. }
  7627. }
  7628. applog(LOG_DEBUG, "%"PRIpreprv": Got work %d from get queue to get work for thread %d",
  7629. cgpu->proc_repr, work->id, thr_id);
  7630. work->thr_id = thr_id;
  7631. thread_reportin(thr);
  7632. // HACK: Since get_work still blocks, reportin all processors dependent on this thread
  7633. for (struct cgpu_info *proc = thr->cgpu->next_proc; proc; proc = proc->next_proc)
  7634. {
  7635. if (proc->threads)
  7636. break;
  7637. thread_reportin(proc->thr[0]);
  7638. }
  7639. work->mined = true;
  7640. work->blk.nonce = 0;
  7641. cgtime(&tv_get);
  7642. timersub(&tv_get, &dev_stats->_get_start, &tv_get);
  7643. timeradd(&tv_get, &dev_stats->getwork_wait, &dev_stats->getwork_wait);
  7644. if (timercmp(&tv_get, &dev_stats->getwork_wait_max, >))
  7645. dev_stats->getwork_wait_max = tv_get;
  7646. if (timercmp(&tv_get, &dev_stats->getwork_wait_min, <))
  7647. dev_stats->getwork_wait_min = tv_get;
  7648. ++dev_stats->getwork_calls;
  7649. pool_stats = &(work->pool->cgminer_stats);
  7650. timeradd(&tv_get, &pool_stats->getwork_wait, &pool_stats->getwork_wait);
  7651. if (timercmp(&tv_get, &pool_stats->getwork_wait_max, >))
  7652. pool_stats->getwork_wait_max = tv_get;
  7653. if (timercmp(&tv_get, &pool_stats->getwork_wait_min, <))
  7654. pool_stats->getwork_wait_min = tv_get;
  7655. ++pool_stats->getwork_calls;
  7656. return work;
  7657. }
  7658. static
  7659. void _submit_work_async(struct work *work)
  7660. {
  7661. applog(LOG_DEBUG, "Pushing submit work to work thread");
  7662. mutex_lock(&submitting_lock);
  7663. ++total_submitting;
  7664. DL_APPEND(submit_waiting, work);
  7665. mutex_unlock(&submitting_lock);
  7666. notifier_wake(submit_waiting_notifier);
  7667. }
  7668. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  7669. static void submit_work_async2(struct work *work, struct timeval *tv_work_found)
  7670. {
  7671. if (tv_work_found)
  7672. copy_time(&work->tv_work_found, tv_work_found);
  7673. _submit_work_async(work);
  7674. }
  7675. void inc_hw_errors2(struct thr_info *thr, const struct work *work, const uint32_t *bad_nonce_p)
  7676. {
  7677. struct cgpu_info * const cgpu = thr->cgpu;
  7678. if (bad_nonce_p)
  7679. {
  7680. if (bad_nonce_p == UNKNOWN_NONCE)
  7681. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce - HW error",
  7682. cgpu->proc_repr);
  7683. else
  7684. applog(LOG_DEBUG, "%"PRIpreprv": invalid nonce (%08lx) - HW error",
  7685. cgpu->proc_repr, (unsigned long)be32toh(*bad_nonce_p));
  7686. }
  7687. mutex_lock(&stats_lock);
  7688. hw_errors++;
  7689. ++cgpu->hw_errors;
  7690. if (bad_nonce_p)
  7691. {
  7692. ++total_bad_nonces;
  7693. ++cgpu->bad_nonces;
  7694. }
  7695. mutex_unlock(&stats_lock);
  7696. if (thr->cgpu->drv->hw_error)
  7697. thr->cgpu->drv->hw_error(thr);
  7698. }
  7699. void inc_hw_errors(struct thr_info *thr, const struct work *work, const uint32_t bad_nonce)
  7700. {
  7701. inc_hw_errors2(thr, work, work ? &bad_nonce : NULL);
  7702. }
  7703. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  7704. {
  7705. uint32_t *hash2_32 = (uint32_t *)&work->hash[0];
  7706. hash_data(work->hash, work->data);
  7707. if (hash2_32[7] != 0)
  7708. return TNR_BAD;
  7709. if (!checktarget)
  7710. return TNR_GOOD;
  7711. if (!hash_target_check_v(work->hash, work->target))
  7712. return TNR_HIGH;
  7713. return TNR_GOOD;
  7714. }
  7715. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  7716. {
  7717. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7718. *work_nonce = htole32(nonce);
  7719. #ifdef USE_SCRYPT
  7720. if (opt_scrypt)
  7721. // NOTE: Depends on scrypt_test return matching enum values
  7722. return scrypt_test(work->data, work->target, nonce);
  7723. #endif
  7724. return hashtest2(work, checktarget);
  7725. }
  7726. /* Returns true if nonce for work was a valid share */
  7727. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  7728. {
  7729. return submit_noffset_nonce(thr, work, nonce, 0);
  7730. }
  7731. /* Allows drivers to submit work items where the driver has changed the ntime
  7732. * value by noffset. Must be only used with a work protocol that does not ntime
  7733. * roll itself intrinsically to generate work (eg stratum). We do not touch
  7734. * the original work struct, but the copy of it only. */
  7735. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  7736. int noffset)
  7737. {
  7738. struct work *work = make_work();
  7739. _copy_work(work, work_in, noffset);
  7740. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  7741. struct timeval tv_work_found;
  7742. enum test_nonce2_result res;
  7743. bool ret = true;
  7744. thread_reportout(thr);
  7745. cgtime(&tv_work_found);
  7746. *work_nonce = htole32(nonce);
  7747. work->thr_id = thr->id;
  7748. /* Do one last check before attempting to submit the work */
  7749. /* Side effect: sets work->data for us */
  7750. res = test_nonce2(work, nonce);
  7751. if (unlikely(res == TNR_BAD))
  7752. {
  7753. inc_hw_errors(thr, work, nonce);
  7754. ret = false;
  7755. goto out;
  7756. }
  7757. mutex_lock(&stats_lock);
  7758. total_diff1++;
  7759. thr->cgpu->diff1++;
  7760. work->pool->diff1++;
  7761. thr->cgpu->last_device_valid_work = time(NULL);
  7762. mutex_unlock(&stats_lock);
  7763. if (noncelog_file)
  7764. noncelog(work);
  7765. if (res == TNR_HIGH)
  7766. {
  7767. // Share above target, normal
  7768. /* Check the diff of the share, even if it didn't reach the
  7769. * target, just to set the best share value if it's higher. */
  7770. share_diff(work);
  7771. goto out;
  7772. }
  7773. submit_work_async2(work, &tv_work_found);
  7774. work = NULL; // Taken by submit_work_async2
  7775. out:
  7776. if (work)
  7777. free_work(work);
  7778. thread_reportin(thr);
  7779. return ret;
  7780. }
  7781. bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  7782. {
  7783. if (wdiff->tv_sec > opt_scantime ||
  7784. work->blk.nonce >= MAXTHREADS - hashes ||
  7785. hashes >= 0xfffffffe ||
  7786. stale_work(work, false))
  7787. return true;
  7788. return false;
  7789. }
  7790. void __thr_being_msg(int prio, struct thr_info *thr, const char *being)
  7791. {
  7792. struct cgpu_info *proc = thr->cgpu;
  7793. if (proc->threads > 1)
  7794. applog(prio, "%"PRIpreprv" (thread %d) %s", proc->proc_repr, thr->id, being);
  7795. else
  7796. applog(prio, "%"PRIpreprv" %s", proc->proc_repr, being);
  7797. }
  7798. // Called by asynchronous minerloops, when they find their processor should be disabled
  7799. void mt_disable_start(struct thr_info *mythr)
  7800. {
  7801. struct cgpu_info *cgpu = mythr->cgpu;
  7802. struct device_drv *drv = cgpu->drv;
  7803. if (drv->thread_disable)
  7804. drv->thread_disable(mythr);
  7805. hashmeter2(mythr);
  7806. if (mythr->prev_work)
  7807. free_work(mythr->prev_work);
  7808. mythr->prev_work = mythr->work;
  7809. mythr->work = NULL;
  7810. mythr->_job_transition_in_progress = false;
  7811. __thr_being_msg(LOG_WARNING, mythr, "being disabled");
  7812. mythr->rolling = mythr->cgpu->rolling = 0;
  7813. thread_reportout(mythr);
  7814. mythr->_mt_disable_called = true;
  7815. }
  7816. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  7817. * the driver tells us it's full so that it may extract the work item using
  7818. * the get_queued() function which adds it to the hashtable on
  7819. * cgpu->queued_work. */
  7820. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  7821. {
  7822. thread_reportout(mythr);
  7823. do {
  7824. bool need_work;
  7825. /* Do this lockless just to know if we need more unqueued work. */
  7826. need_work = (!cgpu->unqueued_work);
  7827. /* get_work is a blocking function so do it outside of lock
  7828. * to prevent deadlocks with other locks. */
  7829. if (need_work) {
  7830. struct work *work = get_work(mythr);
  7831. wr_lock(&cgpu->qlock);
  7832. /* Check we haven't grabbed work somehow between
  7833. * checking and picking up the lock. */
  7834. if (likely(!cgpu->unqueued_work))
  7835. cgpu->unqueued_work = work;
  7836. else
  7837. need_work = false;
  7838. wr_unlock(&cgpu->qlock);
  7839. if (unlikely(!need_work))
  7840. discard_work(work);
  7841. }
  7842. /* The queue_full function should be used by the driver to
  7843. * actually place work items on the physical device if it
  7844. * does have a queue. */
  7845. } while (drv->queue_full && !drv->queue_full(cgpu));
  7846. }
  7847. /* Add a work item to a cgpu's queued hashlist */
  7848. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  7849. {
  7850. cgpu->queued_count++;
  7851. HASH_ADD_INT(cgpu->queued_work, id, work);
  7852. }
  7853. /* This function is for retrieving one work item from the unqueued pointer and
  7854. * adding it to the hashtable of queued work. Code using this function must be
  7855. * able to handle NULL as a return which implies there is no work available. */
  7856. struct work *get_queued(struct cgpu_info *cgpu)
  7857. {
  7858. struct work *work = NULL;
  7859. wr_lock(&cgpu->qlock);
  7860. if (cgpu->unqueued_work) {
  7861. work = cgpu->unqueued_work;
  7862. __add_queued(cgpu, work);
  7863. cgpu->unqueued_work = NULL;
  7864. }
  7865. wr_unlock(&cgpu->qlock);
  7866. return work;
  7867. }
  7868. void add_queued(struct cgpu_info *cgpu, struct work *work)
  7869. {
  7870. wr_lock(&cgpu->qlock);
  7871. __add_queued(cgpu, work);
  7872. wr_unlock(&cgpu->qlock);
  7873. }
  7874. /* Get fresh work and add it to cgpu's queued hashlist */
  7875. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  7876. {
  7877. struct work *work = get_work(thr);
  7878. add_queued(cgpu, work);
  7879. return work;
  7880. }
  7881. /* This function is for finding an already queued work item in the
  7882. * given que hashtable. Code using this function must be able
  7883. * to handle NULL as a return which implies there is no matching work.
  7884. * The calling function must lock access to the que if it is required.
  7885. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7886. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7887. {
  7888. struct work *work, *tmp, *ret = NULL;
  7889. HASH_ITER(hh, que, work, tmp) {
  7890. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  7891. memcmp(work->data + offset, data, datalen) == 0) {
  7892. ret = work;
  7893. break;
  7894. }
  7895. }
  7896. return ret;
  7897. }
  7898. /* This function is for finding an already queued work item in the
  7899. * device's queued_work hashtable. Code using this function must be able
  7900. * to handle NULL as a return which implies there is no matching work.
  7901. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  7902. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7903. {
  7904. struct work *ret;
  7905. rd_lock(&cgpu->qlock);
  7906. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7907. rd_unlock(&cgpu->qlock);
  7908. return ret;
  7909. }
  7910. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7911. {
  7912. struct work *work, *ret = NULL;
  7913. rd_lock(&cgpu->qlock);
  7914. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7915. if (work)
  7916. ret = copy_work(work);
  7917. rd_unlock(&cgpu->qlock);
  7918. return ret;
  7919. }
  7920. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  7921. {
  7922. cgpu->queued_count--;
  7923. HASH_DEL(cgpu->queued_work, work);
  7924. }
  7925. /* This function should be used by queued device drivers when they're sure
  7926. * the work struct is no longer in use. */
  7927. void work_completed(struct cgpu_info *cgpu, struct work *work)
  7928. {
  7929. wr_lock(&cgpu->qlock);
  7930. __work_completed(cgpu, work);
  7931. wr_unlock(&cgpu->qlock);
  7932. free_work(work);
  7933. }
  7934. /* Combines find_queued_work_bymidstate and work_completed in one function
  7935. * withOUT destroying the work so the driver must free it. */
  7936. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  7937. {
  7938. struct work *work;
  7939. wr_lock(&cgpu->qlock);
  7940. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  7941. if (work)
  7942. __work_completed(cgpu, work);
  7943. wr_unlock(&cgpu->qlock);
  7944. return work;
  7945. }
  7946. static void flush_queue(struct cgpu_info *cgpu)
  7947. {
  7948. struct work *work = NULL;
  7949. wr_lock(&cgpu->qlock);
  7950. work = cgpu->unqueued_work;
  7951. cgpu->unqueued_work = NULL;
  7952. wr_unlock(&cgpu->qlock);
  7953. if (work) {
  7954. free_work(work);
  7955. applog(LOG_DEBUG, "Discarded queued work item");
  7956. }
  7957. }
  7958. /* This version of hash work is for devices that are fast enough to always
  7959. * perform a full nonce range and need a queue to maintain the device busy.
  7960. * Work creation and destruction is not done from within this function
  7961. * directly. */
  7962. void hash_queued_work(struct thr_info *mythr)
  7963. {
  7964. const long cycle = opt_log_interval / 5 ? : 1;
  7965. struct timeval tv_start = {0, 0}, tv_end;
  7966. struct cgpu_info *cgpu = mythr->cgpu;
  7967. struct device_drv *drv = cgpu->drv;
  7968. const int thr_id = mythr->id;
  7969. int64_t hashes_done = 0;
  7970. if (unlikely(cgpu->deven != DEV_ENABLED))
  7971. mt_disable(mythr);
  7972. while (likely(!cgpu->shutdown)) {
  7973. struct timeval diff;
  7974. int64_t hashes;
  7975. fill_queue(mythr, cgpu, drv, thr_id);
  7976. thread_reportin(mythr);
  7977. hashes = drv->scanwork(mythr);
  7978. /* Reset the bool here in case the driver looks for it
  7979. * synchronously in the scanwork loop. */
  7980. mythr->work_restart = false;
  7981. if (unlikely(hashes == -1 )) {
  7982. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  7983. cgpu->deven = DEV_DISABLED;
  7984. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  7985. mt_disable(mythr);
  7986. }
  7987. hashes_done += hashes;
  7988. cgtime(&tv_end);
  7989. timersub(&tv_end, &tv_start, &diff);
  7990. if (diff.tv_sec >= cycle) {
  7991. hashmeter(thr_id, &diff, hashes_done);
  7992. hashes_done = 0;
  7993. copy_time(&tv_start, &tv_end);
  7994. }
  7995. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  7996. mt_disable(mythr);
  7997. if (unlikely(mythr->work_restart)) {
  7998. flush_queue(cgpu);
  7999. if (drv->flush_work)
  8000. drv->flush_work(cgpu);
  8001. }
  8002. }
  8003. // cgpu->deven = DEV_DISABLED; set in miner_thread
  8004. }
  8005. // Called by minerloop, when it is re-enabling a processor
  8006. void mt_disable_finish(struct thr_info *mythr)
  8007. {
  8008. struct device_drv *drv = mythr->cgpu->drv;
  8009. thread_reportin(mythr);
  8010. __thr_being_msg(LOG_WARNING, mythr, "being re-enabled");
  8011. if (drv->thread_enable)
  8012. drv->thread_enable(mythr);
  8013. mythr->_mt_disable_called = false;
  8014. }
  8015. // Called by synchronous minerloops, when they find their processor should be disabled
  8016. // Calls mt_disable_start, waits until it's re-enabled, then calls mt_disable_finish
  8017. void mt_disable(struct thr_info *mythr)
  8018. {
  8019. const struct cgpu_info * const cgpu = mythr->cgpu;
  8020. mt_disable_start(mythr);
  8021. applog(LOG_DEBUG, "Waiting for wakeup notification in miner thread");
  8022. do {
  8023. notifier_read(mythr->notifier);
  8024. } while (mythr->pause || cgpu->deven != DEV_ENABLED);
  8025. mt_disable_finish(mythr);
  8026. }
  8027. enum {
  8028. STAT_SLEEP_INTERVAL = 1,
  8029. STAT_CTR_INTERVAL = 10000000,
  8030. FAILURE_INTERVAL = 30,
  8031. };
  8032. /* Stage another work item from the work returned in a longpoll */
  8033. 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)
  8034. {
  8035. bool rc;
  8036. work->rolltime = rolltime;
  8037. rc = work_decode(pool, work, val);
  8038. if (unlikely(!rc)) {
  8039. applog(LOG_ERR, "Could not convert longpoll data to work");
  8040. free_work(work);
  8041. return;
  8042. }
  8043. total_getworks++;
  8044. pool->getwork_requested++;
  8045. work->pool = pool;
  8046. copy_time(&work->tv_getwork, tv_lp);
  8047. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  8048. calc_diff(work, 0);
  8049. if (pool->enabled == POOL_REJECTING)
  8050. work->mandatory = true;
  8051. work->longpoll = true;
  8052. work->getwork_mode = GETWORK_MODE_LP;
  8053. update_last_work(work);
  8054. /* We'll be checking this work item twice, but we already know it's
  8055. * from a new block so explicitly force the new block detection now
  8056. * rather than waiting for it to hit the stage thread. This also
  8057. * allows testwork to know whether LP discovered the block or not. */
  8058. test_work_current(work);
  8059. /* Don't use backup LPs as work if we have failover-only enabled. Use
  8060. * the longpoll work from a pool that has been rejecting shares as a
  8061. * way to detect when the pool has recovered.
  8062. */
  8063. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  8064. free_work(work);
  8065. return;
  8066. }
  8067. work = clone_work(work);
  8068. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  8069. stage_work(work);
  8070. applog(LOG_DEBUG, "Converted longpoll data to work");
  8071. }
  8072. /* If we want longpoll, enable it for the chosen default pool, or, if
  8073. * the pool does not support longpoll, find the first one that does
  8074. * and use its longpoll support */
  8075. static struct pool *select_longpoll_pool(struct pool *cp)
  8076. {
  8077. int i;
  8078. if (cp->lp_url)
  8079. return cp;
  8080. for (i = 0; i < total_pools; i++) {
  8081. struct pool *pool = pools[i];
  8082. if (pool->has_stratum || pool->lp_url)
  8083. return pool;
  8084. }
  8085. return NULL;
  8086. }
  8087. /* This will make the longpoll thread wait till it's the current pool, or it
  8088. * has been flagged as rejecting, before attempting to open any connections.
  8089. */
  8090. static void wait_lpcurrent(struct pool *pool)
  8091. {
  8092. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  8093. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  8094. pool_strategy != POOL_BALANCE))) {
  8095. mutex_lock(&lp_lock);
  8096. pthread_cond_wait(&lp_cond, &lp_lock);
  8097. mutex_unlock(&lp_lock);
  8098. }
  8099. }
  8100. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  8101. struct pool *pool = vpool;
  8102. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  8103. pool->lp_socket = sock;
  8104. return sock;
  8105. }
  8106. static void *longpoll_thread(void *userdata)
  8107. {
  8108. struct pool *cp = (struct pool *)userdata;
  8109. /* This *pool is the source of the actual longpoll, not the pool we've
  8110. * tied it to */
  8111. struct timeval start, reply, end;
  8112. struct pool *pool = NULL;
  8113. char threadname[20];
  8114. CURL *curl = NULL;
  8115. int failures = 0;
  8116. char *lp_url;
  8117. int rolltime;
  8118. #ifndef HAVE_PTHREAD_CANCEL
  8119. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8120. #endif
  8121. snprintf(threadname, 20, "longpoll%u", cp->pool_no);
  8122. RenameThread(threadname);
  8123. curl = curl_easy_init();
  8124. if (unlikely(!curl)) {
  8125. applog(LOG_ERR, "CURL initialisation failed");
  8126. return NULL;
  8127. }
  8128. retry_pool:
  8129. pool = select_longpoll_pool(cp);
  8130. if (!pool) {
  8131. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  8132. while (!pool) {
  8133. cgsleep_ms(60000);
  8134. pool = select_longpoll_pool(cp);
  8135. }
  8136. }
  8137. if (pool->has_stratum) {
  8138. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8139. cp->rpc_url, pool->rpc_url);
  8140. goto out;
  8141. }
  8142. /* Any longpoll from any pool is enough for this to be true */
  8143. have_longpoll = true;
  8144. wait_lpcurrent(cp);
  8145. {
  8146. lp_url = pool->lp_url;
  8147. if (cp == pool)
  8148. applog(LOG_WARNING, "Long-polling activated for %s (%s)", lp_url, pool_protocol_name(pool->lp_proto));
  8149. else
  8150. applog(LOG_WARNING, "Long-polling activated for %s via %s (%s)", cp->rpc_url, lp_url, pool_protocol_name(pool->lp_proto));
  8151. }
  8152. while (42) {
  8153. json_t *val, *soval;
  8154. struct work *work = make_work();
  8155. char *lpreq;
  8156. lpreq = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  8157. work->pool = pool;
  8158. if (!lpreq)
  8159. {
  8160. free_work(work);
  8161. goto lpfail;
  8162. }
  8163. wait_lpcurrent(cp);
  8164. cgtime(&start);
  8165. /* Longpoll connections can be persistent for a very long time
  8166. * and any number of issues could have come up in the meantime
  8167. * so always establish a fresh connection instead of relying on
  8168. * a persistent one. */
  8169. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  8170. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  8171. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  8172. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  8173. lpreq, false, true, &rolltime, pool, false);
  8174. pool->lp_socket = CURL_SOCKET_BAD;
  8175. cgtime(&reply);
  8176. free(lpreq);
  8177. if (likely(val)) {
  8178. soval = json_object_get(json_object_get(val, "result"), "submitold");
  8179. if (soval)
  8180. pool->submit_old = json_is_true(soval);
  8181. else
  8182. pool->submit_old = false;
  8183. convert_to_work(val, rolltime, pool, work, &start, &reply);
  8184. failures = 0;
  8185. json_decref(val);
  8186. } else {
  8187. /* Some pools regularly drop the longpoll request so
  8188. * only see this as longpoll failure if it happens
  8189. * immediately and just restart it the rest of the
  8190. * time. */
  8191. cgtime(&end);
  8192. free_work(work);
  8193. if (end.tv_sec - start.tv_sec > 30)
  8194. continue;
  8195. if (failures == 1)
  8196. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  8197. lpfail:
  8198. cgsleep_ms(30000);
  8199. }
  8200. if (pool != cp) {
  8201. pool = select_longpoll_pool(cp);
  8202. if (pool->has_stratum) {
  8203. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  8204. cp->rpc_url, pool->rpc_url);
  8205. break;
  8206. }
  8207. if (unlikely(!pool))
  8208. goto retry_pool;
  8209. }
  8210. if (unlikely(pool->removed))
  8211. break;
  8212. }
  8213. out:
  8214. curl_easy_cleanup(curl);
  8215. return NULL;
  8216. }
  8217. static void stop_longpoll(void)
  8218. {
  8219. int i;
  8220. want_longpoll = false;
  8221. for (i = 0; i < total_pools; ++i)
  8222. {
  8223. struct pool *pool = pools[i];
  8224. if (unlikely(!pool->lp_started))
  8225. continue;
  8226. pool->lp_started = false;
  8227. pthread_cancel(pool->longpoll_thread);
  8228. }
  8229. have_longpoll = false;
  8230. }
  8231. static void start_longpoll(void)
  8232. {
  8233. int i;
  8234. want_longpoll = true;
  8235. for (i = 0; i < total_pools; ++i)
  8236. {
  8237. struct pool *pool = pools[i];
  8238. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  8239. continue;
  8240. pool->lp_started = true;
  8241. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  8242. quit(1, "Failed to create pool longpoll thread");
  8243. }
  8244. }
  8245. void reinit_device(struct cgpu_info *cgpu)
  8246. {
  8247. if (cgpu->drv->reinit_device)
  8248. cgpu->drv->reinit_device(cgpu);
  8249. }
  8250. static struct timeval rotate_tv;
  8251. /* We reap curls if they are unused for over a minute */
  8252. static void reap_curl(struct pool *pool)
  8253. {
  8254. struct curl_ent *ent, *iter;
  8255. struct timeval now;
  8256. int reaped = 0;
  8257. cgtime(&now);
  8258. mutex_lock(&pool->pool_lock);
  8259. LL_FOREACH_SAFE(pool->curllist, ent, iter) {
  8260. if (pool->curls < 2)
  8261. break;
  8262. if (now.tv_sec - ent->tv.tv_sec > 300) {
  8263. reaped++;
  8264. pool->curls--;
  8265. LL_DELETE(pool->curllist, ent);
  8266. curl_easy_cleanup(ent->curl);
  8267. free(ent);
  8268. }
  8269. }
  8270. mutex_unlock(&pool->pool_lock);
  8271. if (reaped)
  8272. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  8273. }
  8274. static void *watchpool_thread(void __maybe_unused *userdata)
  8275. {
  8276. int intervals = 0;
  8277. #ifndef HAVE_PTHREAD_CANCEL
  8278. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8279. #endif
  8280. RenameThread("watchpool");
  8281. while (42) {
  8282. struct timeval now;
  8283. int i;
  8284. if (++intervals > 20)
  8285. intervals = 0;
  8286. cgtime(&now);
  8287. for (i = 0; i < total_pools; i++) {
  8288. struct pool *pool = pools[i];
  8289. if (!opt_benchmark)
  8290. reap_curl(pool);
  8291. /* Get a rolling utility per pool over 10 mins */
  8292. if (intervals > 19) {
  8293. int shares = pool->diff1 - pool->last_shares;
  8294. pool->last_shares = pool->diff1;
  8295. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  8296. pool->shares = pool->utility;
  8297. }
  8298. if (pool->enabled == POOL_DISABLED)
  8299. continue;
  8300. /* Don't start testing any pools if the test threads
  8301. * from startup are still doing their first attempt. */
  8302. if (unlikely(pool->testing)) {
  8303. pthread_join(pool->test_thread, NULL);
  8304. }
  8305. /* Test pool is idle once every minute */
  8306. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  8307. cgtime(&pool->tv_idle);
  8308. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  8309. pool_resus(pool);
  8310. }
  8311. /* Only switch pools if the failback pool has been
  8312. * alive for more than 5 minutes to prevent
  8313. * intermittently failing pools from being used. */
  8314. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  8315. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  8316. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  8317. pool->pool_no, pool->rpc_url);
  8318. switch_pools(NULL);
  8319. }
  8320. }
  8321. if (current_pool()->idle)
  8322. switch_pools(NULL);
  8323. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  8324. cgtime(&rotate_tv);
  8325. switch_pools(NULL);
  8326. }
  8327. cgsleep_ms(30000);
  8328. }
  8329. return NULL;
  8330. }
  8331. void mt_enable(struct thr_info *thr)
  8332. {
  8333. applog(LOG_DEBUG, "Waking up thread %d", thr->id);
  8334. notifier_wake(thr->notifier);
  8335. }
  8336. void proc_enable(struct cgpu_info *cgpu)
  8337. {
  8338. int j;
  8339. cgpu->deven = DEV_ENABLED;
  8340. for (j = cgpu->threads ?: 1; j--; )
  8341. mt_enable(cgpu->thr[j]);
  8342. }
  8343. #define device_recovered(cgpu) proc_enable(cgpu)
  8344. void cgpu_set_defaults(struct cgpu_info * const cgpu)
  8345. {
  8346. const struct device_drv * const drv = cgpu->drv;
  8347. struct string_elist *setstr_elist;
  8348. const char *p, *p2;
  8349. char replybuf[0x2000];
  8350. size_t L;
  8351. DL_FOREACH(opt_set_device_list, setstr_elist)
  8352. {
  8353. const char * const setstr = setstr_elist->string;
  8354. p = strchr(setstr, ':');
  8355. if (!p)
  8356. p = setstr;
  8357. {
  8358. L = p - setstr;
  8359. char pattern[L + 1];
  8360. if (L)
  8361. memcpy(pattern, setstr, L);
  8362. pattern[L] = '\0';
  8363. if (!cgpu_match(pattern, cgpu))
  8364. continue;
  8365. }
  8366. applog(LOG_DEBUG, "%"PRIpreprv": %s: Matched with set default: %s",
  8367. cgpu->proc_repr, __func__, setstr);
  8368. if (!drv->set_device)
  8369. {
  8370. applog(LOG_WARNING, "%"PRIpreprv": set_device is not implemented (trying to apply rule: %s)",
  8371. cgpu->proc_repr, setstr);
  8372. continue;
  8373. }
  8374. if (p[0] == ':')
  8375. ++p;
  8376. p2 = strchr(p, '=');
  8377. if (!p2)
  8378. {
  8379. L = strlen(p);
  8380. p2 = "";
  8381. }
  8382. else
  8383. {
  8384. L = p2 - p;
  8385. ++p2;
  8386. }
  8387. char opt[L + 1];
  8388. if (L)
  8389. memcpy(opt, p, L);
  8390. opt[L] = '\0';
  8391. L = strlen(p2);
  8392. char setval[L + 1];
  8393. if (L)
  8394. memcpy(setval, p2, L);
  8395. setval[L] = '\0';
  8396. p = drv->set_device(cgpu, opt, setval, replybuf);
  8397. if (p)
  8398. applog(LOG_WARNING, "%"PRIpreprv": Applying rule %s: %s",
  8399. cgpu->proc_repr, setstr, p);
  8400. else
  8401. applog(LOG_DEBUG, "%"PRIpreprv": Applied rule %s",
  8402. cgpu->proc_repr, setstr);
  8403. }
  8404. cgpu->already_set_defaults = true;
  8405. }
  8406. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  8407. * the screen at regular intervals, and restarts threads if they appear to have
  8408. * died. */
  8409. #define WATCHDOG_SICK_TIME 60
  8410. #define WATCHDOG_DEAD_TIME 600
  8411. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  8412. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  8413. static void *watchdog_thread(void __maybe_unused *userdata)
  8414. {
  8415. const unsigned int interval = WATCHDOG_INTERVAL;
  8416. struct timeval zero_tv;
  8417. #ifndef HAVE_PTHREAD_CANCEL
  8418. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8419. #endif
  8420. RenameThread("watchdog");
  8421. memset(&zero_tv, 0, sizeof(struct timeval));
  8422. cgtime(&rotate_tv);
  8423. while (1) {
  8424. int i;
  8425. struct timeval now;
  8426. sleep(interval);
  8427. discard_stale();
  8428. hashmeter(-1, &zero_tv, 0);
  8429. #ifdef HAVE_CURSES
  8430. const int ts = total_staged();
  8431. if (curses_active_locked()) {
  8432. change_logwinsize();
  8433. curses_print_status(ts);
  8434. for (i = 0; i < total_devices; i++)
  8435. curses_print_devstatus(get_devices(i));
  8436. touchwin(statuswin);
  8437. wrefresh(statuswin);
  8438. touchwin(logwin);
  8439. wrefresh(logwin);
  8440. unlock_curses();
  8441. }
  8442. #endif
  8443. cgtime(&now);
  8444. if (!sched_paused && !should_run()) {
  8445. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  8446. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8447. if (!schedstart.enable) {
  8448. quit(0, "Terminating execution as planned");
  8449. break;
  8450. }
  8451. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  8452. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8453. sched_paused = true;
  8454. rd_lock(&mining_thr_lock);
  8455. for (i = 0; i < mining_threads; i++)
  8456. mining_thr[i]->pause = true;
  8457. rd_unlock(&mining_thr_lock);
  8458. } else if (sched_paused && should_run()) {
  8459. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  8460. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  8461. if (schedstop.enable)
  8462. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  8463. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  8464. sched_paused = false;
  8465. for (i = 0; i < mining_threads; i++) {
  8466. struct thr_info *thr;
  8467. thr = get_thread(i);
  8468. thr->pause = false;
  8469. }
  8470. for (i = 0; i < total_devices; ++i)
  8471. {
  8472. struct cgpu_info *cgpu = get_devices(i);
  8473. /* Don't touch disabled devices */
  8474. if (cgpu->deven == DEV_DISABLED)
  8475. continue;
  8476. proc_enable(cgpu);
  8477. }
  8478. }
  8479. for (i = 0; i < total_devices; ++i) {
  8480. struct cgpu_info *cgpu = get_devices(i);
  8481. if (!cgpu->disable_watchdog)
  8482. bfg_watchdog(cgpu, &now);
  8483. }
  8484. }
  8485. return NULL;
  8486. }
  8487. void bfg_watchdog(struct cgpu_info * const cgpu, struct timeval * const tvp_now)
  8488. {
  8489. struct thr_info *thr = cgpu->thr[0];
  8490. enum dev_enable *denable;
  8491. char *dev_str = cgpu->proc_repr;
  8492. int gpu;
  8493. if (likely(drv_ready(cgpu)))
  8494. {
  8495. if (unlikely(!cgpu->already_set_defaults))
  8496. cgpu_set_defaults(cgpu);
  8497. if (cgpu->drv->get_stats)
  8498. cgpu->drv->get_stats(cgpu);
  8499. }
  8500. gpu = cgpu->device_id;
  8501. denable = &cgpu->deven;
  8502. #ifdef HAVE_ADL
  8503. if (adl_active && cgpu->has_adl)
  8504. gpu_autotune(gpu, denable);
  8505. if (opt_debug && cgpu->has_adl) {
  8506. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  8507. float temp = 0, vddc = 0;
  8508. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  8509. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMHz V: %.3fV A: %d%% P: %d%%",
  8510. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  8511. }
  8512. #endif
  8513. /* Thread is disabled */
  8514. if (*denable == DEV_DISABLED)
  8515. return;
  8516. else
  8517. if (*denable == DEV_RECOVER_ERR) {
  8518. if (opt_restart && timer_elapsed(&cgpu->tv_device_last_not_well, NULL) > cgpu->reinit_backoff) {
  8519. applog(LOG_NOTICE, "Attempting to reinitialize %s",
  8520. dev_str);
  8521. if (cgpu->reinit_backoff < 300)
  8522. cgpu->reinit_backoff *= 2;
  8523. device_recovered(cgpu);
  8524. }
  8525. return;
  8526. }
  8527. else
  8528. if (*denable == DEV_RECOVER) {
  8529. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  8530. applog(LOG_NOTICE, "%s recovered to temperature below target, re-enabling",
  8531. dev_str);
  8532. device_recovered(cgpu);
  8533. }
  8534. dev_error_update(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8535. return;
  8536. }
  8537. else
  8538. if (cgpu->temp > cgpu->cutofftemp)
  8539. {
  8540. applog(LOG_WARNING, "%s hit thermal cutoff limit, disabling!",
  8541. dev_str);
  8542. *denable = DEV_RECOVER;
  8543. dev_error(cgpu, REASON_DEV_THERMAL_CUTOFF);
  8544. run_cmd(cmd_idle);
  8545. }
  8546. if (thr->getwork) {
  8547. if (cgpu->status == LIFE_WELL && thr->getwork < tvp_now->tv_sec - opt_log_interval) {
  8548. int thrid;
  8549. bool cgpu_idle = true;
  8550. thr->rolling = 0;
  8551. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  8552. if (!cgpu->thr[thrid]->getwork)
  8553. cgpu_idle = false;
  8554. if (cgpu_idle) {
  8555. cgpu->rolling = 0;
  8556. cgpu->status = LIFE_WAIT;
  8557. }
  8558. }
  8559. return;
  8560. }
  8561. else if (cgpu->status == LIFE_WAIT)
  8562. cgpu->status = LIFE_WELL;
  8563. #ifdef WANT_CPUMINE
  8564. if (!strcmp(cgpu->drv->dname, "cpu"))
  8565. return;
  8566. #endif
  8567. if (cgpu->status != LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  8568. if (likely(cgpu->status != LIFE_INIT && cgpu->status != LIFE_INIT2))
  8569. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  8570. cgpu->status = LIFE_WELL;
  8571. cgpu->device_last_well = time(NULL);
  8572. } else if (cgpu->status == LIFE_WELL && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  8573. thr->rolling = cgpu->rolling = 0;
  8574. cgpu->status = LIFE_SICK;
  8575. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  8576. cgtime(&thr->sick);
  8577. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  8578. run_cmd(cmd_sick);
  8579. #ifdef HAVE_ADL
  8580. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8581. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  8582. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  8583. } else
  8584. #endif
  8585. if (opt_restart && cgpu->drv->reinit_device) {
  8586. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  8587. reinit_device(cgpu);
  8588. }
  8589. } else if (cgpu->status == LIFE_SICK && (tvp_now->tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  8590. cgpu->status = LIFE_DEAD;
  8591. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  8592. cgtime(&thr->sick);
  8593. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  8594. run_cmd(cmd_dead);
  8595. } else if (tvp_now->tv_sec - thr->sick.tv_sec > 60 &&
  8596. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  8597. /* Attempt to restart a GPU that's sick or dead once every minute */
  8598. cgtime(&thr->sick);
  8599. #ifdef HAVE_ADL
  8600. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  8601. /* Again do not attempt to restart a device that may have hard hung */
  8602. } else
  8603. #endif
  8604. if (opt_restart)
  8605. reinit_device(cgpu);
  8606. }
  8607. }
  8608. static void log_print_status(struct cgpu_info *cgpu)
  8609. {
  8610. char logline[255];
  8611. get_statline(logline, sizeof(logline), cgpu);
  8612. applog(LOG_WARNING, "%s", logline);
  8613. }
  8614. void print_summary(void)
  8615. {
  8616. struct timeval diff;
  8617. int hours, mins, secs, i;
  8618. double utility, efficiency = 0.0;
  8619. char xfer[17], bw[19];
  8620. int pool_secs;
  8621. timersub(&total_tv_end, &total_tv_start, &diff);
  8622. hours = diff.tv_sec / 3600;
  8623. mins = (diff.tv_sec % 3600) / 60;
  8624. secs = diff.tv_sec % 60;
  8625. utility = total_accepted / total_secs * 60;
  8626. efficiency = total_bytes_xfer ? total_diff_accepted * 2048. / total_bytes_xfer : 0.0;
  8627. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  8628. applog(LOG_WARNING, "Started at %s", datestamp);
  8629. if (total_pools == 1)
  8630. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  8631. #ifdef WANT_CPUMINE
  8632. if (opt_n_threads)
  8633. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  8634. #endif
  8635. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  8636. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  8637. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  8638. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  8639. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  8640. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  8641. applog(LOG_WARNING, "Rejected shares: %d + %d stale (%.2f%%)",
  8642. total_rejected, total_stale,
  8643. (float)(total_rejected + total_stale) / (float)(total_rejected + total_stale + total_accepted)
  8644. );
  8645. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  8646. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  8647. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  8648. applog(LOG_WARNING, "Network transfer: %s (%s)",
  8649. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8650. (float)total_bytes_rcvd,
  8651. (float)total_bytes_sent),
  8652. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8653. (float)(total_bytes_rcvd / total_secs),
  8654. (float)(total_bytes_sent / total_secs)));
  8655. applog(LOG_WARNING, "Efficiency (accepted shares * difficulty / 2 KB): %.2f", efficiency);
  8656. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  8657. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  8658. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  8659. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  8660. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  8661. if (total_pools > 1) {
  8662. for (i = 0; i < total_pools; i++) {
  8663. struct pool *pool = pools[i];
  8664. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  8665. if (pool->solved)
  8666. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  8667. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  8668. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  8669. applog(LOG_WARNING, " Rejected shares: %d + %d stale (%.2f%%)",
  8670. pool->rejected, pool->stale_shares,
  8671. (float)(pool->rejected + pool->stale_shares) / (float)(pool->rejected + pool->stale_shares + pool->accepted)
  8672. );
  8673. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  8674. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  8675. pool_secs = timer_elapsed(&pool->cgminer_stats.start_tv, NULL);
  8676. applog(LOG_WARNING, " Network transfer: %s (%s)",
  8677. multi_format_unit2(xfer, sizeof(xfer), true, "B", H2B_SPACED, " / ", 2,
  8678. (float)pool->cgminer_pool_stats.net_bytes_received,
  8679. (float)pool->cgminer_pool_stats.net_bytes_sent),
  8680. multi_format_unit2(bw, sizeof(bw), true, "B/s", H2B_SPACED, " / ", 2,
  8681. (float)(pool->cgminer_pool_stats.net_bytes_received / pool_secs),
  8682. (float)(pool->cgminer_pool_stats.net_bytes_sent / pool_secs)));
  8683. uint64_t pool_bytes_xfer = pool->cgminer_pool_stats.net_bytes_received + pool->cgminer_pool_stats.net_bytes_sent;
  8684. efficiency = pool_bytes_xfer ? pool->diff_accepted * 2048. / pool_bytes_xfer : 0.0;
  8685. applog(LOG_WARNING, " Efficiency (accepted * difficulty / 2 KB): %.2f", efficiency);
  8686. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  8687. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  8688. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  8689. }
  8690. }
  8691. applog(LOG_WARNING, "Summary of per device statistics:\n");
  8692. for (i = 0; i < total_devices; ++i) {
  8693. struct cgpu_info *cgpu = get_devices(i);
  8694. if ((!cgpu->proc_id) && cgpu->procs > 1)
  8695. {
  8696. // Device summary line
  8697. opt_show_procs = false;
  8698. log_print_status(cgpu);
  8699. opt_show_procs = true;
  8700. }
  8701. log_print_status(cgpu);
  8702. }
  8703. if (opt_shares) {
  8704. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  8705. if (opt_shares > total_diff_accepted)
  8706. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  8707. }
  8708. applog(LOG_WARNING, " ");
  8709. fflush(stderr);
  8710. fflush(stdout);
  8711. }
  8712. void _bfg_clean_up(bool restarting)
  8713. {
  8714. #ifdef HAVE_OPENCL
  8715. clear_adl(nDevs);
  8716. #endif
  8717. #ifdef HAVE_LIBUSB
  8718. if (likely(have_libusb))
  8719. libusb_exit(NULL);
  8720. #endif
  8721. cgtime(&total_tv_end);
  8722. #ifdef WIN32
  8723. timeEndPeriod(1);
  8724. #endif
  8725. if (!restarting) {
  8726. /* Attempting to disable curses or print a summary during a
  8727. * restart can lead to a deadlock. */
  8728. #ifdef HAVE_CURSES
  8729. disable_curses();
  8730. #endif
  8731. if (!opt_realquiet && successful_connect)
  8732. print_summary();
  8733. }
  8734. if (opt_n_threads)
  8735. free(cpus);
  8736. curl_global_cleanup();
  8737. #ifdef WIN32
  8738. WSACleanup();
  8739. #endif
  8740. }
  8741. void _quit(int status)
  8742. {
  8743. if (status) {
  8744. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  8745. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  8746. int *p = NULL;
  8747. // NOTE debugger can bypass with: p = &p
  8748. *p = status; // Segfault, hopefully dumping core
  8749. }
  8750. }
  8751. #if defined(unix) || defined(__APPLE__)
  8752. if (forkpid > 0) {
  8753. kill(forkpid, SIGTERM);
  8754. forkpid = 0;
  8755. }
  8756. #endif
  8757. exit(status);
  8758. }
  8759. #ifdef HAVE_CURSES
  8760. char *curses_input(const char *query)
  8761. {
  8762. char *input;
  8763. echo();
  8764. input = malloc(255);
  8765. if (!input)
  8766. quit(1, "Failed to malloc input");
  8767. leaveok(logwin, false);
  8768. wlogprint("%s:\n", query);
  8769. wgetnstr(logwin, input, 255);
  8770. if (!strlen(input))
  8771. {
  8772. free(input);
  8773. input = NULL;
  8774. }
  8775. leaveok(logwin, true);
  8776. noecho();
  8777. return input;
  8778. }
  8779. #endif
  8780. static bool pools_active = false;
  8781. static void *test_pool_thread(void *arg)
  8782. {
  8783. struct pool *pool = (struct pool *)arg;
  8784. if (pool_active(pool, false)) {
  8785. pool_tset(pool, &pool->lagging);
  8786. pool_tclear(pool, &pool->idle);
  8787. bool first_pool = false;
  8788. cg_wlock(&control_lock);
  8789. if (!pools_active) {
  8790. currentpool = pool;
  8791. if (pool->pool_no != 0)
  8792. first_pool = true;
  8793. pools_active = true;
  8794. }
  8795. cg_wunlock(&control_lock);
  8796. if (unlikely(first_pool))
  8797. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  8798. else
  8799. applog(LOG_NOTICE, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  8800. switch_pools(NULL);
  8801. } else
  8802. pool_died(pool);
  8803. pool->testing = false;
  8804. return NULL;
  8805. }
  8806. /* Always returns true that the pool details were added unless we are not
  8807. * live, implying this is the only pool being added, so if no pools are
  8808. * active it returns false. */
  8809. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  8810. {
  8811. size_t siz;
  8812. pool->rpc_url = url;
  8813. pool->rpc_user = user;
  8814. pool->rpc_pass = pass;
  8815. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8816. pool->rpc_userpass = malloc(siz);
  8817. if (!pool->rpc_userpass)
  8818. quit(1, "Failed to malloc userpass");
  8819. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8820. pool->testing = true;
  8821. pool->idle = true;
  8822. enable_pool(pool);
  8823. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8824. if (!live) {
  8825. pthread_join(pool->test_thread, NULL);
  8826. return pools_active;
  8827. }
  8828. return true;
  8829. }
  8830. #ifdef HAVE_CURSES
  8831. static bool input_pool(bool live)
  8832. {
  8833. char *url = NULL, *user = NULL, *pass = NULL;
  8834. struct pool *pool;
  8835. bool ret = false;
  8836. immedok(logwin, true);
  8837. wlogprint("Input server details.\n");
  8838. url = curses_input("URL");
  8839. if (!url)
  8840. goto out;
  8841. user = curses_input("Username");
  8842. if (!user)
  8843. goto out;
  8844. pass = curses_input("Password");
  8845. if (!pass)
  8846. pass = calloc(1, 1);
  8847. pool = add_pool();
  8848. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  8849. strncmp(url, "https://", 8)) {
  8850. char *httpinput;
  8851. httpinput = malloc(256);
  8852. if (!httpinput)
  8853. quit(1, "Failed to malloc httpinput");
  8854. strcpy(httpinput, "http://");
  8855. strncat(httpinput, url, 248);
  8856. free(url);
  8857. url = httpinput;
  8858. }
  8859. ret = add_pool_details(pool, live, url, user, pass);
  8860. out:
  8861. immedok(logwin, false);
  8862. if (!ret) {
  8863. if (url)
  8864. free(url);
  8865. if (user)
  8866. free(user);
  8867. if (pass)
  8868. free(pass);
  8869. }
  8870. return ret;
  8871. }
  8872. #endif
  8873. #if defined(unix) || defined(__APPLE__)
  8874. static void fork_monitor()
  8875. {
  8876. // Make a pipe: [readFD, writeFD]
  8877. int pfd[2];
  8878. int r = pipe(pfd);
  8879. if (r < 0) {
  8880. perror("pipe - failed to create pipe for --monitor");
  8881. exit(1);
  8882. }
  8883. // Make stderr write end of pipe
  8884. fflush(stderr);
  8885. r = dup2(pfd[1], 2);
  8886. if (r < 0) {
  8887. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  8888. exit(1);
  8889. }
  8890. r = close(pfd[1]);
  8891. if (r < 0) {
  8892. perror("close - failed to close write end of pipe for --monitor");
  8893. exit(1);
  8894. }
  8895. // Don't allow a dying monitor to kill the main process
  8896. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  8897. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  8898. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  8899. perror("signal - failed to edit signal mask for --monitor");
  8900. exit(1);
  8901. }
  8902. // Fork a child process
  8903. forkpid = fork();
  8904. if (forkpid < 0) {
  8905. perror("fork - failed to fork child process for --monitor");
  8906. exit(1);
  8907. }
  8908. // Child: launch monitor command
  8909. if (0 == forkpid) {
  8910. // Make stdin read end of pipe
  8911. r = dup2(pfd[0], 0);
  8912. if (r < 0) {
  8913. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  8914. exit(1);
  8915. }
  8916. close(pfd[0]);
  8917. if (r < 0) {
  8918. perror("close - in child, failed to close read end of pipe for --monitor");
  8919. exit(1);
  8920. }
  8921. // Launch user specified command
  8922. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  8923. perror("execl - in child failed to exec user specified command for --monitor");
  8924. exit(1);
  8925. }
  8926. // Parent: clean up unused fds and bail
  8927. r = close(pfd[0]);
  8928. if (r < 0) {
  8929. perror("close - failed to close read end of pipe for --monitor");
  8930. exit(1);
  8931. }
  8932. }
  8933. #endif // defined(unix)
  8934. #ifdef HAVE_CURSES
  8935. #ifdef USE_UNICODE
  8936. static
  8937. wchar_t select_unicode_char(const wchar_t *opt)
  8938. {
  8939. for ( ; *opt; ++opt)
  8940. if (iswprint(*opt))
  8941. return *opt;
  8942. return '?';
  8943. }
  8944. #endif
  8945. void enable_curses(void) {
  8946. int x;
  8947. __maybe_unused int y;
  8948. lock_curses();
  8949. if (curses_active) {
  8950. unlock_curses();
  8951. return;
  8952. }
  8953. #ifdef USE_UNICODE
  8954. if (use_unicode)
  8955. {
  8956. setlocale(LC_CTYPE, "");
  8957. if (iswprint(0xb0))
  8958. have_unicode_degrees = true;
  8959. unicode_micro = select_unicode_char(L"\xb5\u03bcu");
  8960. }
  8961. #endif
  8962. mainwin = initscr();
  8963. start_color();
  8964. #if defined(PDCURSES) || defined(NCURSES_VERSION)
  8965. if (ERR != use_default_colors())
  8966. default_bgcolor = -1;
  8967. #endif
  8968. if (has_colors() && ERR != init_pair(1, COLOR_WHITE, COLOR_BLUE))
  8969. {
  8970. menu_attr = COLOR_PAIR(1);
  8971. if (ERR != init_pair(2, COLOR_RED, default_bgcolor))
  8972. attr_bad |= COLOR_PAIR(2);
  8973. }
  8974. keypad(mainwin, true);
  8975. getmaxyx(mainwin, y, x);
  8976. statuswin = newwin(logstart, x, 0, 0);
  8977. leaveok(statuswin, true);
  8978. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  8979. // We resize the window later anyway, so just start it off at 1 :)
  8980. logwin = newwin(1, 0, logcursor, 0);
  8981. idlok(logwin, true);
  8982. scrollok(logwin, true);
  8983. leaveok(logwin, true);
  8984. cbreak();
  8985. noecho();
  8986. nonl();
  8987. curses_active = true;
  8988. statusy = logstart;
  8989. unlock_curses();
  8990. }
  8991. #endif
  8992. /* TODO: fix need a dummy CPU device_drv even if no support for CPU mining */
  8993. #ifndef WANT_CPUMINE
  8994. struct device_drv cpu_drv;
  8995. struct device_drv cpu_drv = {
  8996. .name = "CPU",
  8997. };
  8998. #endif
  8999. static int cgminer_id_count = 0;
  9000. static int device_line_id_count;
  9001. void register_device(struct cgpu_info *cgpu)
  9002. {
  9003. cgpu->deven = DEV_ENABLED;
  9004. wr_lock(&devices_lock);
  9005. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  9006. wr_unlock(&devices_lock);
  9007. if (!cgpu->proc_id)
  9008. cgpu->device_line_id = device_line_id_count++;
  9009. mining_threads += cgpu->threads ?: 1;
  9010. #ifdef HAVE_CURSES
  9011. adj_width(mining_threads, &dev_width);
  9012. #endif
  9013. rwlock_init(&cgpu->qlock);
  9014. cgpu->queued_work = NULL;
  9015. }
  9016. struct _cgpu_devid_counter {
  9017. char name[4];
  9018. int lastid;
  9019. UT_hash_handle hh;
  9020. };
  9021. void renumber_cgpu(struct cgpu_info *cgpu)
  9022. {
  9023. static struct _cgpu_devid_counter *devids = NULL;
  9024. struct _cgpu_devid_counter *d;
  9025. HASH_FIND_STR(devids, cgpu->drv->name, d);
  9026. if (d)
  9027. cgpu->device_id = ++d->lastid;
  9028. else {
  9029. d = malloc(sizeof(*d));
  9030. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  9031. cgpu->device_id = d->lastid = 0;
  9032. HASH_ADD_STR(devids, name, d);
  9033. }
  9034. }
  9035. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  9036. {
  9037. sha256(buffer, length, digest);
  9038. return true;
  9039. }
  9040. #ifndef HAVE_PTHREAD_CANCEL
  9041. extern void setup_pthread_cancel_workaround();
  9042. extern struct sigaction pcwm_orig_term_handler;
  9043. #endif
  9044. bool bfg_need_detect_rescan;
  9045. extern void probe_device(struct lowlevel_device_info *);
  9046. static
  9047. void drv_detect_all()
  9048. {
  9049. rescan:
  9050. bfg_need_detect_rescan = false;
  9051. #ifdef HAVE_BFG_LOWLEVEL
  9052. struct lowlevel_device_info * const infolist = lowlevel_scan(), *info, *infotmp;
  9053. LL_FOREACH_SAFE(infolist, info, infotmp)
  9054. probe_device(info);
  9055. LL_FOREACH_SAFE(infolist, info, infotmp)
  9056. pthread_join(info->probe_pth, NULL);
  9057. #endif
  9058. struct driver_registration *reg, *tmp;
  9059. const int algomatch = opt_scrypt ? POW_SCRYPT : POW_SHA256D;
  9060. BFG_FOREACH_DRIVER_BY_PRIORITY(reg, tmp)
  9061. {
  9062. const struct device_drv * const drv = reg->drv;
  9063. const supported_algos_t algos = drv->supported_algos ?: POW_SHA256D;
  9064. if (0 == (algos & algomatch) || !drv->drv_detect)
  9065. continue;
  9066. drv->drv_detect();
  9067. }
  9068. #ifdef HAVE_BFG_LOWLEVEL
  9069. lowlevel_scan_free();
  9070. #endif
  9071. if (bfg_need_detect_rescan)
  9072. {
  9073. applog(LOG_DEBUG, "Device rescan requested");
  9074. goto rescan;
  9075. }
  9076. }
  9077. static
  9078. void allocate_cgpu(struct cgpu_info *cgpu, unsigned int *kp)
  9079. {
  9080. struct thr_info *thr;
  9081. int j;
  9082. struct device_drv *api = cgpu->drv;
  9083. if (!cgpu->devtype)
  9084. cgpu->devtype = "PGA";
  9085. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9086. int threadobj = cgpu->threads;
  9087. if (!threadobj)
  9088. // Create a fake thread object to handle hashmeter etc
  9089. threadobj = 1;
  9090. cgpu->thr = calloc(threadobj + 1, sizeof(*cgpu->thr));
  9091. cgpu->thr[threadobj] = NULL;
  9092. cgpu->status = LIFE_INIT;
  9093. if (opt_devices_enabled_list)
  9094. {
  9095. struct string_elist *enablestr_elist;
  9096. cgpu->deven = DEV_DISABLED;
  9097. DL_FOREACH(opt_devices_enabled_list, enablestr_elist)
  9098. {
  9099. const char * const enablestr = enablestr_elist->string;
  9100. if (cgpu_match(enablestr, cgpu))
  9101. {
  9102. cgpu->deven = DEV_ENABLED;
  9103. break;
  9104. }
  9105. }
  9106. }
  9107. cgpu->max_hashes = 0;
  9108. // Setup thread structs before starting any of the threads, in case they try to interact
  9109. for (j = 0; j < threadobj; ++j, ++*kp) {
  9110. thr = get_thread(*kp);
  9111. thr->id = *kp;
  9112. thr->cgpu = cgpu;
  9113. thr->device_thread = j;
  9114. thr->work_restart_notifier[1] = INVSOCK;
  9115. thr->mutex_request[1] = INVSOCK;
  9116. thr->_job_transition_in_progress = true;
  9117. timerclear(&thr->tv_morework);
  9118. thr->scanhash_working = true;
  9119. thr->hashes_done = 0;
  9120. timerclear(&thr->tv_hashes_done);
  9121. cgtime(&thr->tv_lastupdate);
  9122. thr->tv_poll.tv_sec = -1;
  9123. thr->_max_nonce = api->can_limit_work ? api->can_limit_work(thr) : 0xffffffff;
  9124. cgpu->thr[j] = thr;
  9125. }
  9126. if (!cgpu->device->threads)
  9127. notifier_init_invalid(cgpu->thr[0]->notifier);
  9128. else
  9129. if (!cgpu->threads)
  9130. memcpy(&cgpu->thr[0]->notifier, &cgpu->device->thr[0]->notifier, sizeof(cgpu->thr[0]->notifier));
  9131. else
  9132. for (j = 0; j < cgpu->threads; ++j)
  9133. {
  9134. thr = cgpu->thr[j];
  9135. notifier_init(thr->notifier);
  9136. }
  9137. }
  9138. static
  9139. void start_cgpu(struct cgpu_info *cgpu)
  9140. {
  9141. struct thr_info *thr;
  9142. int j;
  9143. for (j = 0; j < cgpu->threads; ++j) {
  9144. thr = cgpu->thr[j];
  9145. /* Enable threads for devices set not to mine but disable
  9146. * their queue in case we wish to enable them later */
  9147. if (cgpu->drv->thread_prepare && !cgpu->drv->thread_prepare(thr))
  9148. continue;
  9149. thread_reportout(thr);
  9150. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  9151. quit(1, "thread %d create failed", thr->id);
  9152. notifier_wake(thr->notifier);
  9153. }
  9154. if (cgpu->deven == DEV_ENABLED)
  9155. proc_enable(cgpu);
  9156. }
  9157. static
  9158. void _scan_serial(void *p)
  9159. {
  9160. const char *s = p;
  9161. struct string_elist *iter, *tmp;
  9162. struct string_elist *orig_scan_devices = scan_devices;
  9163. if (s)
  9164. {
  9165. // Make temporary scan_devices list
  9166. scan_devices = NULL;
  9167. string_elist_add("noauto", &scan_devices);
  9168. add_serial(s);
  9169. }
  9170. drv_detect_all();
  9171. if (s)
  9172. {
  9173. DL_FOREACH_SAFE(scan_devices, iter, tmp)
  9174. {
  9175. string_elist_del(&scan_devices, iter);
  9176. }
  9177. scan_devices = orig_scan_devices;
  9178. }
  9179. }
  9180. #ifdef HAVE_BFG_LOWLEVEL
  9181. static
  9182. bool _probe_device_match(const struct lowlevel_device_info * const info, const char * const ser)
  9183. {
  9184. if (!(false
  9185. || (info->serial && !strcasecmp(ser, info->serial))
  9186. || (info->path && !strcasecmp(ser, info->path ))
  9187. ))
  9188. {
  9189. char *devid = devpath_to_devid(ser);
  9190. if (!devid)
  9191. return false;
  9192. const bool different = strcmp(info->devid, devid);
  9193. free(devid);
  9194. if (different)
  9195. return false;
  9196. }
  9197. return true;
  9198. }
  9199. static
  9200. const struct device_drv *_probe_device_find_drv(const char * const _dname, const size_t dnamelen)
  9201. {
  9202. struct driver_registration *dreg;
  9203. char dname[dnamelen];
  9204. int i;
  9205. for (i = 0; i < dnamelen; ++i)
  9206. dname[i] = tolower(_dname[i]);
  9207. BFG_FIND_DRV_BY_DNAME(dreg, dname, dnamelen);
  9208. if (!dreg)
  9209. {
  9210. for (i = 0; i < dnamelen; ++i)
  9211. dname[i] = toupper(_dname[i]);
  9212. BFG_FIND_DRV_BY_NAME(dreg, dname, dnamelen);
  9213. if (!dreg)
  9214. return NULL;
  9215. }
  9216. return dreg->drv;
  9217. }
  9218. static
  9219. bool _probe_device_internal(struct lowlevel_device_info * const info, const char * const dname, const size_t dnamelen)
  9220. {
  9221. const struct device_drv * const drv = _probe_device_find_drv(dname, dnamelen);
  9222. if (!(drv && drv->lowl_probe))
  9223. return false;
  9224. return drv->lowl_probe(info);
  9225. }
  9226. static
  9227. void *probe_device_thread(void *p)
  9228. {
  9229. struct lowlevel_device_info * const infolist = p;
  9230. struct lowlevel_device_info *info = infolist;
  9231. {
  9232. char threadname[5 + strlen(info->devid) + 1];
  9233. sprintf(threadname, "probe_%s", info->devid);
  9234. RenameThread(threadname);
  9235. }
  9236. // If already in use, ignore
  9237. if (bfg_claim_any(NULL, NULL, info->devid))
  9238. applogr(NULL, LOG_DEBUG, "%s: \"%s\" already in use",
  9239. __func__, info->product);
  9240. // if lowlevel device matches specific user assignment, probe requested driver(s)
  9241. struct string_elist *sd_iter, *sd_tmp;
  9242. struct driver_registration *dreg, *dreg_tmp;
  9243. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9244. {
  9245. const char * const dname = sd_iter->string;
  9246. const char * const colon = strpbrk(dname, ":@");
  9247. if (!(colon && colon != dname))
  9248. continue;
  9249. const char * const ser = &colon[1];
  9250. LL_FOREACH2(infolist, info, same_devid_next)
  9251. {
  9252. if (!_probe_device_match(info, ser))
  9253. continue;
  9254. const size_t dnamelen = (colon - dname);
  9255. if (_probe_device_internal(info, dname, dnamelen))
  9256. return NULL;
  9257. }
  9258. }
  9259. // probe driver(s) with auto enabled and matching VID/PID/Product/etc of device
  9260. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9261. {
  9262. const struct device_drv * const drv = dreg->drv;
  9263. // Check for "noauto" flag
  9264. // NOTE: driver-specific configuration overrides general
  9265. bool doauto = true;
  9266. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9267. {
  9268. const char * const dname = sd_iter->string;
  9269. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9270. const char *colon = strchr(dname, ':');
  9271. if (!colon)
  9272. colon = &dname[-1];
  9273. if (strcasecmp("noauto", &colon[1]) && strcasecmp("auto", &colon[1]))
  9274. continue;
  9275. const ssize_t dnamelen = (colon - dname);
  9276. if (dnamelen >= 0 && _probe_device_find_drv(dname, dnamelen) != drv)
  9277. continue;
  9278. doauto = (tolower(colon[1]) == 'a');
  9279. if (dnamelen != -1)
  9280. break;
  9281. }
  9282. if (doauto && drv->lowl_match)
  9283. {
  9284. LL_FOREACH2(infolist, info, same_devid_next)
  9285. {
  9286. if (!drv->lowl_match(info))
  9287. continue;
  9288. if (drv->lowl_probe(info))
  9289. return NULL;
  9290. }
  9291. }
  9292. }
  9293. // probe driver(s) with 'all' enabled
  9294. DL_FOREACH_SAFE(scan_devices, sd_iter, sd_tmp)
  9295. {
  9296. const char * const dname = sd_iter->string;
  9297. // NOTE: Only checking flags here, NOT path/serial, so @ is unacceptable
  9298. const char * const colon = strchr(dname, ':');
  9299. if (!colon)
  9300. {
  9301. LL_FOREACH2(infolist, info, same_devid_next)
  9302. {
  9303. if (
  9304. #ifdef NEED_BFG_LOWL_VCOM
  9305. (info->lowl == &lowl_vcom && !strcasecmp(dname, "all")) ||
  9306. #endif
  9307. _probe_device_match(info, (dname[0] == '@') ? &dname[1] : dname))
  9308. {
  9309. BFG_FOREACH_DRIVER_BY_PRIORITY(dreg, dreg_tmp)
  9310. {
  9311. const struct device_drv * const drv = dreg->drv;
  9312. if (drv->lowl_probe_by_name_only)
  9313. continue;
  9314. if (!drv->lowl_probe)
  9315. continue;
  9316. if (drv->lowl_probe(info))
  9317. return NULL;
  9318. }
  9319. break;
  9320. }
  9321. }
  9322. continue;
  9323. }
  9324. if (strcasecmp(&colon[1], "all"))
  9325. continue;
  9326. const size_t dnamelen = (colon - dname);
  9327. LL_FOREACH2(infolist, info, same_devid_next)
  9328. {
  9329. if (_probe_device_internal(info, dname, dnamelen))
  9330. return NULL;
  9331. }
  9332. }
  9333. return NULL;
  9334. }
  9335. void probe_device(struct lowlevel_device_info * const info)
  9336. {
  9337. pthread_create(&info->probe_pth, NULL, probe_device_thread, info);
  9338. }
  9339. #endif
  9340. int create_new_cgpus(void (*addfunc)(void*), void *arg)
  9341. {
  9342. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9343. int devcount, i, mining_threads_new = 0;
  9344. unsigned int k;
  9345. struct cgpu_info *cgpu;
  9346. struct thr_info *thr;
  9347. void *p;
  9348. char *dummy = "\0";
  9349. mutex_lock(&mutex);
  9350. devcount = total_devices;
  9351. addfunc(arg);
  9352. if (!total_devices_new)
  9353. goto out;
  9354. wr_lock(&devices_lock);
  9355. p = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + total_devices_new + 1));
  9356. if (unlikely(!p))
  9357. {
  9358. wr_unlock(&devices_lock);
  9359. applog(LOG_ERR, "scan_serial: realloc failed trying to grow devices array");
  9360. goto out;
  9361. }
  9362. devices = p;
  9363. wr_unlock(&devices_lock);
  9364. for (i = 0; i < total_devices_new; ++i)
  9365. {
  9366. cgpu = devices_new[i];
  9367. mining_threads_new += cgpu->threads ?: 1;
  9368. }
  9369. wr_lock(&mining_thr_lock);
  9370. mining_threads_new += mining_threads;
  9371. p = realloc(mining_thr, sizeof(struct thr_info *) * mining_threads_new);
  9372. if (unlikely(!p))
  9373. {
  9374. wr_unlock(&mining_thr_lock);
  9375. applog(LOG_ERR, "scan_serial: realloc failed trying to grow mining_thr");
  9376. goto out;
  9377. }
  9378. mining_thr = p;
  9379. wr_unlock(&mining_thr_lock);
  9380. for (i = mining_threads; i < mining_threads_new; ++i) {
  9381. mining_thr[i] = calloc(1, sizeof(*thr));
  9382. if (!mining_thr[i])
  9383. {
  9384. applog(LOG_ERR, "scan_serial: Failed to calloc mining_thr[%d]", i);
  9385. for ( ; --i >= mining_threads; )
  9386. free(mining_thr[i]);
  9387. goto out;
  9388. }
  9389. }
  9390. k = mining_threads;
  9391. for (i = 0; i < total_devices_new; ++i)
  9392. {
  9393. cgpu = devices_new[i];
  9394. load_temp_config_cgpu(cgpu, &dummy, &dummy);
  9395. allocate_cgpu(cgpu, &k);
  9396. start_cgpu(cgpu);
  9397. register_device(cgpu);
  9398. ++total_devices;
  9399. }
  9400. #ifdef HAVE_CURSES
  9401. switch_logsize();
  9402. #endif
  9403. out:
  9404. total_devices_new = 0;
  9405. devcount = total_devices - devcount;
  9406. mutex_unlock(&mutex);
  9407. return devcount;
  9408. }
  9409. int scan_serial(const char *s)
  9410. {
  9411. return create_new_cgpus(_scan_serial, (void*)s);
  9412. }
  9413. static void probe_pools(void)
  9414. {
  9415. int i;
  9416. for (i = 0; i < total_pools; i++) {
  9417. struct pool *pool = pools[i];
  9418. pool->testing = true;
  9419. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  9420. }
  9421. }
  9422. static void raise_fd_limits(void)
  9423. {
  9424. #ifdef HAVE_SETRLIMIT
  9425. struct rlimit fdlimit;
  9426. unsigned long old_soft_limit;
  9427. char frombuf[0x10] = "unlimited";
  9428. char hardbuf[0x10] = "unlimited";
  9429. if (getrlimit(RLIMIT_NOFILE, &fdlimit))
  9430. applogr(, LOG_DEBUG, "setrlimit: Failed to getrlimit(RLIMIT_NOFILE)");
  9431. old_soft_limit = fdlimit.rlim_cur;
  9432. if (fdlimit.rlim_max > FD_SETSIZE || fdlimit.rlim_max == RLIM_INFINITY)
  9433. fdlimit.rlim_cur = FD_SETSIZE;
  9434. else
  9435. fdlimit.rlim_cur = fdlimit.rlim_max;
  9436. if (fdlimit.rlim_max != RLIM_INFINITY)
  9437. snprintf(hardbuf, sizeof(hardbuf), "%lu", (unsigned long)fdlimit.rlim_max);
  9438. if (old_soft_limit != RLIM_INFINITY)
  9439. snprintf(frombuf, sizeof(frombuf), "%lu", old_soft_limit);
  9440. if (fdlimit.rlim_cur == old_soft_limit)
  9441. applogr(, LOG_DEBUG, "setrlimit: Soft fd limit not being changed from %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9442. old_soft_limit, (unsigned long)FD_SETSIZE, hardbuf);
  9443. if (setrlimit(RLIMIT_NOFILE, &fdlimit))
  9444. applogr(, LOG_DEBUG, "setrlimit: Failed to change soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9445. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9446. applog(LOG_DEBUG, "setrlimit: Changed soft fd limit from %s to %lu (FD_SETSIZE=%lu; hard limit=%s)",
  9447. frombuf, (unsigned long)fdlimit.rlim_cur, (unsigned long)FD_SETSIZE, hardbuf);
  9448. #else
  9449. applog(LOG_DEBUG, "setrlimit: Not supported by platform");
  9450. #endif
  9451. }
  9452. extern void bfg_init_threadlocal();
  9453. extern void stratumsrv_start();
  9454. int main(int argc, char *argv[])
  9455. {
  9456. struct sigaction handler;
  9457. struct thr_info *thr;
  9458. struct block *block;
  9459. unsigned int k;
  9460. int i;
  9461. char *s;
  9462. #ifdef WIN32
  9463. LoadLibrary("backtrace.dll");
  9464. #endif
  9465. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  9466. bfg_init_threadlocal();
  9467. #ifndef HAVE_PTHREAD_CANCEL
  9468. setup_pthread_cancel_workaround();
  9469. #endif
  9470. #ifdef WIN32
  9471. {
  9472. WSADATA wsa;
  9473. i = WSAStartup(MAKEWORD(2, 2), &wsa);
  9474. if (i)
  9475. quit(1, "Failed to initialise Winsock: %s", bfg_strerror(i, BST_SOCKET));
  9476. }
  9477. #endif
  9478. /* This dangerous functions tramples random dynamically allocated
  9479. * variables so do it before anything at all */
  9480. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  9481. quit(1, "Failed to curl_global_init");
  9482. initial_args = malloc(sizeof(char *) * (argc + 1));
  9483. for (i = 0; i < argc; i++)
  9484. initial_args[i] = strdup(argv[i]);
  9485. initial_args[argc] = NULL;
  9486. mutex_init(&hash_lock);
  9487. mutex_init(&console_lock);
  9488. cglock_init(&control_lock);
  9489. mutex_init(&stats_lock);
  9490. mutex_init(&sharelog_lock);
  9491. cglock_init(&ch_lock);
  9492. mutex_init(&sshare_lock);
  9493. rwlock_init(&blk_lock);
  9494. rwlock_init(&netacc_lock);
  9495. rwlock_init(&mining_thr_lock);
  9496. rwlock_init(&devices_lock);
  9497. mutex_init(&lp_lock);
  9498. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  9499. quit(1, "Failed to pthread_cond_init lp_cond");
  9500. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  9501. quit(1, "Failed to pthread_cond_init gws_cond");
  9502. notifier_init(submit_waiting_notifier);
  9503. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  9504. #ifdef WANT_CPUMINE
  9505. init_max_name_len();
  9506. #endif
  9507. handler.sa_handler = &sighandler;
  9508. handler.sa_flags = 0;
  9509. sigemptyset(&handler.sa_mask);
  9510. #ifdef HAVE_PTHREAD_CANCEL
  9511. sigaction(SIGTERM, &handler, &termhandler);
  9512. #else
  9513. // Need to let pthread_cancel emulation handle SIGTERM first
  9514. termhandler = pcwm_orig_term_handler;
  9515. pcwm_orig_term_handler = handler;
  9516. #endif
  9517. sigaction(SIGINT, &handler, &inthandler);
  9518. #ifndef WIN32
  9519. signal(SIGPIPE, SIG_IGN);
  9520. #else
  9521. timeBeginPeriod(1);
  9522. #endif
  9523. opt_kernel_path = CGMINER_PREFIX;
  9524. cgminer_path = alloca(PATH_MAX);
  9525. s = strdup(argv[0]);
  9526. strcpy(cgminer_path, dirname(s));
  9527. free(s);
  9528. strcat(cgminer_path, "/");
  9529. #ifdef WANT_CPUMINE
  9530. // Hack to make cgminer silent when called recursively on WIN32
  9531. int skip_to_bench = 0;
  9532. #if defined(WIN32)
  9533. char buf[32];
  9534. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  9535. skip_to_bench = 1;
  9536. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  9537. skip_to_bench = 1;
  9538. #endif // defined(WIN32)
  9539. #endif
  9540. devcursor = 8;
  9541. logstart = devcursor;
  9542. logcursor = logstart;
  9543. block = calloc(sizeof(struct block), 1);
  9544. if (unlikely(!block))
  9545. quit (1, "main OOM");
  9546. for (i = 0; i < 36; i++)
  9547. strcat(block->hash, "0");
  9548. HASH_ADD_STR(blocks, hash, block);
  9549. strcpy(current_block, block->hash);
  9550. mutex_init(&submitting_lock);
  9551. #ifdef HAVE_OPENCL
  9552. memset(gpus, 0, sizeof(gpus));
  9553. for (i = 0; i < MAX_GPUDEVICES; i++)
  9554. gpus[i].dynamic = true;
  9555. #endif
  9556. schedstart.tm.tm_sec = 1;
  9557. schedstop .tm.tm_sec = 1;
  9558. /* parse command line */
  9559. opt_register_table(opt_config_table,
  9560. "Options for both config file and command line");
  9561. opt_register_table(opt_cmdline_table,
  9562. "Options for command line only");
  9563. opt_parse(&argc, argv, applog_and_exit);
  9564. if (argc != 1)
  9565. quit(1, "Unexpected extra commandline arguments");
  9566. if (!config_loaded)
  9567. load_default_config();
  9568. #ifndef HAVE_PTHREAD_CANCEL
  9569. // Can't do this any earlier, or config isn't loaded
  9570. applog(LOG_DEBUG, "pthread_cancel workaround in use");
  9571. #endif
  9572. #ifdef HAVE_PWD_H
  9573. struct passwd *user_info = NULL;
  9574. if (opt_setuid != NULL) {
  9575. if ((user_info = getpwnam(opt_setuid)) == NULL) {
  9576. quit(1, "Unable to find setuid user information");
  9577. }
  9578. }
  9579. #endif
  9580. #ifdef HAVE_CHROOT
  9581. if (chroot_dir != NULL) {
  9582. #ifdef HAVE_PWD_H
  9583. if (user_info == NULL && getuid() == 0) {
  9584. applog(LOG_WARNING, "Running as root inside chroot");
  9585. }
  9586. #endif
  9587. if (chroot(chroot_dir) != 0) {
  9588. quit(1, "Unable to chroot");
  9589. }
  9590. if (chdir("/"))
  9591. quit(1, "Unable to chdir to chroot");
  9592. }
  9593. #endif
  9594. #ifdef HAVE_PWD_H
  9595. if (user_info != NULL) {
  9596. if (setgid((*user_info).pw_gid) != 0)
  9597. quit(1, "Unable to setgid");
  9598. if (setuid((*user_info).pw_uid) != 0)
  9599. quit(1, "Unable to setuid");
  9600. }
  9601. #endif
  9602. raise_fd_limits();
  9603. if (opt_benchmark) {
  9604. struct pool *pool;
  9605. if (opt_scrypt)
  9606. quit(1, "Cannot use benchmark mode with scrypt");
  9607. want_longpoll = false;
  9608. pool = add_pool();
  9609. pool->rpc_url = malloc(255);
  9610. strcpy(pool->rpc_url, "Benchmark");
  9611. pool->rpc_user = pool->rpc_url;
  9612. pool->rpc_pass = pool->rpc_url;
  9613. enable_pool(pool);
  9614. pool->idle = false;
  9615. successful_connect = true;
  9616. }
  9617. if (opt_unittest) {
  9618. test_cgpu_match();
  9619. test_intrange();
  9620. test_decimal_width();
  9621. utf8_test();
  9622. }
  9623. #ifdef HAVE_CURSES
  9624. if (opt_realquiet || opt_display_devs)
  9625. use_curses = false;
  9626. setlocale(LC_ALL, "C");
  9627. if (use_curses)
  9628. enable_curses();
  9629. #endif
  9630. #ifdef HAVE_LIBUSB
  9631. int err = libusb_init(NULL);
  9632. if (err)
  9633. applog(LOG_WARNING, "libusb_init() failed err %d", err);
  9634. else
  9635. have_libusb = true;
  9636. #endif
  9637. applog(LOG_WARNING, "Started %s", packagename);
  9638. if (cnfbuf) {
  9639. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  9640. switch (fileconf_load) {
  9641. case 0:
  9642. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  9643. applog(LOG_WARNING, "Configuration file could not be used.");
  9644. break;
  9645. case -1:
  9646. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  9647. if (use_curses)
  9648. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  9649. break;
  9650. default:
  9651. break;
  9652. }
  9653. free(cnfbuf);
  9654. cnfbuf = NULL;
  9655. }
  9656. i = strlen(opt_kernel_path) + 2;
  9657. char __kernel_path[i];
  9658. snprintf(__kernel_path, i, "%s/", opt_kernel_path);
  9659. opt_kernel_path = __kernel_path;
  9660. if (want_per_device_stats)
  9661. opt_log_output = true;
  9662. #ifdef WANT_CPUMINE
  9663. #ifdef USE_SCRYPT
  9664. if (opt_scrypt)
  9665. set_scrypt_algo(&opt_algo);
  9666. else
  9667. #endif
  9668. if (0 <= opt_bench_algo) {
  9669. double rate = bench_algo_stage3(opt_bench_algo);
  9670. if (!skip_to_bench)
  9671. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  9672. else {
  9673. // Write result to shared memory for parent
  9674. #if defined(WIN32)
  9675. char unique_name[64];
  9676. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  9677. HANDLE map_handle = CreateFileMapping(
  9678. INVALID_HANDLE_VALUE, // use paging file
  9679. NULL, // default security attributes
  9680. PAGE_READWRITE, // read/write access
  9681. 0, // size: high 32-bits
  9682. 4096, // size: low 32-bits
  9683. unique_name // name of map object
  9684. );
  9685. if (NULL != map_handle) {
  9686. void *shared_mem = MapViewOfFile(
  9687. map_handle, // object to map view of
  9688. FILE_MAP_WRITE, // read/write access
  9689. 0, // high offset: map from
  9690. 0, // low offset: beginning
  9691. 0 // default: map entire file
  9692. );
  9693. if (NULL != shared_mem)
  9694. CopyMemory(shared_mem, &rate, sizeof(rate));
  9695. (void)UnmapViewOfFile(shared_mem);
  9696. }
  9697. (void)CloseHandle(map_handle);
  9698. }
  9699. #endif
  9700. }
  9701. exit(0);
  9702. }
  9703. #endif
  9704. bfg_devapi_init();
  9705. drv_detect_all();
  9706. total_devices = total_devices_new;
  9707. devices = devices_new;
  9708. total_devices_new = 0;
  9709. devices_new = NULL;
  9710. if (opt_display_devs) {
  9711. int devcount = 0;
  9712. applog(LOG_ERR, "Devices detected:");
  9713. for (i = 0; i < total_devices; ++i) {
  9714. struct cgpu_info *cgpu = devices[i];
  9715. char buf[0x100];
  9716. if (cgpu->device != cgpu)
  9717. continue;
  9718. if (cgpu->name)
  9719. snprintf(buf, sizeof(buf), " %s", cgpu->name);
  9720. else
  9721. if (cgpu->dev_manufacturer)
  9722. snprintf(buf, sizeof(buf), " %s by %s", (cgpu->dev_product ?: "Device"), cgpu->dev_manufacturer);
  9723. else
  9724. if (cgpu->dev_product)
  9725. snprintf(buf, sizeof(buf), " %s", cgpu->dev_product);
  9726. else
  9727. strcpy(buf, " Device");
  9728. tailsprintf(buf, sizeof(buf), " (driver=%s; procs=%d", cgpu->drv->dname, cgpu->procs);
  9729. if (cgpu->dev_serial)
  9730. tailsprintf(buf, sizeof(buf), "; serial=%s", cgpu->dev_serial);
  9731. if (cgpu->device_path)
  9732. tailsprintf(buf, sizeof(buf), "; path=%s", cgpu->device_path);
  9733. tailsprintf(buf, sizeof(buf), ")");
  9734. _applog(LOG_NOTICE, buf);
  9735. ++devcount;
  9736. }
  9737. quit(0, "%d devices listed", devcount);
  9738. }
  9739. mining_threads = 0;
  9740. for (i = 0; i < total_devices; ++i)
  9741. register_device(devices[i]);
  9742. if (!total_devices) {
  9743. applog(LOG_WARNING, "No devices detected!");
  9744. if (use_curses)
  9745. applog(LOG_WARNING, "Waiting for devices; press 'M+' to add, or 'Q' to quit");
  9746. else
  9747. applog(LOG_WARNING, "Waiting for devices");
  9748. }
  9749. load_temp_config();
  9750. #ifdef HAVE_CURSES
  9751. switch_logsize();
  9752. #endif
  9753. if (!total_pools) {
  9754. applog(LOG_WARNING, "Need to specify at least one pool server.");
  9755. #ifdef HAVE_CURSES
  9756. if (!use_curses || !input_pool(false))
  9757. #endif
  9758. quit(1, "Pool setup failed");
  9759. }
  9760. for (i = 0; i < total_pools; i++) {
  9761. struct pool *pool = pools[i];
  9762. size_t siz;
  9763. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9764. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  9765. if (!pool->rpc_url)
  9766. quit(1, "No URI supplied for pool %u", i);
  9767. if (!pool->rpc_userpass) {
  9768. if (!pool->rpc_user || !pool->rpc_pass)
  9769. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  9770. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  9771. pool->rpc_userpass = malloc(siz);
  9772. if (!pool->rpc_userpass)
  9773. quit(1, "Failed to malloc userpass");
  9774. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  9775. }
  9776. }
  9777. /* Set the currentpool to pool with priority 0 */
  9778. validate_pool_priorities();
  9779. for (i = 0; i < total_pools; i++) {
  9780. struct pool *pool = pools[i];
  9781. if (!pool->prio)
  9782. currentpool = pool;
  9783. }
  9784. #ifdef HAVE_SYSLOG_H
  9785. if (use_syslog)
  9786. openlog(PACKAGE, LOG_PID, LOG_USER);
  9787. #endif
  9788. #if defined(unix) || defined(__APPLE__)
  9789. if (opt_stderr_cmd)
  9790. fork_monitor();
  9791. #endif // defined(unix)
  9792. mining_thr = calloc(mining_threads, sizeof(thr));
  9793. if (!mining_thr)
  9794. quit(1, "Failed to calloc mining_thr");
  9795. for (i = 0; i < mining_threads; i++) {
  9796. mining_thr[i] = calloc(1, sizeof(*thr));
  9797. if (!mining_thr[i])
  9798. quit(1, "Failed to calloc mining_thr[%d]", i);
  9799. }
  9800. total_control_threads = 6;
  9801. control_thr = calloc(total_control_threads, sizeof(*thr));
  9802. if (!control_thr)
  9803. quit(1, "Failed to calloc control_thr");
  9804. gwsched_thr_id = 0;
  9805. /* Create a unique get work queue */
  9806. getq = tq_new();
  9807. if (!getq)
  9808. quit(1, "Failed to create getq");
  9809. /* We use the getq mutex as the staged lock */
  9810. stgd_lock = &getq->mutex;
  9811. if (opt_benchmark)
  9812. goto begin_bench;
  9813. for (i = 0; i < total_pools; i++) {
  9814. struct pool *pool = pools[i];
  9815. enable_pool(pool);
  9816. pool->idle = true;
  9817. }
  9818. applog(LOG_NOTICE, "Probing for an alive pool");
  9819. do {
  9820. bool still_testing;
  9821. int i;
  9822. /* Look for at least one active pool before starting */
  9823. probe_pools();
  9824. do {
  9825. sleep(1);
  9826. if (pools_active)
  9827. break;
  9828. still_testing = false;
  9829. for (int i = 0; i < total_pools; ++i)
  9830. if (pools[i]->testing)
  9831. still_testing = true;
  9832. } while (still_testing);
  9833. if (!pools_active) {
  9834. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  9835. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  9836. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  9837. for (i = 0; i < total_pools; i++) {
  9838. struct pool *pool;
  9839. pool = pools[i];
  9840. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  9841. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  9842. }
  9843. #ifdef HAVE_CURSES
  9844. if (use_curses) {
  9845. halfdelay(150);
  9846. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  9847. if (getch() != ERR)
  9848. quit(0, "No servers could be used! Exiting.");
  9849. cbreak();
  9850. } else
  9851. #endif
  9852. quit(0, "No servers could be used! Exiting.");
  9853. }
  9854. } while (!pools_active);
  9855. #ifdef USE_SCRYPT
  9856. if (detect_algo == 1 && !opt_scrypt) {
  9857. applog(LOG_NOTICE, "Detected scrypt algorithm");
  9858. opt_scrypt = true;
  9859. }
  9860. #endif
  9861. detect_algo = 0;
  9862. begin_bench:
  9863. total_mhashes_done = 0;
  9864. for (i = 0; i < total_devices; i++) {
  9865. struct cgpu_info *cgpu = devices[i];
  9866. cgpu->rolling = cgpu->total_mhashes = 0;
  9867. }
  9868. cgtime(&total_tv_start);
  9869. cgtime(&total_tv_end);
  9870. miner_started = total_tv_start;
  9871. time_t miner_start_ts = time(NULL);
  9872. if (schedstart.tm.tm_sec)
  9873. localtime_r(&miner_start_ts, &schedstart.tm);
  9874. if (schedstop.tm.tm_sec)
  9875. localtime_r(&miner_start_ts, &schedstop .tm);
  9876. get_datestamp(datestamp, sizeof(datestamp), miner_start_ts);
  9877. // Initialise processors and threads
  9878. k = 0;
  9879. for (i = 0; i < total_devices; ++i) {
  9880. struct cgpu_info *cgpu = devices[i];
  9881. allocate_cgpu(cgpu, &k);
  9882. }
  9883. // Start threads
  9884. for (i = 0; i < total_devices; ++i) {
  9885. struct cgpu_info *cgpu = devices[i];
  9886. start_cgpu(cgpu);
  9887. }
  9888. #ifdef HAVE_OPENCL
  9889. for (i = 0; i < nDevs; i++)
  9890. pause_dynamic_threads(i);
  9891. #endif
  9892. #ifdef WANT_CPUMINE
  9893. applog(LOG_INFO, "%d cpu miner threads started, "
  9894. "using SHA256 '%s' algorithm.",
  9895. opt_n_threads,
  9896. algo_names[opt_algo]);
  9897. #endif
  9898. cgtime(&total_tv_start);
  9899. cgtime(&total_tv_end);
  9900. {
  9901. pthread_t submit_thread;
  9902. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, NULL)))
  9903. quit(1, "submit_work thread create failed");
  9904. }
  9905. watchpool_thr_id = 1;
  9906. thr = &control_thr[watchpool_thr_id];
  9907. /* start watchpool thread */
  9908. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  9909. quit(1, "watchpool thread create failed");
  9910. pthread_detach(thr->pth);
  9911. watchdog_thr_id = 2;
  9912. thr = &control_thr[watchdog_thr_id];
  9913. /* start watchdog thread */
  9914. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  9915. quit(1, "watchdog thread create failed");
  9916. pthread_detach(thr->pth);
  9917. #ifdef HAVE_OPENCL
  9918. /* Create reinit gpu thread */
  9919. gpur_thr_id = 3;
  9920. thr = &control_thr[gpur_thr_id];
  9921. thr->q = tq_new();
  9922. if (!thr->q)
  9923. quit(1, "tq_new failed for gpur_thr_id");
  9924. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  9925. quit(1, "reinit_gpu thread create failed");
  9926. #endif
  9927. /* Create API socket thread */
  9928. api_thr_id = 4;
  9929. thr = &control_thr[api_thr_id];
  9930. if (thr_info_create(thr, NULL, api_thread, thr))
  9931. quit(1, "API thread create failed");
  9932. #ifdef USE_LIBMICROHTTPD
  9933. if (httpsrv_port != -1)
  9934. httpsrv_start(httpsrv_port);
  9935. #endif
  9936. #ifdef USE_LIBEVENT
  9937. if (stratumsrv_port != -1)
  9938. stratumsrv_start();
  9939. #endif
  9940. #ifdef HAVE_CURSES
  9941. /* Create curses input thread for keyboard input. Create this last so
  9942. * that we know all threads are created since this can call kill_work
  9943. * to try and shut down ll previous threads. */
  9944. input_thr_id = 5;
  9945. thr = &control_thr[input_thr_id];
  9946. if (thr_info_create(thr, NULL, input_thread, thr))
  9947. quit(1, "input thread create failed");
  9948. pthread_detach(thr->pth);
  9949. #endif
  9950. /* Just to be sure */
  9951. if (total_control_threads != 6)
  9952. quit(1, "incorrect total_control_threads (%d) should be 7", total_control_threads);
  9953. /* Once everything is set up, main() becomes the getwork scheduler */
  9954. while (42) {
  9955. int ts, max_staged = opt_queue;
  9956. struct pool *pool, *cp;
  9957. bool lagging = false;
  9958. struct curl_ent *ce;
  9959. struct work *work;
  9960. cp = current_pool();
  9961. /* If the primary pool is a getwork pool and cannot roll work,
  9962. * try to stage one extra work per mining thread */
  9963. if (!pool_localgen(cp) && !staged_rollable)
  9964. max_staged += mining_threads;
  9965. mutex_lock(stgd_lock);
  9966. ts = __total_staged();
  9967. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  9968. lagging = true;
  9969. /* Wait until hash_pop tells us we need to create more work */
  9970. if (ts > max_staged) {
  9971. staged_full = true;
  9972. pthread_cond_wait(&gws_cond, stgd_lock);
  9973. ts = __total_staged();
  9974. }
  9975. mutex_unlock(stgd_lock);
  9976. if (ts > max_staged)
  9977. continue;
  9978. work = make_work();
  9979. if (lagging && !pool_tset(cp, &cp->lagging)) {
  9980. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  9981. cp->getfail_occasions++;
  9982. total_go++;
  9983. }
  9984. pool = select_pool(lagging);
  9985. retry:
  9986. if (pool->has_stratum) {
  9987. while (!pool->stratum_active || !pool->stratum_notify) {
  9988. struct pool *altpool = select_pool(true);
  9989. if (altpool == pool && pool->has_stratum)
  9990. cgsleep_ms(5000);
  9991. pool = altpool;
  9992. goto retry;
  9993. }
  9994. gen_stratum_work(pool, work);
  9995. applog(LOG_DEBUG, "Generated stratum work");
  9996. stage_work(work);
  9997. continue;
  9998. }
  9999. if (pool->last_work_copy) {
  10000. mutex_lock(&pool->last_work_lock);
  10001. struct work *last_work = pool->last_work_copy;
  10002. if (!last_work)
  10003. {}
  10004. else
  10005. if (can_roll(last_work) && should_roll(last_work)) {
  10006. struct timeval tv_now;
  10007. cgtime(&tv_now);
  10008. free_work(work);
  10009. work = make_clone(pool->last_work_copy);
  10010. mutex_unlock(&pool->last_work_lock);
  10011. roll_work(work);
  10012. applog(LOG_DEBUG, "Generated work from latest GBT job in get_work_thread with %d seconds left", (int)blkmk_time_left(work->tmpl, tv_now.tv_sec));
  10013. stage_work(work);
  10014. continue;
  10015. } else if (last_work->tmpl && pool->proto == PLP_GETBLOCKTEMPLATE && blkmk_work_left(last_work->tmpl) > (unsigned long)mining_threads) {
  10016. // Don't free last_work_copy, since it is used to detect upstream provides plenty of work per template
  10017. } else {
  10018. free_work(last_work);
  10019. pool->last_work_copy = NULL;
  10020. }
  10021. mutex_unlock(&pool->last_work_lock);
  10022. }
  10023. if (clone_available()) {
  10024. applog(LOG_DEBUG, "Cloned getwork work");
  10025. free_work(work);
  10026. continue;
  10027. }
  10028. if (opt_benchmark) {
  10029. get_benchmark_work(work);
  10030. applog(LOG_DEBUG, "Generated benchmark work");
  10031. stage_work(work);
  10032. continue;
  10033. }
  10034. work->pool = pool;
  10035. ce = pop_curl_entry3(pool, 2);
  10036. /* obtain new work from bitcoin via JSON-RPC */
  10037. if (!get_upstream_work(work, ce->curl)) {
  10038. struct pool *next_pool;
  10039. /* Make sure the pool just hasn't stopped serving
  10040. * requests but is up as we'll keep hammering it */
  10041. push_curl_entry(ce, pool);
  10042. ++pool->seq_getfails;
  10043. pool_died(pool);
  10044. next_pool = select_pool(!opt_fail_only);
  10045. if (pool == next_pool) {
  10046. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  10047. cgsleep_ms(5000);
  10048. } else {
  10049. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, failover activated", pool->pool_no);
  10050. pool = next_pool;
  10051. }
  10052. goto retry;
  10053. }
  10054. if (ts >= max_staged)
  10055. pool_tclear(pool, &pool->lagging);
  10056. if (pool_tclear(pool, &pool->idle))
  10057. pool_resus(pool);
  10058. applog(LOG_DEBUG, "Generated getwork work");
  10059. stage_work(work);
  10060. push_curl_entry(ce, pool);
  10061. }
  10062. return 0;
  10063. }