miner.c 258 KB

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