miner.c 259 KB

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