miner.c 257 KB

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