miner.c 199 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #include <sys/stat.h>
  28. #include <sys/types.h>
  29. #ifndef WIN32
  30. #include <sys/resource.h>
  31. #include <sys/socket.h>
  32. #else
  33. #include <winsock2.h>
  34. #endif
  35. #include <ccan/opt/opt.h>
  36. #include <jansson.h>
  37. #include <curl/curl.h>
  38. #include <libgen.h>
  39. #include <sha2.h>
  40. #include <blkmaker.h>
  41. #include <blkmaker_jansson.h>
  42. #include <blktemplate.h>
  43. #include "compat.h"
  44. #include "miner.h"
  45. #include "findnonce.h"
  46. #include "adl.h"
  47. #include "driver-cpu.h"
  48. #include "driver-opencl.h"
  49. #include "bench_block.h"
  50. #include "scrypt.h"
  51. #if defined(unix)
  52. #include <errno.h>
  53. #include <fcntl.h>
  54. #include <sys/wait.h>
  55. #endif
  56. #ifdef USE_SCRYPT
  57. #include "scrypt.h"
  58. #endif
  59. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_MODMINER)
  60. # define USE_FPGA
  61. # define USE_FPGA_SERIAL
  62. #elif defined(USE_ZTEX)
  63. # define USE_FPGA
  64. #endif
  65. enum workio_commands {
  66. WC_GET_WORK,
  67. WC_SUBMIT_WORK,
  68. };
  69. struct workio_cmd {
  70. enum workio_commands cmd;
  71. struct thr_info *thr;
  72. struct work *work;
  73. struct pool *pool;
  74. struct list_head list;
  75. };
  76. struct strategies strategies[] = {
  77. { "Failover" },
  78. { "Round Robin" },
  79. { "Rotate" },
  80. { "Load Balance" },
  81. { "Balance" },
  82. };
  83. static char packagename[255];
  84. bool opt_protocol;
  85. static bool opt_benchmark;
  86. static bool want_longpoll = true;
  87. static bool want_gbt = true;
  88. static bool want_stratum = true;
  89. #if BLKMAKER_VERSION < 1
  90. const
  91. #endif
  92. char *opt_coinbase_sig;
  93. bool have_longpoll;
  94. bool want_per_device_stats;
  95. bool use_syslog;
  96. bool opt_quiet;
  97. bool opt_realquiet;
  98. bool opt_loginput;
  99. const int opt_cutofftemp = 95;
  100. int opt_hysteresis = 3;
  101. static int opt_retries = -1;
  102. int opt_fail_pause = 5;
  103. int opt_log_interval = 5;
  104. int opt_queue = 1;
  105. int opt_scantime = 60;
  106. int opt_expiry = 120;
  107. int opt_bench_algo = -1;
  108. static const bool opt_time = true;
  109. unsigned long long global_hashrate;
  110. #ifdef HAVE_OPENCL
  111. int opt_dynamic_interval = 7;
  112. int nDevs;
  113. int opt_g_threads = 2;
  114. int gpu_threads;
  115. #endif
  116. #ifdef USE_SCRYPT
  117. static char detect_algo = 1;
  118. bool opt_scrypt;
  119. #else
  120. static char detect_algo;
  121. #endif
  122. bool opt_restart = true;
  123. static bool opt_nogpu;
  124. struct list_head scan_devices;
  125. static signed int devices_enabled;
  126. static bool opt_removedisabled;
  127. int total_devices;
  128. struct cgpu_info **devices;
  129. bool have_opencl;
  130. int opt_n_threads = -1;
  131. int mining_threads;
  132. int num_processors;
  133. #ifdef HAVE_CURSES
  134. bool use_curses = true;
  135. #else
  136. bool use_curses;
  137. #endif
  138. static bool opt_submit_stale = true;
  139. static int opt_shares;
  140. static int opt_submit_threads = 0x40;
  141. bool opt_fail_only;
  142. bool opt_autofan;
  143. bool opt_autoengine;
  144. bool opt_noadl;
  145. char *opt_api_allow = NULL;
  146. char *opt_api_groups;
  147. char *opt_api_description = PACKAGE_STRING;
  148. int opt_api_port = 4028;
  149. bool opt_api_listen;
  150. bool opt_api_network;
  151. bool opt_delaynet;
  152. bool opt_disable_pool = true;
  153. char *opt_icarus_options = NULL;
  154. char *opt_icarus_timing = NULL;
  155. bool opt_worktime;
  156. char *opt_kernel_path;
  157. char *cgminer_path;
  158. #if defined(USE_BITFORCE)
  159. bool opt_bfl_noncerange;
  160. #endif
  161. #define QUIET (opt_quiet || opt_realquiet)
  162. struct thr_info *thr_info;
  163. static int work_thr_id;
  164. static int stage_thr_id;
  165. static int watchpool_thr_id;
  166. static int watchdog_thr_id;
  167. #ifdef HAVE_CURSES
  168. static int input_thr_id;
  169. #endif
  170. int gpur_thr_id;
  171. static int api_thr_id;
  172. static int total_threads;
  173. static pthread_mutex_t hash_lock;
  174. static pthread_mutex_t qd_lock;
  175. static pthread_mutex_t *stgd_lock;
  176. pthread_mutex_t console_lock;
  177. pthread_mutex_t ch_lock;
  178. static pthread_rwlock_t blk_lock;
  179. static pthread_mutex_t sshare_lock;
  180. pthread_rwlock_t netacc_lock;
  181. static pthread_mutex_t lp_lock;
  182. static pthread_cond_t lp_cond;
  183. pthread_mutex_t restart_lock;
  184. pthread_cond_t restart_cond;
  185. double total_mhashes_done;
  186. static struct timeval total_tv_start, total_tv_end;
  187. static struct timeval miner_started;
  188. pthread_mutex_t control_lock;
  189. static pthread_mutex_t submitting_lock;
  190. static int submitting;
  191. static struct list_head submit_waiting;
  192. int hw_errors;
  193. int total_accepted, total_rejected, total_diff1;
  194. float total_accepted_weighed;
  195. int total_getworks, total_stale, total_discarded;
  196. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  197. static int total_queued, staged_rollable;
  198. unsigned int new_blocks;
  199. unsigned int found_blocks;
  200. unsigned int local_work;
  201. unsigned int total_go, total_ro;
  202. struct pool **pools;
  203. static struct pool *currentpool = NULL;
  204. int total_pools, enabled_pools;
  205. enum pool_strategy pool_strategy = POOL_FAILOVER;
  206. int opt_rotate_period;
  207. static int total_urls, total_users, total_passes;
  208. static
  209. #ifndef HAVE_CURSES
  210. const
  211. #endif
  212. bool curses_active;
  213. static char current_block[37];
  214. static char *current_hash;
  215. static uint32_t current_block_id;
  216. char *current_fullhash;
  217. static char datestamp[40];
  218. static char blocktime[30];
  219. struct timeval block_timeval;
  220. struct block {
  221. char hash[37];
  222. UT_hash_handle hh;
  223. int block_no;
  224. };
  225. static struct block *blocks = NULL;
  226. int swork_id;
  227. /* For creating a hash database of stratum shares submitted that have not had
  228. * a response yet */
  229. struct stratum_share {
  230. UT_hash_handle hh;
  231. bool block;
  232. struct work work;
  233. int id;
  234. };
  235. static struct stratum_share *stratum_shares = NULL;
  236. char *opt_socks_proxy = NULL;
  237. static const char def_conf[] = "bfgminer.conf";
  238. static bool config_loaded;
  239. static int include_count;
  240. #define JSON_INCLUDE_CONF "include"
  241. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  242. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  243. #define JSON_MAX_DEPTH 10
  244. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  245. #if defined(unix)
  246. static char *opt_stderr_cmd = NULL;
  247. static int forkpid;
  248. #endif // defined(unix)
  249. bool ping = true;
  250. struct sigaction termhandler, inthandler, segvhandler, bushandler, illhandler;
  251. struct thread_q *getq;
  252. static int total_work;
  253. struct work *staged_work = NULL;
  254. struct schedtime {
  255. bool enable;
  256. struct tm tm;
  257. };
  258. struct schedtime schedstart;
  259. struct schedtime schedstop;
  260. bool sched_paused;
  261. static bool time_before(struct tm *tm1, struct tm *tm2)
  262. {
  263. if (tm1->tm_hour < tm2->tm_hour)
  264. return true;
  265. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  266. return true;
  267. return false;
  268. }
  269. static bool should_run(void)
  270. {
  271. struct timeval tv;
  272. struct tm tm;
  273. bool within_range;
  274. if (!schedstart.enable && !schedstop.enable)
  275. return true;
  276. gettimeofday(&tv, NULL);
  277. tm = *localtime(&tv.tv_sec);
  278. // NOTE: This is delicately balanced so that should_run is always false if schedstart==schedstop
  279. if (time_before(&schedstop.tm, &schedstart.tm))
  280. within_range = (time_before(&tm, &schedstop.tm) || !time_before(&tm, &schedstart.tm));
  281. else
  282. within_range = (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm));
  283. if (within_range && !schedstop.enable)
  284. /* This is a once off event with no stop time set */
  285. schedstart.enable = false;
  286. return within_range;
  287. }
  288. void get_datestamp(char *f, struct timeval *tv)
  289. {
  290. struct tm *tm;
  291. tm = localtime(&tv->tv_sec);
  292. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  293. tm->tm_year + 1900,
  294. tm->tm_mon + 1,
  295. tm->tm_mday,
  296. tm->tm_hour,
  297. tm->tm_min,
  298. tm->tm_sec);
  299. }
  300. void get_timestamp(char *f, struct timeval *tv)
  301. {
  302. struct tm *tm;
  303. tm = localtime(&tv->tv_sec);
  304. sprintf(f, "[%02d:%02d:%02d]",
  305. tm->tm_hour,
  306. tm->tm_min,
  307. tm->tm_sec);
  308. }
  309. static void applog_and_exit(const char *fmt, ...)
  310. {
  311. va_list ap;
  312. va_start(ap, fmt);
  313. vapplog(LOG_ERR, fmt, ap);
  314. va_end(ap);
  315. exit(1);
  316. }
  317. static pthread_mutex_t sharelog_lock;
  318. static FILE *sharelog_file = NULL;
  319. static void sharelog(const char*disposition, const struct work*work)
  320. {
  321. char *target, *hash, *data;
  322. struct cgpu_info *cgpu;
  323. unsigned long int t;
  324. struct pool *pool;
  325. int thr_id, rv;
  326. char s[1024];
  327. size_t ret;
  328. if (!sharelog_file)
  329. return;
  330. thr_id = work->thr_id;
  331. cgpu = thr_info[thr_id].cgpu;
  332. pool = work->pool;
  333. t = (unsigned long int)(work->tv_work_found.tv_sec);
  334. target = bin2hex(work->target, sizeof(work->target));
  335. hash = bin2hex(work->hash, sizeof(work->hash));
  336. data = bin2hex(work->data, sizeof(work->data));
  337. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  338. rv = snprintf(s, sizeof(s), "%lu,%s,%s,%s,%s%u,%u,%s,%s\n", t, disposition, target, pool->rpc_url, cgpu->api->name, cgpu->device_id, thr_id, hash, data);
  339. free(target);
  340. free(hash);
  341. free(data);
  342. if (rv >= (int)(sizeof(s)))
  343. s[sizeof(s) - 1] = '\0';
  344. else if (rv < 0) {
  345. applog(LOG_ERR, "sharelog printf error");
  346. return;
  347. }
  348. mutex_lock(&sharelog_lock);
  349. ret = fwrite(s, rv, 1, sharelog_file);
  350. fflush(sharelog_file);
  351. mutex_unlock(&sharelog_lock);
  352. if (ret != 1)
  353. applog(LOG_ERR, "sharelog fwrite error");
  354. }
  355. /* Return value is ignored if not called from add_pool_details */
  356. struct pool *add_pool(void)
  357. {
  358. struct pool *pool;
  359. pool = calloc(sizeof(struct pool), 1);
  360. if (!pool)
  361. quit(1, "Failed to malloc pool in add_pool");
  362. pool->pool_no = pool->prio = total_pools;
  363. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  364. quit(1, "Failed to pthread_mutex_init in add_pool");
  365. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  366. quit(1, "Failed to pthread_cond_init in add_pool");
  367. if (unlikely(pthread_mutex_init(&pool->stratum_lock, NULL)))
  368. quit(1, "Failed to pthread_mutex_init in add_pool");
  369. INIT_LIST_HEAD(&pool->curlring);
  370. /* Make sure the pool doesn't think we've been idle since time 0 */
  371. pool->tv_idle.tv_sec = ~0UL;
  372. pool->rpc_proxy = NULL;
  373. pool->lp_socket = CURL_SOCKET_BAD;
  374. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  375. pools[total_pools++] = pool;
  376. return pool;
  377. }
  378. /* Pool variant of test and set */
  379. static bool pool_tset(struct pool *pool, bool *var)
  380. {
  381. bool ret;
  382. mutex_lock(&pool->pool_lock);
  383. ret = *var;
  384. *var = true;
  385. mutex_unlock(&pool->pool_lock);
  386. return ret;
  387. }
  388. bool pool_tclear(struct pool *pool, bool *var)
  389. {
  390. bool ret;
  391. mutex_lock(&pool->pool_lock);
  392. ret = *var;
  393. *var = false;
  394. mutex_unlock(&pool->pool_lock);
  395. return ret;
  396. }
  397. struct pool *current_pool(void)
  398. {
  399. struct pool *pool;
  400. mutex_lock(&control_lock);
  401. pool = currentpool;
  402. mutex_unlock(&control_lock);
  403. return pool;
  404. }
  405. char *set_int_range(const char *arg, int *i, int min, int max)
  406. {
  407. char *err = opt_set_intval(arg, i);
  408. if (err)
  409. return err;
  410. if (*i < min || *i > max)
  411. return "Value out of range";
  412. return NULL;
  413. }
  414. static char *set_int_0_to_9999(const char *arg, int *i)
  415. {
  416. return set_int_range(arg, i, 0, 9999);
  417. }
  418. static char *set_int_1_to_65535(const char *arg, int *i)
  419. {
  420. return set_int_range(arg, i, 1, 65535);
  421. }
  422. static char *set_int_0_to_10(const char *arg, int *i)
  423. {
  424. return set_int_range(arg, i, 0, 10);
  425. }
  426. static char *set_int_1_to_10(const char *arg, int *i)
  427. {
  428. return set_int_range(arg, i, 1, 10);
  429. }
  430. char *set_strdup(const char *arg, char **p)
  431. {
  432. *p = strdup((char *)arg);
  433. return NULL;
  434. }
  435. #ifdef HAVE_LIBUDEV
  436. #include <libudev.h>
  437. #endif
  438. static
  439. char* add_serial_all(char*arg, char*p) {
  440. #ifdef HAVE_LIBUDEV
  441. struct udev *udev = udev_new();
  442. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  443. struct udev_list_entry *list_entry;
  444. udev_enumerate_add_match_subsystem(enumerate, "tty");
  445. udev_enumerate_add_match_property(enumerate, "ID_SERIAL", "*");
  446. udev_enumerate_scan_devices(enumerate);
  447. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  448. struct udev_device *device = udev_device_new_from_syspath(
  449. udev_enumerate_get_udev(enumerate),
  450. udev_list_entry_get_name(list_entry)
  451. );
  452. if (!device)
  453. continue;
  454. const char *devpath = udev_device_get_devnode(device);
  455. if (devpath) {
  456. size_t pLen = p - arg;
  457. size_t dLen = strlen(devpath) + 1;
  458. char dev[dLen + pLen];
  459. memcpy(dev, arg, pLen);
  460. memcpy(&dev[pLen], devpath, dLen);
  461. applog(LOG_DEBUG, "scan-serial: libudev all-adding %s", dev);
  462. string_elist_add(dev, &scan_devices);
  463. }
  464. udev_device_unref(device);
  465. }
  466. udev_enumerate_unref(enumerate);
  467. udev_unref(udev);
  468. return NULL;
  469. #elif defined(WIN32)
  470. size_t bufLen = 0x10; // temp!
  471. tryagain: ;
  472. char buf[bufLen];
  473. if (!QueryDosDevice(NULL, buf, bufLen)) {
  474. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  475. bufLen *= 2;
  476. applog(LOG_DEBUG, "scan-serial: QueryDosDevice returned insufficent buffer error; enlarging to %llx", (unsigned long long)bufLen);
  477. goto tryagain;
  478. }
  479. return "scan-serial: Error occurred trying to enumerate COM ports with QueryDosDevice";
  480. }
  481. size_t tLen = p - arg;
  482. char dev[12 + tLen];
  483. memcpy(dev, arg, tLen);
  484. memcpy(&dev[tLen], "\\\\.\\", 4);
  485. char *devp = &dev[tLen + 4];
  486. for (char *t = buf; *t; t += tLen) {
  487. tLen = strlen(t) + 1;
  488. if (strncmp("COM", t, 3))
  489. continue;
  490. memcpy(devp, t, tLen);
  491. applog(LOG_DEBUG, "scan-serial: QueryDosDevice all-adding %s", dev);
  492. string_elist_add(dev, &scan_devices);
  493. }
  494. return NULL;
  495. #else
  496. return "scan-serial 'all' is not supported on this platform";
  497. #endif
  498. }
  499. #ifdef USE_FPGA_SERIAL
  500. static char *add_serial(char *arg)
  501. {
  502. char *p = strchr(arg, ':');
  503. if (p)
  504. ++p;
  505. else
  506. p = arg;
  507. if (!strcasecmp(p, "all")) {
  508. return add_serial_all(arg, p);
  509. }
  510. string_elist_add(arg, &scan_devices);
  511. return NULL;
  512. }
  513. #endif
  514. static char *set_devices(char *arg)
  515. {
  516. int i = strtol(arg, &arg, 0);
  517. if (*arg) {
  518. if (*arg == '?') {
  519. devices_enabled = -1;
  520. return NULL;
  521. }
  522. return "Invalid device number";
  523. }
  524. if (i < 0 || i >= (int)(sizeof(devices_enabled) * 8) - 1)
  525. return "Invalid device number";
  526. devices_enabled |= 1 << i;
  527. return NULL;
  528. }
  529. static char *set_balance(enum pool_strategy *strategy)
  530. {
  531. *strategy = POOL_BALANCE;
  532. return NULL;
  533. }
  534. static char *set_loadbalance(enum pool_strategy *strategy)
  535. {
  536. *strategy = POOL_LOADBALANCE;
  537. return NULL;
  538. }
  539. static char *set_rotate(const char *arg, int *i)
  540. {
  541. pool_strategy = POOL_ROTATE;
  542. return set_int_range(arg, i, 0, 9999);
  543. }
  544. static char *set_rr(enum pool_strategy *strategy)
  545. {
  546. *strategy = POOL_ROUNDROBIN;
  547. return NULL;
  548. }
  549. /* Detect that url is for a stratum protocol either via the presence of
  550. * stratum+tcp or by detecting a stratum server response */
  551. bool detect_stratum(struct pool *pool, char *url)
  552. {
  553. if (opt_scrypt)
  554. return false;
  555. if (!extract_sockaddr(pool, url))
  556. return false;
  557. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  558. pool->has_stratum = true;
  559. pool->stratum_url = pool->sockaddr_url;
  560. return true;
  561. }
  562. return false;
  563. }
  564. static char *set_url(char *arg)
  565. {
  566. struct pool *pool;
  567. total_urls++;
  568. if (total_urls > total_pools)
  569. add_pool();
  570. pool = pools[total_urls - 1];
  571. if (detect_stratum(pool, arg)) {
  572. if (!pool->rpc_url)
  573. pool->rpc_url = strdup(pool->stratum_url);
  574. return NULL;
  575. }
  576. opt_set_charp(arg, &pool->rpc_url);
  577. if (strncmp(arg, "http://", 7) &&
  578. strncmp(arg, "https://", 8)) {
  579. char *httpinput;
  580. httpinput = malloc(255);
  581. if (!httpinput)
  582. quit(1, "Failed to malloc httpinput");
  583. strcpy(httpinput, "http://");
  584. strncat(httpinput, arg, 248);
  585. pool->rpc_url = httpinput;
  586. }
  587. return NULL;
  588. }
  589. static char *set_user(const char *arg)
  590. {
  591. struct pool *pool;
  592. total_users++;
  593. if (total_users > total_pools)
  594. add_pool();
  595. pool = pools[total_users - 1];
  596. opt_set_charp(arg, &pool->rpc_user);
  597. return NULL;
  598. }
  599. static char *set_pass(const char *arg)
  600. {
  601. struct pool *pool;
  602. total_passes++;
  603. if (total_passes > total_pools)
  604. add_pool();
  605. pool = pools[total_passes - 1];
  606. opt_set_charp(arg, &pool->rpc_pass);
  607. return NULL;
  608. }
  609. static char *set_userpass(const char *arg)
  610. {
  611. struct pool *pool;
  612. char *updup;
  613. if (total_users != total_passes)
  614. return "User + pass options must be balanced before userpass";
  615. ++total_users;
  616. ++total_passes;
  617. if (total_users > total_pools)
  618. add_pool();
  619. pool = pools[total_users - 1];
  620. updup = strdup(arg);
  621. opt_set_charp(arg, &pool->rpc_userpass);
  622. pool->rpc_user = strtok(updup, ":");
  623. if (!pool->rpc_user)
  624. return "Failed to find : delimited user info";
  625. pool->rpc_pass = strtok(NULL, ":");
  626. if (!pool->rpc_pass)
  627. return "Failed to find : delimited pass info";
  628. return NULL;
  629. }
  630. static char *set_pool_proxy(const char *arg)
  631. {
  632. struct pool *pool;
  633. if (!total_pools)
  634. return "Usage of --pool-proxy before pools are defined does not make sense";
  635. if (!our_curl_supports_proxy_uris())
  636. return "Your installed cURL library does not support proxy URIs. At least version 7.21.7 is required.";
  637. pool = pools[total_pools - 1];
  638. opt_set_charp(arg, &pool->rpc_proxy);
  639. return NULL;
  640. }
  641. static char *enable_debug(bool *flag)
  642. {
  643. *flag = true;
  644. opt_debug_console = true;
  645. /* Turn on verbose output, too. */
  646. opt_log_output = true;
  647. return NULL;
  648. }
  649. static char *set_schedtime(const char *arg, struct schedtime *st)
  650. {
  651. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  652. {
  653. if (strcasecmp(arg, "now"))
  654. return "Invalid time set, should be HH:MM";
  655. } else
  656. schedstop.tm.tm_sec = 0;
  657. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  658. return "Invalid time set.";
  659. st->enable = true;
  660. return NULL;
  661. }
  662. static char* set_sharelog(char *arg)
  663. {
  664. char *r = "";
  665. long int i = strtol(arg, &r, 10);
  666. if ((!*r) && i >= 0 && i <= INT_MAX) {
  667. sharelog_file = fdopen((int)i, "a");
  668. if (!sharelog_file)
  669. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  670. } else if (!strcmp(arg, "-")) {
  671. sharelog_file = stdout;
  672. if (!sharelog_file)
  673. applog(LOG_ERR, "Standard output missing for share log");
  674. } else {
  675. sharelog_file = fopen(arg, "a");
  676. if (!sharelog_file)
  677. applog(LOG_ERR, "Failed to open %s for share log", arg);
  678. }
  679. return NULL;
  680. }
  681. static char *temp_cutoff_str = "";
  682. static char *temp_target_str = "";
  683. char *set_temp_cutoff(char *arg)
  684. {
  685. int val;
  686. if (!(arg && arg[0]))
  687. return "Invalid parameters for set temp cutoff";
  688. val = atoi(arg);
  689. if (val < 0 || val > 200)
  690. return "Invalid value passed to set temp cutoff";
  691. temp_cutoff_str = arg;
  692. return NULL;
  693. }
  694. char *set_temp_target(char *arg)
  695. {
  696. int val;
  697. if (!(arg && arg[0]))
  698. return "Invalid parameters for set temp target";
  699. val = atoi(arg);
  700. if (val < 0 || val > 200)
  701. return "Invalid value passed to set temp target";
  702. temp_target_str = arg;
  703. return NULL;
  704. }
  705. // For a single element string, this always returns the number (for all calls)
  706. // For multi-element strings, it returns each element as a number in order, and 0 when there are no more
  707. static int temp_strtok(char *base, char **n)
  708. {
  709. char *i = *n;
  710. char *p = strchr(i, ',');
  711. if (p) {
  712. p[0] = '\0';
  713. *n = &p[1];
  714. }
  715. else
  716. if (base != i)
  717. *n = strchr(i, '\0');
  718. return atoi(i);
  719. }
  720. static void load_temp_config()
  721. {
  722. int i, val = 0, target_off;
  723. char *cutoff_n, *target_n;
  724. struct cgpu_info *cgpu;
  725. cutoff_n = temp_cutoff_str;
  726. target_n = temp_target_str;
  727. for (i = 0; i < total_devices; ++i) {
  728. cgpu = devices[i];
  729. // cutoff default may be specified by driver during probe; otherwise, opt_cutofftemp (const)
  730. if (!cgpu->cutofftemp)
  731. cgpu->cutofftemp = opt_cutofftemp;
  732. // target default may be specified by driver, and is moved with offset; otherwise, offset minus 6
  733. if (cgpu->targettemp)
  734. target_off = cgpu->targettemp - cgpu->cutofftemp;
  735. else
  736. target_off = -6;
  737. val = temp_strtok(temp_cutoff_str, &cutoff_n);
  738. if (val < 0 || val > 200)
  739. quit(1, "Invalid value passed to set temp cutoff");
  740. if (val)
  741. cgpu->cutofftemp = val;
  742. val = temp_strtok(temp_target_str, &target_n);
  743. if (val < 0 || val > 200)
  744. quit(1, "Invalid value passed to set temp target");
  745. if (val)
  746. cgpu->targettemp = val;
  747. else
  748. cgpu->targettemp = cgpu->cutofftemp + target_off;
  749. applog(LOG_DEBUG, "%s %u: Set temperature config: target=%d cutoff=%d",
  750. cgpu->api->name, cgpu->device_id,
  751. cgpu->targettemp, cgpu->cutofftemp);
  752. }
  753. if (cutoff_n != temp_cutoff_str && cutoff_n[0])
  754. quit(1, "Too many values passed to set temp cutoff");
  755. if (target_n != temp_target_str && target_n[0])
  756. quit(1, "Too many values passed to set temp target");
  757. }
  758. static char *set_api_allow(const char *arg)
  759. {
  760. opt_set_charp(arg, &opt_api_allow);
  761. return NULL;
  762. }
  763. static char *set_api_groups(const char *arg)
  764. {
  765. opt_set_charp(arg, &opt_api_groups);
  766. return NULL;
  767. }
  768. static char *set_api_description(const char *arg)
  769. {
  770. opt_set_charp(arg, &opt_api_description);
  771. return NULL;
  772. }
  773. #ifdef USE_ICARUS
  774. static char *set_icarus_options(const char *arg)
  775. {
  776. opt_set_charp(arg, &opt_icarus_options);
  777. return NULL;
  778. }
  779. static char *set_icarus_timing(const char *arg)
  780. {
  781. opt_set_charp(arg, &opt_icarus_timing);
  782. return NULL;
  783. }
  784. #endif
  785. __maybe_unused
  786. static char *set_null(const char __maybe_unused *arg)
  787. {
  788. return NULL;
  789. }
  790. /* These options are available from config file or commandline */
  791. static struct opt_table opt_config_table[] = {
  792. #ifdef WANT_CPUMINE
  793. OPT_WITH_ARG("--algo|-a",
  794. set_algo, show_algo, &opt_algo,
  795. "Specify sha256 implementation for CPU mining:\n"
  796. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  797. "\n\tc\t\tLinux kernel sha256, implemented in C"
  798. #ifdef WANT_SSE2_4WAY
  799. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  800. #endif
  801. #ifdef WANT_VIA_PADLOCK
  802. "\n\tvia\t\tVIA padlock implementation"
  803. #endif
  804. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  805. #ifdef WANT_CRYPTOPP_ASM32
  806. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  807. #endif
  808. #ifdef WANT_X8632_SSE2
  809. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  810. #endif
  811. #ifdef WANT_X8664_SSE2
  812. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  813. #endif
  814. #ifdef WANT_X8664_SSE4
  815. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  816. #endif
  817. #ifdef WANT_ALTIVEC_4WAY
  818. "\n\taltivec_4way\tAltivec implementation for PowerPC G4 and G5 machines"
  819. #endif
  820. ),
  821. #endif
  822. OPT_WITH_ARG("--api-allow",
  823. set_api_allow, NULL, NULL,
  824. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  825. OPT_WITH_ARG("--api-description",
  826. set_api_description, NULL, NULL,
  827. "Description placed in the API status header, default: BFGMiner version"),
  828. OPT_WITH_ARG("--api-groups",
  829. set_api_groups, NULL, NULL,
  830. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  831. OPT_WITHOUT_ARG("--api-listen",
  832. opt_set_bool, &opt_api_listen,
  833. "Enable API, default: disabled"),
  834. OPT_WITHOUT_ARG("--api-network",
  835. opt_set_bool, &opt_api_network,
  836. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  837. OPT_WITH_ARG("--api-port",
  838. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  839. "Port number of miner API"),
  840. #ifdef HAVE_ADL
  841. OPT_WITHOUT_ARG("--auto-fan",
  842. opt_set_bool, &opt_autofan,
  843. "Automatically adjust all GPU fan speeds to maintain a target temperature"),
  844. OPT_WITHOUT_ARG("--auto-gpu",
  845. opt_set_bool, &opt_autoengine,
  846. "Automatically adjust all GPU engine clock speeds to maintain a target temperature"),
  847. #endif
  848. OPT_WITHOUT_ARG("--balance",
  849. set_balance, &pool_strategy,
  850. "Change multipool strategy from failover to even share balance"),
  851. OPT_WITHOUT_ARG("--benchmark",
  852. opt_set_bool, &opt_benchmark,
  853. "Run BFGMiner in benchmark mode - produces no shares"),
  854. #if defined(USE_BITFORCE)
  855. OPT_WITHOUT_ARG("--bfl-range",
  856. opt_set_bool, &opt_bfl_noncerange,
  857. "Use nonce range on bitforce devices if supported"),
  858. #endif
  859. #ifdef WANT_CPUMINE
  860. OPT_WITH_ARG("--bench-algo|-b",
  861. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  862. opt_hidden),
  863. #endif
  864. #if BLKMAKER_VERSION > 0
  865. OPT_WITH_ARG("--coinbase-sig",
  866. set_strdup, NULL, &opt_coinbase_sig,
  867. "Set coinbase signature when possible"),
  868. OPT_WITH_ARG("--coinbase|--cbsig|--cb-sig|--cb|--prayer",
  869. set_strdup, NULL, &opt_coinbase_sig,
  870. opt_hidden),
  871. #endif
  872. #ifdef WANT_CPUMINE
  873. OPT_WITH_ARG("--cpu-threads|-t",
  874. force_nthreads_int, opt_show_intval, &opt_n_threads,
  875. "Number of miner CPU threads"),
  876. #endif
  877. OPT_WITHOUT_ARG("--debug|-D",
  878. enable_debug, &opt_debug,
  879. "Enable debug output"),
  880. OPT_WITHOUT_ARG("--debuglog",
  881. opt_set_bool, &opt_debug,
  882. "Enable debug logging"),
  883. OPT_WITH_ARG("--device|-d",
  884. set_devices, NULL, NULL,
  885. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  886. OPT_WITHOUT_ARG("--disable-gpu|-G",
  887. opt_set_bool, &opt_nogpu,
  888. #ifdef HAVE_OPENCL
  889. "Disable GPU mining even if suitable devices exist"
  890. #else
  891. opt_hidden
  892. #endif
  893. ),
  894. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(USE_FPGA))
  895. OPT_WITHOUT_ARG("--enable-cpu|-C",
  896. opt_set_bool, &opt_usecpu,
  897. "Enable CPU mining with other mining (default: no CPU mining if other devices exist)"),
  898. #endif
  899. OPT_WITH_ARG("--expiry|-E",
  900. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  901. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  902. OPT_WITHOUT_ARG("--failover-only",
  903. opt_set_bool, &opt_fail_only,
  904. "Don't leak work to backup pools when primary pool is lagging"),
  905. #ifdef HAVE_OPENCL
  906. OPT_WITH_ARG("--gpu-dyninterval",
  907. set_int_1_to_65535, opt_show_intval, &opt_dynamic_interval,
  908. "Set the refresh interval in ms for GPUs using dynamic intensity"),
  909. OPT_WITH_ARG("--gpu-platform",
  910. set_int_0_to_9999, opt_show_intval, &opt_platform_id,
  911. "Select OpenCL platform ID to use for GPU mining"),
  912. OPT_WITH_ARG("--gpu-threads|-g",
  913. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  914. "Number of threads per GPU (1 - 10)"),
  915. #ifdef HAVE_ADL
  916. OPT_WITH_ARG("--gpu-engine",
  917. set_gpu_engine, NULL, NULL,
  918. "GPU engine (over)clock range in Mhz - one value, range and/or comma separated list (e.g. 850-900,900,750-850)"),
  919. OPT_WITH_ARG("--gpu-fan",
  920. set_gpu_fan, NULL, NULL,
  921. "GPU fan percentage range - one value, range and/or comma separated list (e.g. 0-85,85,65)"),
  922. OPT_WITH_ARG("--gpu-map",
  923. set_gpu_map, NULL, NULL,
  924. "Map OpenCL to ADL device order manually, paired CSV (e.g. 1:0,2:1 maps OpenCL 1 to ADL 0, 2 to 1)"),
  925. OPT_WITH_ARG("--gpu-memclock",
  926. set_gpu_memclock, NULL, NULL,
  927. "Set the GPU memory (over)clock in Mhz - one value for all or separate by commas for per card"),
  928. OPT_WITH_ARG("--gpu-memdiff",
  929. set_gpu_memdiff, NULL, NULL,
  930. "Set a fixed difference in clock speed between the GPU and memory in auto-gpu mode"),
  931. OPT_WITH_ARG("--gpu-powertune",
  932. set_gpu_powertune, NULL, NULL,
  933. "Set the GPU powertune percentage - one value for all or separate by commas for per card"),
  934. OPT_WITHOUT_ARG("--gpu-reorder",
  935. opt_set_bool, &opt_reorder,
  936. "Attempt to reorder GPU devices according to PCI Bus ID"),
  937. OPT_WITH_ARG("--gpu-vddc",
  938. set_gpu_vddc, NULL, NULL,
  939. "Set the GPU voltage in Volts - one value for all or separate by commas for per card"),
  940. #endif
  941. #ifdef USE_SCRYPT
  942. OPT_WITH_ARG("--lookup-gap",
  943. set_lookup_gap, NULL, NULL,
  944. "Set GPU lookup gap for scrypt mining, comma separated"),
  945. #endif
  946. OPT_WITH_ARG("--intensity|-I",
  947. set_intensity, NULL, NULL,
  948. "Intensity of GPU scanning (d or " _MIN_INTENSITY_STR " -> " _MAX_INTENSITY_STR ", default: d to maintain desktop interactivity)"),
  949. #endif
  950. #if defined(HAVE_OPENCL) || defined(USE_MODMINER) || defined(USE_ZTEX)
  951. OPT_WITH_ARG("--kernel-path|-K",
  952. opt_set_charp, opt_show_charp, &opt_kernel_path,
  953. "Specify a path to where bitstream and kernel files are"),
  954. #endif
  955. #ifdef HAVE_OPENCL
  956. OPT_WITH_ARG("--kernel|-k",
  957. set_kernel, NULL, NULL,
  958. "Override sha256 kernel to use (diablo, poclbm, phatk or diakgcn) - one value or comma separated"),
  959. #endif
  960. #ifdef USE_ICARUS
  961. OPT_WITH_ARG("--icarus-options",
  962. set_icarus_options, NULL, NULL,
  963. opt_hidden),
  964. OPT_WITH_ARG("--icarus-timing",
  965. set_icarus_timing, NULL, NULL,
  966. opt_hidden),
  967. #endif
  968. OPT_WITHOUT_ARG("--load-balance",
  969. set_loadbalance, &pool_strategy,
  970. "Change multipool strategy from failover to efficiency based balance"),
  971. OPT_WITH_ARG("--log|-l",
  972. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  973. "Interval in seconds between log output"),
  974. #if defined(unix)
  975. OPT_WITH_ARG("--monitor|-m",
  976. opt_set_charp, NULL, &opt_stderr_cmd,
  977. "Use custom pipe cmd for output messages"),
  978. #endif // defined(unix)
  979. OPT_WITHOUT_ARG("--net-delay",
  980. opt_set_bool, &opt_delaynet,
  981. "Impose small delays in networking to not overload slow routers"),
  982. OPT_WITHOUT_ARG("--no-adl",
  983. opt_set_bool, &opt_noadl,
  984. #ifdef HAVE_ADL
  985. "Disable the ATI display library used for monitoring and setting GPU parameters"
  986. #else
  987. opt_hidden
  988. #endif
  989. ),
  990. OPT_WITHOUT_ARG("--no-gbt",
  991. opt_set_invbool, &want_gbt,
  992. "Disable getblocktemplate support"),
  993. OPT_WITHOUT_ARG("--no-longpoll",
  994. opt_set_invbool, &want_longpoll,
  995. "Disable X-Long-Polling support"),
  996. OPT_WITHOUT_ARG("--no-pool-disable",
  997. opt_set_invbool, &opt_disable_pool,
  998. "Do not automatically disable pools that continually reject shares"),
  999. OPT_WITHOUT_ARG("--no-restart",
  1000. opt_set_invbool, &opt_restart,
  1001. "Do not attempt to restart devices that hang or BFGMiner if it crashes"
  1002. ),
  1003. OPT_WITHOUT_ARG("--no-stratum",
  1004. opt_set_invbool, &want_stratum,
  1005. "Disable Stratum detection"),
  1006. OPT_WITHOUT_ARG("--no-submit-stale",
  1007. opt_set_invbool, &opt_submit_stale,
  1008. "Don't submit shares if they are detected as stale"),
  1009. OPT_WITH_ARG("--pass|-p",
  1010. set_pass, NULL, NULL,
  1011. "Password for bitcoin JSON-RPC server"),
  1012. OPT_WITHOUT_ARG("--per-device-stats",
  1013. opt_set_bool, &want_per_device_stats,
  1014. "Force verbose mode and output per-device statistics"),
  1015. OPT_WITH_ARG("--pool-proxy|-x",
  1016. set_pool_proxy, NULL, NULL,
  1017. "Proxy URI to use for connecting to just the previous-defined pool"),
  1018. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1019. opt_set_bool, &opt_protocol,
  1020. "Verbose dump of protocol-level activities"),
  1021. OPT_WITH_ARG("--queue|-Q",
  1022. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1023. "Minimum number of work items to have queued (0+)"),
  1024. OPT_WITHOUT_ARG("--quiet|-q",
  1025. opt_set_bool, &opt_quiet,
  1026. "Disable logging output, display status and errors"),
  1027. OPT_WITHOUT_ARG("--real-quiet",
  1028. opt_set_bool, &opt_realquiet,
  1029. "Disable all output"),
  1030. OPT_WITHOUT_ARG("--remove-disabled",
  1031. opt_set_bool, &opt_removedisabled,
  1032. "Remove disabled devices entirely, as if they didn't exist"),
  1033. OPT_WITH_ARG("--retries",
  1034. opt_set_intval, opt_show_intval, &opt_retries,
  1035. "Number of times to retry failed submissions before giving up (-1 means never)"),
  1036. OPT_WITH_ARG("--retry-pause",
  1037. set_null, NULL, NULL,
  1038. opt_hidden),
  1039. OPT_WITH_ARG("--rotate",
  1040. set_rotate, opt_show_intval, &opt_rotate_period,
  1041. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1042. OPT_WITHOUT_ARG("--round-robin",
  1043. set_rr, &pool_strategy,
  1044. "Change multipool strategy from failover to round robin on failure"),
  1045. #ifdef USE_FPGA_SERIAL
  1046. OPT_WITH_ARG("--scan-serial|-S",
  1047. add_serial, NULL, NULL,
  1048. "Serial port to probe for FPGA Mining device"),
  1049. #endif
  1050. OPT_WITH_ARG("--scan-time|-s",
  1051. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1052. "Upper bound on time spent scanning current work, in seconds"),
  1053. OPT_WITH_ARG("--sched-start",
  1054. set_schedtime, NULL, &schedstart,
  1055. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1056. OPT_WITH_ARG("--sched-stop",
  1057. set_schedtime, NULL, &schedstop,
  1058. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1059. #ifdef USE_SCRYPT
  1060. OPT_WITHOUT_ARG("--scrypt",
  1061. opt_set_bool, &opt_scrypt,
  1062. "Use the scrypt algorithm for mining (non-bitcoin)"),
  1063. #ifdef HAVE_OPENCL
  1064. OPT_WITH_ARG("--shaders",
  1065. set_shaders, NULL, NULL,
  1066. "GPU shaders per card for tuning scrypt, comma separated"),
  1067. #endif
  1068. #endif
  1069. OPT_WITH_ARG("--sharelog",
  1070. set_sharelog, NULL, NULL,
  1071. "Append share log to file"),
  1072. OPT_WITH_ARG("--shares",
  1073. opt_set_intval, NULL, &opt_shares,
  1074. "Quit after mining N shares (default: unlimited)"),
  1075. OPT_WITH_ARG("--socks-proxy",
  1076. opt_set_charp, NULL, &opt_socks_proxy,
  1077. "Set socks4 proxy (host:port)"),
  1078. OPT_WITHOUT_ARG("--submit-stale",
  1079. opt_set_bool, &opt_submit_stale,
  1080. opt_hidden),
  1081. OPT_WITHOUT_ARG("--submit-threads",
  1082. opt_set_intval, &opt_submit_threads,
  1083. "Maximum number of share submission threads (default: 64)"),
  1084. #ifdef HAVE_SYSLOG_H
  1085. OPT_WITHOUT_ARG("--syslog",
  1086. opt_set_bool, &use_syslog,
  1087. "Use system log for output messages (default: standard error)"),
  1088. #endif
  1089. #if defined(HAVE_ADL) || defined(USE_BITFORCE) || defined(USE_MODMINER)
  1090. OPT_WITH_ARG("--temp-cutoff",
  1091. set_temp_cutoff, opt_show_intval, &opt_cutofftemp,
  1092. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1093. #endif
  1094. #if defined(HAVE_ADL) || defined(USE_MODMINER)
  1095. OPT_WITH_ARG("--temp-hysteresis",
  1096. set_int_1_to_10, opt_show_intval, &opt_hysteresis,
  1097. "Set how much the temperature can fluctuate outside limits when automanaging speeds"),
  1098. #ifdef HAVE_ADL
  1099. OPT_WITH_ARG("--temp-overheat",
  1100. set_temp_overheat, opt_show_intval, &opt_overheattemp,
  1101. "Overheat temperature when automatically managing fan and GPU speeds, one value or comma separated list"),
  1102. #endif
  1103. OPT_WITH_ARG("--temp-target",
  1104. set_temp_target, NULL, NULL,
  1105. "Target temperature when automatically managing fan and clock speeds, one value or comma separated list"),
  1106. #endif
  1107. OPT_WITHOUT_ARG("--text-only|-T",
  1108. opt_set_invbool, &use_curses,
  1109. #ifdef HAVE_CURSES
  1110. "Disable ncurses formatted screen output"
  1111. #else
  1112. opt_hidden
  1113. #endif
  1114. ),
  1115. #if defined(USE_SCRYPT) && defined(HAVE_OPENCL)
  1116. OPT_WITH_ARG("--thread-concurrency",
  1117. set_thread_concurrency, NULL, NULL,
  1118. "Set GPU thread concurrency for scrypt mining, comma separated"),
  1119. #endif
  1120. OPT_WITH_ARG("--url|-o",
  1121. set_url, NULL, NULL,
  1122. "URL for bitcoin JSON-RPC server"),
  1123. OPT_WITH_ARG("--user|-u",
  1124. set_user, NULL, NULL,
  1125. "Username for bitcoin JSON-RPC server"),
  1126. #ifdef HAVE_OPENCL
  1127. OPT_WITH_ARG("--vectors|-v",
  1128. set_vector, NULL, NULL,
  1129. "Override detected optimal vector (1, 2 or 4) - one value or comma separated list"),
  1130. #endif
  1131. OPT_WITHOUT_ARG("--verbose",
  1132. opt_set_bool, &opt_log_output,
  1133. "Log verbose output to stderr as well as status output"),
  1134. #ifdef HAVE_OPENCL
  1135. OPT_WITH_ARG("--worksize|-w",
  1136. set_worksize, NULL, NULL,
  1137. "Override detected optimal worksize - one value or comma separated list"),
  1138. #endif
  1139. OPT_WITH_ARG("--userpass|-O",
  1140. set_userpass, NULL, NULL,
  1141. "Username:Password pair for bitcoin JSON-RPC server"),
  1142. OPT_WITHOUT_ARG("--worktime",
  1143. opt_set_bool, &opt_worktime,
  1144. "Display extra work time debug information"),
  1145. OPT_WITH_ARG("--pools",
  1146. opt_set_bool, NULL, NULL, opt_hidden),
  1147. OPT_ENDTABLE
  1148. };
  1149. static char *load_config(const char *arg, void __maybe_unused *unused);
  1150. static int fileconf_load;
  1151. static char *parse_config(json_t *config, bool fileconf)
  1152. {
  1153. static char err_buf[200];
  1154. struct opt_table *opt;
  1155. json_t *val;
  1156. if (fileconf && !fileconf_load)
  1157. fileconf_load = 1;
  1158. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1159. char *p, *name, *sp;
  1160. /* We don't handle subtables. */
  1161. assert(!(opt->type & OPT_SUBTABLE));
  1162. /* Pull apart the option name(s). */
  1163. name = strdup(opt->names);
  1164. for (p = strtok_r(name, "|", &sp); p; p = strtok_r(NULL, "|", &sp)) {
  1165. char *err = "Invalid value";
  1166. /* Ignore short options. */
  1167. if (p[1] != '-')
  1168. continue;
  1169. val = json_object_get(config, p+2);
  1170. if (!val)
  1171. continue;
  1172. if (opt->type & OPT_HASARG) {
  1173. if (json_is_string(val)) {
  1174. err = opt->cb_arg(json_string_value(val),
  1175. opt->u.arg);
  1176. } else if (json_is_number(val)) {
  1177. char buf[256], *p, *q;
  1178. snprintf(buf, 256, "%f", json_number_value(val));
  1179. if ( (p = strchr(buf, '.')) ) {
  1180. // Trim /\.0*$/ to work properly with integer-only arguments
  1181. q = p;
  1182. while (*(++q) == '0') {}
  1183. if (*q == '\0')
  1184. *p = '\0';
  1185. }
  1186. err = opt->cb_arg(buf, opt->u.arg);
  1187. } else if (json_is_array(val)) {
  1188. int n, size = json_array_size(val);
  1189. err = NULL;
  1190. for (n = 0; n < size && !err; n++) {
  1191. if (json_is_string(json_array_get(val, n)))
  1192. err = opt->cb_arg(json_string_value(json_array_get(val, n)), opt->u.arg);
  1193. else if (json_is_object(json_array_get(val, n)))
  1194. err = parse_config(json_array_get(val, n), false);
  1195. }
  1196. }
  1197. } else if (opt->type & OPT_NOARG) {
  1198. if (json_is_true(val))
  1199. err = opt->cb(opt->u.arg);
  1200. else if (json_is_boolean(val)) {
  1201. if (opt->cb == (void*)opt_set_bool)
  1202. err = opt_set_invbool(opt->u.arg);
  1203. else if (opt->cb == (void*)opt_set_invbool)
  1204. err = opt_set_bool(opt->u.arg);
  1205. }
  1206. }
  1207. if (err) {
  1208. /* Allow invalid values to be in configuration
  1209. * file, just skipping over them provided the
  1210. * JSON is still valid after that. */
  1211. if (fileconf) {
  1212. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1213. fileconf_load = -1;
  1214. } else {
  1215. sprintf(err_buf, "Parsing JSON option %s: %s",
  1216. p, err);
  1217. return err_buf;
  1218. }
  1219. }
  1220. }
  1221. free(name);
  1222. }
  1223. val = json_object_get(config, JSON_INCLUDE_CONF);
  1224. if (val && json_is_string(val))
  1225. return load_config(json_string_value(val), NULL);
  1226. return NULL;
  1227. }
  1228. char *cnfbuf = NULL;
  1229. static char *load_config(const char *arg, void __maybe_unused *unused)
  1230. {
  1231. json_error_t err;
  1232. json_t *config;
  1233. char *json_error;
  1234. if (!cnfbuf)
  1235. cnfbuf = strdup(arg);
  1236. if (++include_count > JSON_MAX_DEPTH)
  1237. return JSON_MAX_DEPTH_ERR;
  1238. #if JANSSON_MAJOR_VERSION > 1
  1239. config = json_load_file(arg, 0, &err);
  1240. #else
  1241. config = json_load_file(arg, &err);
  1242. #endif
  1243. if (!json_is_object(config)) {
  1244. json_error = malloc(JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text));
  1245. if (!json_error)
  1246. quit(1, "Malloc failure in json error");
  1247. sprintf(json_error, JSON_LOAD_ERROR, arg, err.text);
  1248. return json_error;
  1249. }
  1250. config_loaded = true;
  1251. /* Parse the config now, so we can override it. That can keep pointers
  1252. * so don't free config object. */
  1253. return parse_config(config, true);
  1254. }
  1255. static void load_default_config(void)
  1256. {
  1257. cnfbuf = malloc(PATH_MAX);
  1258. #if defined(unix)
  1259. if (getenv("HOME") && *getenv("HOME")) {
  1260. strcpy(cnfbuf, getenv("HOME"));
  1261. strcat(cnfbuf, "/");
  1262. } else
  1263. strcpy(cnfbuf, "");
  1264. char *dirp = cnfbuf + strlen(cnfbuf);
  1265. strcpy(dirp, ".bfgminer/");
  1266. strcat(dirp, def_conf);
  1267. if (access(cnfbuf, R_OK))
  1268. // No BFGMiner config, try Cgminer's...
  1269. strcpy(dirp, ".cgminer/cgminer.conf");
  1270. #else
  1271. strcpy(cnfbuf, "");
  1272. strcat(cnfbuf, def_conf);
  1273. #endif
  1274. if (!access(cnfbuf, R_OK))
  1275. load_config(cnfbuf, NULL);
  1276. else {
  1277. free(cnfbuf);
  1278. cnfbuf = NULL;
  1279. }
  1280. }
  1281. extern const char *opt_argv0;
  1282. static char *opt_verusage_and_exit(const char *extra)
  1283. {
  1284. printf("%s\nBuilt with "
  1285. #ifdef HAVE_OPENCL
  1286. "GPU "
  1287. #endif
  1288. #ifdef WANT_CPUMINE
  1289. "CPU "
  1290. #endif
  1291. #ifdef USE_BITFORCE
  1292. "bitforce "
  1293. #endif
  1294. #ifdef USE_ICARUS
  1295. "icarus "
  1296. #endif
  1297. #ifdef USE_MODMINER
  1298. "modminer "
  1299. #endif
  1300. #ifdef USE_ZTEX
  1301. "ztex "
  1302. #endif
  1303. #ifdef USE_SCRYPT
  1304. "scrypt "
  1305. #endif
  1306. "mining support.\n"
  1307. , packagename);
  1308. printf("%s", opt_usage(opt_argv0, extra));
  1309. fflush(stdout);
  1310. exit(0);
  1311. }
  1312. /* These options are available from commandline only */
  1313. static struct opt_table opt_cmdline_table[] = {
  1314. OPT_WITH_ARG("--config|-c",
  1315. load_config, NULL, NULL,
  1316. "Load a JSON-format configuration file\n"
  1317. "See example.conf for an example configuration."),
  1318. OPT_WITHOUT_ARG("--help|-h",
  1319. opt_verusage_and_exit, NULL,
  1320. "Print this message"),
  1321. #ifdef HAVE_OPENCL
  1322. OPT_WITHOUT_ARG("--ndevs|-n",
  1323. print_ndevs_and_exit, &nDevs,
  1324. "Display number of detected GPUs, OpenCL platform information, and exit"),
  1325. #endif
  1326. OPT_WITHOUT_ARG("--version|-V",
  1327. opt_version_and_exit, packagename,
  1328. "Display version and exit"),
  1329. OPT_ENDTABLE
  1330. };
  1331. static bool jobj_binary(const json_t *obj, const char *key,
  1332. void *buf, size_t buflen, bool required)
  1333. {
  1334. const char *hexstr;
  1335. json_t *tmp;
  1336. tmp = json_object_get(obj, key);
  1337. if (unlikely(!tmp)) {
  1338. if (unlikely(required))
  1339. applog(LOG_ERR, "JSON key '%s' not found", key);
  1340. return false;
  1341. }
  1342. hexstr = json_string_value(tmp);
  1343. if (unlikely(!hexstr)) {
  1344. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1345. return false;
  1346. }
  1347. if (!hex2bin(buf, hexstr, buflen))
  1348. return false;
  1349. return true;
  1350. }
  1351. static void calc_midstate(struct work *work)
  1352. {
  1353. union {
  1354. unsigned char c[64];
  1355. uint32_t i[16];
  1356. } data;
  1357. swap32yes(&data.i[0], work->data, 16);
  1358. sha2_context ctx;
  1359. sha2_starts( &ctx, 0 );
  1360. sha2_update( &ctx, data.c, 64 );
  1361. memcpy(work->midstate, ctx.state, sizeof(work->midstate));
  1362. swap32tole(work->midstate, work->midstate, 8);
  1363. }
  1364. static bool work_decode(const json_t *val, struct work *work)
  1365. {
  1366. if (unlikely(detect_algo == 1)) {
  1367. json_t *tmp = json_object_get(val, "algorithm");
  1368. const char *v = tmp ? json_string_value(tmp) : "";
  1369. if (strncasecmp(v, "scrypt", 6))
  1370. detect_algo = 2;
  1371. }
  1372. if (work->tmpl) {
  1373. const char *err = blktmpl_add_jansson(work->tmpl, val, time(NULL));
  1374. if (err) {
  1375. applog(LOG_ERR, "blktmpl error: %s", err);
  1376. goto err_out;
  1377. }
  1378. work->rolltime = blkmk_time_left(work->tmpl, time(NULL));
  1379. #if BLKMAKER_VERSION > 0
  1380. {
  1381. ssize_t ae = blkmk_append_coinbase_safe(work->tmpl, opt_coinbase_sig, 101);
  1382. static bool appenderr = false;
  1383. if (ae <= 0) {
  1384. if (opt_coinbase_sig) {
  1385. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Cannot append coinbase signature at all on pool %u (%d)", ae, work->pool->pool_no);
  1386. appenderr = true;
  1387. }
  1388. } else if (ae >= 3 || opt_coinbase_sig) {
  1389. const char *cbappend = opt_coinbase_sig;
  1390. if (!cbappend) {
  1391. const char full[] = PACKAGE " " VERSION;
  1392. // NOTE: Intentially including a trailing \0 on long forms so extranonce doesn't confuse things
  1393. if ((size_t)ae >= sizeof(full))
  1394. cbappend = full;
  1395. else if ((size_t)ae >= sizeof(PACKAGE))
  1396. cbappend = PACKAGE;
  1397. else
  1398. cbappend = "BFG";
  1399. }
  1400. size_t cbappendsz = strlen(cbappend);
  1401. static bool truncatewarning = false;
  1402. if (cbappendsz <= (size_t)ae) {
  1403. ae = cbappendsz;
  1404. truncatewarning = false;
  1405. } else {
  1406. char *tmp = malloc(ae + 1);
  1407. memcpy(tmp, opt_coinbase_sig, ae);
  1408. tmp[ae] = '\0';
  1409. applog((truncatewarning ? LOG_DEBUG : LOG_WARNING),
  1410. "Pool %u truncating appended coinbase signature at %d bytes: %s(%s)",
  1411. work->pool->pool_no, ae, tmp, &opt_coinbase_sig[ae]);
  1412. free(tmp);
  1413. truncatewarning = true;
  1414. }
  1415. ae = blkmk_append_coinbase_safe(work->tmpl, cbappend, ae);
  1416. if (ae <= 0) {
  1417. applog((appenderr ? LOG_DEBUG : LOG_WARNING), "Error appending coinbase signature (%d)", ae);
  1418. appenderr = true;
  1419. } else
  1420. appenderr = false;
  1421. }
  1422. }
  1423. #endif
  1424. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  1425. goto err_out;
  1426. swap32yes(work->data, work->data, 80 / 4);
  1427. memcpy(&work->data[80], "\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", 48);
  1428. const struct blktmpl_longpoll_req *lp;
  1429. struct pool *pool = work->pool;
  1430. if ((lp = blktmpl_get_longpoll(work->tmpl)) && ((!pool->lp_id) || strcmp(lp->id, pool->lp_id))) {
  1431. free(pool->lp_id);
  1432. pool->lp_id = strdup(lp->id);
  1433. #if 0 /* This just doesn't work :( */
  1434. curl_socket_t sock = pool->lp_socket;
  1435. if (sock != CURL_SOCKET_BAD) {
  1436. pool->lp_socket = CURL_SOCKET_BAD;
  1437. applog(LOG_WARNING, "Pool %u long poll request hanging, reconnecting", pool->pool_no);
  1438. shutdown(sock, SHUT_RDWR);
  1439. }
  1440. #endif
  1441. }
  1442. }
  1443. else
  1444. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data), true))) {
  1445. applog(LOG_ERR, "JSON inval data");
  1446. goto err_out;
  1447. }
  1448. if (!jobj_binary(val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  1449. // Calculate it ourselves
  1450. applog(LOG_DEBUG, "Calculating midstate locally");
  1451. calc_midstate(work);
  1452. }
  1453. if (!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1), false)) {
  1454. // Always the same anyway
  1455. memcpy(work->hash1, "\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\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\1\0\0", 64);
  1456. }
  1457. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target), true))) {
  1458. applog(LOG_ERR, "JSON inval target");
  1459. goto err_out;
  1460. }
  1461. if (work->tmpl) {
  1462. for (size_t i = 0; i < sizeof(work->target) / 2; ++i)
  1463. {
  1464. int p = (sizeof(work->target) - 1) - i;
  1465. unsigned char c = work->target[i];
  1466. work->target[i] = work->target[p];
  1467. work->target[p] = c;
  1468. }
  1469. }
  1470. memset(work->hash, 0, sizeof(work->hash));
  1471. gettimeofday(&work->tv_staged, NULL);
  1472. return true;
  1473. err_out:
  1474. return false;
  1475. }
  1476. int dev_from_id(int thr_id)
  1477. {
  1478. return thr_info[thr_id].cgpu->device_id;
  1479. }
  1480. /* Make the change in the recent value adjust dynamically when the difference
  1481. * is large, but damp it when the values are closer together. This allows the
  1482. * value to change quickly, but not fluctuate too dramatically when it has
  1483. * stabilised. */
  1484. void decay_time(double *f, double fadd)
  1485. {
  1486. double ratio = 0;
  1487. if (likely(*f > 0)) {
  1488. ratio = fadd / *f;
  1489. if (ratio > 1)
  1490. ratio = 1 / ratio;
  1491. }
  1492. if (ratio > 0.63)
  1493. *f = (fadd * 0.58 + *f) / 1.58;
  1494. else
  1495. *f = (fadd + *f * 0.58) / 1.58;
  1496. }
  1497. static int total_staged(void)
  1498. {
  1499. int ret;
  1500. mutex_lock(stgd_lock);
  1501. ret = HASH_COUNT(staged_work);
  1502. mutex_unlock(stgd_lock);
  1503. return ret;
  1504. }
  1505. #ifdef HAVE_CURSES
  1506. WINDOW *mainwin, *statuswin, *logwin;
  1507. #endif
  1508. double total_secs = 1.0;
  1509. static char statusline[256];
  1510. /* logstart is where the log window should start */
  1511. static int devcursor, logstart, logcursor;
  1512. #ifdef HAVE_CURSES
  1513. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  1514. static int statusy;
  1515. static int devsummaryYOffset;
  1516. #endif
  1517. #ifdef HAVE_OPENCL
  1518. struct cgpu_info gpus[MAX_GPUDEVICES]; /* Maximum number apparently possible */
  1519. #endif
  1520. struct cgpu_info *cpus;
  1521. #ifdef HAVE_CURSES
  1522. static inline void unlock_curses(void)
  1523. {
  1524. mutex_unlock(&console_lock);
  1525. }
  1526. static inline void lock_curses(void)
  1527. {
  1528. mutex_lock(&console_lock);
  1529. }
  1530. static bool curses_active_locked(void)
  1531. {
  1532. bool ret;
  1533. lock_curses();
  1534. ret = curses_active;
  1535. if (!ret)
  1536. unlock_curses();
  1537. return ret;
  1538. }
  1539. // Cancellable getch
  1540. int my_cancellable_getch(void)
  1541. {
  1542. // This only works because the macro only hits direct getch() calls
  1543. typedef int (*real_getch_t)(void);
  1544. const real_getch_t real_getch = __real_getch;
  1545. int type, rv;
  1546. bool sct;
  1547. sct = !pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type);
  1548. rv = real_getch();
  1549. if (sct)
  1550. pthread_setcanceltype(type, &type);
  1551. return rv;
  1552. }
  1553. #endif
  1554. void tailsprintf(char *f, const char *fmt, ...)
  1555. {
  1556. va_list ap;
  1557. va_start(ap, fmt);
  1558. vsprintf(f + strlen(f), fmt, ap);
  1559. va_end(ap);
  1560. }
  1561. /* Convert a uint64_t value into a truncated string for displaying with its
  1562. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  1563. static void suffix_string(uint64_t val, char *buf, int sigdigits)
  1564. {
  1565. const double dkilo = 1000.0;
  1566. const uint64_t kilo = 1000ull;
  1567. const uint64_t mega = 1000000ull;
  1568. const uint64_t giga = 1000000000ull;
  1569. const uint64_t tera = 1000000000000ull;
  1570. const uint64_t peta = 1000000000000000ull;
  1571. const uint64_t exa = 1000000000000000000ull;
  1572. char suffix[2] = "";
  1573. bool decimal = true;
  1574. double dval;
  1575. if (val >= exa) {
  1576. val /= peta;
  1577. dval = (double)val / dkilo;
  1578. sprintf(suffix, "E");
  1579. } else if (val >= peta) {
  1580. val /= tera;
  1581. dval = (double)val / dkilo;
  1582. sprintf(suffix, "P");
  1583. } else if (val >= tera) {
  1584. val /= giga;
  1585. dval = (double)val / dkilo;
  1586. sprintf(suffix, "T");
  1587. } else if (val >= giga) {
  1588. val /= mega;
  1589. dval = (double)val / dkilo;
  1590. sprintf(suffix, "G");
  1591. } else if (val >= mega) {
  1592. val /= kilo;
  1593. dval = (double)val / dkilo;
  1594. sprintf(suffix, "M");
  1595. } else if (val >= kilo) {
  1596. dval = (double)val / dkilo;
  1597. sprintf(suffix, "K");
  1598. } else {
  1599. dval = val;
  1600. decimal = false;
  1601. }
  1602. if (!sigdigits) {
  1603. if (decimal)
  1604. sprintf(buf, "%.3g%s", dval, suffix);
  1605. else
  1606. sprintf(buf, "%d%s", (unsigned int)dval, suffix);
  1607. } else {
  1608. /* Always show sigdigits + 1, padded on right with zeroes
  1609. * followed by suffix */
  1610. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  1611. sprintf(buf, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  1612. }
  1613. }
  1614. static float
  1615. utility_to_hashrate(double utility)
  1616. {
  1617. return utility * 0x4444444;
  1618. }
  1619. static const char*_unitchar = "kMGTPEZY?";
  1620. static void
  1621. hashrate_pick_unit(float hashrate, unsigned char*unit)
  1622. {
  1623. unsigned char i;
  1624. for (i = 0; i <= *unit; ++i)
  1625. hashrate /= 1e3;
  1626. while (hashrate >= 1000)
  1627. {
  1628. hashrate /= 1e3;
  1629. if (likely(_unitchar[*unit] != '?'))
  1630. ++*unit;
  1631. }
  1632. }
  1633. enum h2bs_fmt {
  1634. H2B_NOUNIT, // "xxx.x"
  1635. H2B_SHORT, // "xxx.xMH/s"
  1636. H2B_SPACED, // "xxx.x MH/s"
  1637. };
  1638. static const size_t h2bs_fmt_size[] = {6, 10, 11};
  1639. static char*
  1640. hashrate_to_bufstr(char*buf, float hashrate, signed char unitin, enum h2bs_fmt fmt)
  1641. {
  1642. unsigned char prec, i, ucp, unit;
  1643. if (unitin == -1)
  1644. {
  1645. unit = 0;
  1646. hashrate_pick_unit(hashrate, &unit);
  1647. }
  1648. else
  1649. unit = unitin;
  1650. i = 5;
  1651. switch (fmt) {
  1652. case H2B_SPACED:
  1653. buf[i++] = ' ';
  1654. case H2B_SHORT:
  1655. buf[i++] = _unitchar[unit];
  1656. strcpy(&buf[i], "h/s");
  1657. default:
  1658. break;
  1659. }
  1660. for (i = 0; i <= unit; ++i)
  1661. hashrate /= 1000;
  1662. if (hashrate >= 100 || unit < 2)
  1663. prec = 1;
  1664. else
  1665. if (hashrate >= 10)
  1666. prec = 2;
  1667. else
  1668. prec = 3;
  1669. ucp = (fmt == H2B_NOUNIT ? '\0' : buf[5]);
  1670. sprintf(buf, "%5.*f", prec, hashrate);
  1671. buf[5] = ucp;
  1672. return buf;
  1673. }
  1674. static void
  1675. ti_hashrate_bufstr(char**out, float current, float average, float sharebased, enum h2bs_fmt longfmt)
  1676. {
  1677. unsigned char unit = 0;
  1678. hashrate_pick_unit(current, &unit);
  1679. hashrate_pick_unit(average, &unit);
  1680. hashrate_pick_unit(sharebased, &unit);
  1681. hashrate_to_bufstr(out[0], current, unit, H2B_NOUNIT);
  1682. hashrate_to_bufstr(out[1], average, unit, H2B_NOUNIT);
  1683. hashrate_to_bufstr(out[2], sharebased, unit, longfmt);
  1684. }
  1685. static void get_statline(char *buf, struct cgpu_info *cgpu)
  1686. {
  1687. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  1688. ti_hashrate_bufstr(
  1689. (char*[]){cHr, aHr, uHr},
  1690. 1e6*cgpu->rolling,
  1691. 1e6*cgpu->total_mhashes / total_secs,
  1692. utility_to_hashrate(cgpu->utility_diff1),
  1693. H2B_SPACED);
  1694. sprintf(buf, "%s%d ", cgpu->api->name, cgpu->device_id);
  1695. if (cgpu->api->get_statline_before)
  1696. cgpu->api->get_statline_before(buf, cgpu);
  1697. else
  1698. tailsprintf(buf, " | ");
  1699. tailsprintf(buf, "%ds:%s avg:%s u:%s | A:%d R:%d HW:%d U:%.1f/m",
  1700. opt_log_interval,
  1701. cHr, aHr,
  1702. uHr,
  1703. cgpu->accepted,
  1704. cgpu->rejected,
  1705. cgpu->hw_errors,
  1706. cgpu->utility);
  1707. if (cgpu->api->get_statline)
  1708. cgpu->api->get_statline(buf, cgpu);
  1709. }
  1710. static void text_print_status(int thr_id)
  1711. {
  1712. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1713. char logline[255];
  1714. if (cgpu) {
  1715. get_statline(logline, cgpu);
  1716. printf("%s\n", logline);
  1717. }
  1718. }
  1719. static int global_queued(void);
  1720. #ifdef HAVE_CURSES
  1721. /* Must be called with curses mutex lock held and curses_active */
  1722. static void curses_print_status(void)
  1723. {
  1724. struct pool *pool = current_pool();
  1725. struct timeval now, tv;
  1726. wattron(statuswin, A_BOLD);
  1727. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1728. if (!gettimeofday(&now, NULL))
  1729. {
  1730. unsigned int days, hours;
  1731. div_t d;
  1732. timersub(&now, &miner_started, &tv);
  1733. d = div(tv.tv_sec, 86400);
  1734. days = d.quot;
  1735. d = div(d.rem, 3600);
  1736. hours = d.quot;
  1737. d = div(d.rem, 60);
  1738. wprintw(statuswin, " - [%3u day%c %02d:%02d:%02d]"
  1739. , days
  1740. , (days == 1) ? ' ' : 's'
  1741. , hours
  1742. , d.quot
  1743. , d.rem
  1744. );
  1745. }
  1746. wattroff(statuswin, A_BOLD);
  1747. mvwhline(statuswin, 1, 0, '-', 80);
  1748. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1749. wclrtoeol(statuswin);
  1750. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d GW: %d LW: %d GF: %d RF: %d",
  1751. global_queued(), total_staged(), total_stale, total_discarded, new_blocks,
  1752. total_getworks,
  1753. local_work, total_go, total_ro);
  1754. wclrtoeol(statuswin);
  1755. if (pool->has_stratum) {
  1756. mvwprintw(statuswin, 4, 0, " Connected to %s with stratum as user %s",
  1757. pool->stratum_url, pool->rpc_user);
  1758. } else if ((pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE) && total_pools > 1) {
  1759. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1760. have_longpoll ? "": "out");
  1761. } else {
  1762. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1763. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1764. }
  1765. wclrtoeol(statuswin);
  1766. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1767. mvwhline(statuswin, 6, 0, '-', 80);
  1768. mvwhline(statuswin, statusy - 1, 0, '-', 80);
  1769. mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1770. have_opencl ? "[G]PU management " : "");
  1771. }
  1772. static void adj_width(int var, int *length)
  1773. {
  1774. if ((int)(log10(var) + 1) > *length)
  1775. (*length)++;
  1776. }
  1777. static int dev_width;
  1778. static void curses_print_devstatus(int thr_id)
  1779. {
  1780. static int awidth = 1, rwidth = 1, hwwidth = 1, uwidth = 1;
  1781. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1782. char logline[255];
  1783. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SHORT]];
  1784. int ypos;
  1785. /* Check this isn't out of the window size */
  1786. ypos = cgpu->cgminer_id;
  1787. ypos += devsummaryYOffset;
  1788. if (ypos < 0)
  1789. return;
  1790. ypos += devcursor;
  1791. if (ypos >= statusy - 1)
  1792. return;
  1793. cgpu->utility = cgpu->accepted / total_secs * 60;
  1794. cgpu->utility_diff1 = cgpu->accepted_weighed / total_secs * 60;
  1795. if (wmove(statuswin, ypos, 0) == ERR)
  1796. return;
  1797. wprintw(statuswin, " %s %*d: ", cgpu->api->name, dev_width, cgpu->device_id);
  1798. if (cgpu->api->get_statline_before) {
  1799. logline[0] = '\0';
  1800. cgpu->api->get_statline_before(logline, cgpu);
  1801. wprintw(statuswin, "%s", logline);
  1802. }
  1803. else
  1804. wprintw(statuswin, " | ");
  1805. ti_hashrate_bufstr(
  1806. (char*[]){cHr, aHr, uHr},
  1807. 1e6*cgpu->rolling,
  1808. 1e6*cgpu->total_mhashes / total_secs,
  1809. utility_to_hashrate(cgpu->utility_diff1),
  1810. H2B_SHORT);
  1811. if (cgpu->status == LIFE_DEAD)
  1812. wprintw(statuswin, "DEAD ");
  1813. else if (cgpu->status == LIFE_SICK)
  1814. wprintw(statuswin, "SICK ");
  1815. else if (cgpu->deven == DEV_DISABLED)
  1816. wprintw(statuswin, "OFF ");
  1817. else if (cgpu->deven == DEV_RECOVER)
  1818. wprintw(statuswin, "REST ");
  1819. else if (cgpu->deven == DEV_RECOVER_ERR)
  1820. wprintw(statuswin, " ERR ");
  1821. else if (cgpu->status == LIFE_WAIT)
  1822. wprintw(statuswin, "WAIT ");
  1823. else
  1824. wprintw(statuswin, "%s", cHr);
  1825. adj_width(cgpu->accepted, &awidth);
  1826. adj_width(cgpu->rejected, &rwidth);
  1827. adj_width(cgpu->hw_errors, &hwwidth);
  1828. adj_width(cgpu->utility, &uwidth);
  1829. wprintw(statuswin, "/%s/%s | A:%*d R:%*d HW:%*d U:%*.2f/m",
  1830. aHr,
  1831. uHr,
  1832. awidth, cgpu->accepted,
  1833. rwidth, cgpu->rejected,
  1834. hwwidth, cgpu->hw_errors,
  1835. uwidth + 3, cgpu->utility);
  1836. if (cgpu->api->get_statline) {
  1837. logline[0] = '\0';
  1838. cgpu->api->get_statline(logline, cgpu);
  1839. wprintw(statuswin, "%s", logline);
  1840. }
  1841. wclrtoeol(statuswin);
  1842. }
  1843. #endif
  1844. static void print_status(int thr_id)
  1845. {
  1846. if (!curses_active)
  1847. text_print_status(thr_id);
  1848. }
  1849. #ifdef HAVE_CURSES
  1850. /* Check for window resize. Called with curses mutex locked */
  1851. static inline bool change_logwinsize(void)
  1852. {
  1853. int x, y, logx, logy;
  1854. bool ret = false;
  1855. getmaxyx(mainwin, y, x);
  1856. if (x < 80 || y < 25)
  1857. return ret;
  1858. if (y > statusy + 2 && statusy < logstart) {
  1859. if (y - 2 < logstart)
  1860. statusy = y - 2;
  1861. else
  1862. statusy = logstart;
  1863. logcursor = statusy + 1;
  1864. mvwin(logwin, logcursor, 0);
  1865. wresize(statuswin, statusy, x);
  1866. ret = true;
  1867. }
  1868. y -= logcursor;
  1869. getmaxyx(logwin, logy, logx);
  1870. /* Detect screen size change */
  1871. if (x != logx || y != logy) {
  1872. wresize(logwin, y, x);
  1873. ret = true;
  1874. }
  1875. return ret;
  1876. }
  1877. static void check_winsizes(void)
  1878. {
  1879. if (!use_curses)
  1880. return;
  1881. if (curses_active_locked()) {
  1882. int y, x;
  1883. x = getmaxx(statuswin);
  1884. if (logstart > LINES - 2)
  1885. statusy = LINES - 2;
  1886. else
  1887. statusy = logstart;
  1888. logcursor = statusy + 1;
  1889. wresize(statuswin, statusy, x);
  1890. getmaxyx(mainwin, y, x);
  1891. y -= logcursor;
  1892. wresize(logwin, y, x);
  1893. mvwin(logwin, logcursor, 0);
  1894. unlock_curses();
  1895. }
  1896. }
  1897. /* For mandatory printing when mutex is already locked */
  1898. void wlog(const char *f, ...)
  1899. {
  1900. va_list ap;
  1901. va_start(ap, f);
  1902. vw_printw(logwin, f, ap);
  1903. va_end(ap);
  1904. }
  1905. /* Mandatory printing */
  1906. void wlogprint(const char *f, ...)
  1907. {
  1908. va_list ap;
  1909. if (curses_active_locked()) {
  1910. va_start(ap, f);
  1911. vw_printw(logwin, f, ap);
  1912. va_end(ap);
  1913. unlock_curses();
  1914. }
  1915. }
  1916. #endif
  1917. #ifdef HAVE_CURSES
  1918. bool log_curses_only(int prio, const char *f, va_list ap)
  1919. {
  1920. bool high_prio;
  1921. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  1922. if (curses_active_locked()) {
  1923. if (!opt_loginput || high_prio) {
  1924. vw_printw(logwin, f, ap);
  1925. if (high_prio) {
  1926. touchwin(logwin);
  1927. wrefresh(logwin);
  1928. }
  1929. }
  1930. unlock_curses();
  1931. return true;
  1932. }
  1933. return false;
  1934. }
  1935. void clear_logwin(void)
  1936. {
  1937. if (curses_active_locked()) {
  1938. wclear(logwin);
  1939. unlock_curses();
  1940. }
  1941. }
  1942. #endif
  1943. /* regenerate the full work->hash value and also return true if it's a block */
  1944. bool regeneratehash(const struct work *work)
  1945. {
  1946. uint32_t *data32 = (uint32_t *)(work->data);
  1947. unsigned char swap[128];
  1948. uint32_t *swap32 = (uint32_t *)swap;
  1949. unsigned char hash1[32];
  1950. uint32_t *hash32 = (uint32_t *)(work->hash);
  1951. uint32_t difficulty = 0;
  1952. uint32_t diffbytes = 0;
  1953. uint32_t diffvalue = 0;
  1954. uint32_t diffcmp[8];
  1955. int diffshift = 0;
  1956. int i;
  1957. swap32yes(swap32, data32, 80 / 4);
  1958. sha2(swap, 80, hash1, false);
  1959. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1960. difficulty = be32toh(*((uint32_t *)(work->data + 72)));
  1961. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1962. diffvalue = difficulty & 0x00ffffff;
  1963. diffshift = (diffbytes % 4) * 8;
  1964. if (diffshift == 0) {
  1965. diffshift = 32;
  1966. diffbytes--;
  1967. }
  1968. memset(diffcmp, 0, 32);
  1969. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1970. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1971. for (i = 7; i >= 0; i--) {
  1972. uint32_t hash32i = be32toh(hash32[i]);
  1973. if (hash32i > diffcmp[i])
  1974. return false;
  1975. if (hash32i < diffcmp[i])
  1976. return true;
  1977. }
  1978. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1979. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1980. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1981. return true;
  1982. }
  1983. static void enable_pool(struct pool *pool)
  1984. {
  1985. if (pool->enabled != POOL_ENABLED) {
  1986. enabled_pools++;
  1987. pool->enabled = POOL_ENABLED;
  1988. }
  1989. }
  1990. static void disable_pool(struct pool *pool)
  1991. {
  1992. if (pool->enabled == POOL_ENABLED)
  1993. enabled_pools--;
  1994. pool->enabled = POOL_DISABLED;
  1995. }
  1996. static void reject_pool(struct pool *pool)
  1997. {
  1998. if (pool->enabled == POOL_ENABLED)
  1999. enabled_pools--;
  2000. pool->enabled = POOL_REJECTING;
  2001. }
  2002. /* Theoretically threads could race when modifying accepted and
  2003. * rejected values but the chance of two submits completing at the
  2004. * same time is zero so there is no point adding extra locking */
  2005. static void
  2006. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2007. char *hashshow, bool resubmit, char *worktime)
  2008. {
  2009. struct pool *pool = work->pool;
  2010. struct cgpu_info *cgpu = thr_info[work->thr_id].cgpu;
  2011. if (json_is_null(res) || json_is_true(res)) {
  2012. cgpu->accepted++;
  2013. cgpu->accepted_weighed += work->work_difficulty;
  2014. total_accepted++;
  2015. total_accepted_weighed += work->work_difficulty;
  2016. pool->accepted++;
  2017. cgpu->diff_accepted += work->work_difficulty;
  2018. total_diff_accepted += work->work_difficulty;
  2019. pool->diff_accepted += work->work_difficulty;
  2020. pool->seq_rejects = 0;
  2021. cgpu->last_share_pool = pool->pool_no;
  2022. cgpu->last_share_pool_time = time(NULL);
  2023. cgpu->last_share_diff = work->work_difficulty;
  2024. pool->last_share_time = cgpu->last_share_pool_time;
  2025. pool->last_share_diff = work->work_difficulty;
  2026. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2027. if (!QUIET) {
  2028. if (total_pools > 1)
  2029. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2030. hashshow, cgpu->api->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2031. else
  2032. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2033. hashshow, cgpu->api->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2034. }
  2035. sharelog("accept", work);
  2036. if (opt_shares && total_accepted >= opt_shares) {
  2037. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2038. kill_work();
  2039. return;
  2040. }
  2041. /* Detect if a pool that has been temporarily disabled for
  2042. * continually rejecting shares has started accepting shares.
  2043. * This will only happen with the work returned from a
  2044. * longpoll */
  2045. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2046. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2047. enable_pool(pool);
  2048. switch_pools(NULL);
  2049. }
  2050. } else {
  2051. cgpu->rejected++;
  2052. total_rejected++;
  2053. pool->rejected++;
  2054. cgpu->diff_rejected += work->work_difficulty;
  2055. total_diff_rejected += work->work_difficulty;
  2056. pool->diff_rejected += work->work_difficulty;
  2057. pool->seq_rejects++;
  2058. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2059. if (!QUIET) {
  2060. char where[17];
  2061. char disposition[36] = "reject";
  2062. char reason[32];
  2063. strcpy(reason, "");
  2064. if (total_pools > 1)
  2065. sprintf(where, "pool %d", work->pool->pool_no);
  2066. else
  2067. strcpy(where, "");
  2068. if (!json_is_string(res))
  2069. res = json_object_get(val, "reject-reason");
  2070. if (res) {
  2071. const char *reasontmp = json_string_value(res);
  2072. size_t reasonLen = strlen(reasontmp);
  2073. if (reasonLen > 28)
  2074. reasonLen = 28;
  2075. reason[0] = ' '; reason[1] = '(';
  2076. memcpy(2 + reason, reasontmp, reasonLen);
  2077. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2078. memcpy(disposition + 7, reasontmp, reasonLen);
  2079. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2080. } else if (work->stratum && err && json_is_array(err)) {
  2081. json_t *reason_val = json_array_get(err, 1);
  2082. char *reason_str;
  2083. if (reason_val && json_is_string(reason_val)) {
  2084. reason_str = (char *)json_string_value(reason_val);
  2085. snprintf(reason, 31, " (%s)", reason_str);
  2086. }
  2087. }
  2088. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2089. hashshow, cgpu->api->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2090. sharelog(disposition, work);
  2091. }
  2092. /* Once we have more than a nominal amount of sequential rejects,
  2093. * at least 10 and more than 3 mins at the current utility,
  2094. * disable the pool because some pool error is likely to have
  2095. * ensued. Do not do this if we know the share just happened to
  2096. * be stale due to networking delays.
  2097. */
  2098. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2099. double utility = total_accepted / total_secs * 60;
  2100. if (pool->seq_rejects > utility * 3) {
  2101. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2102. pool->pool_no, pool->seq_rejects);
  2103. reject_pool(pool);
  2104. if (pool == current_pool())
  2105. switch_pools(NULL);
  2106. pool->seq_rejects = 0;
  2107. }
  2108. }
  2109. }
  2110. }
  2111. static const uint64_t diffone = 0xFFFF000000000000ull;
  2112. static uint64_t share_diff(const struct work *work)
  2113. {
  2114. uint64_t *data64, d64;
  2115. char rhash[36];
  2116. uint64_t ret;
  2117. swab256(rhash, work->hash);
  2118. data64 = (uint64_t *)(rhash + 4);
  2119. d64 = be64toh(*data64);
  2120. if (unlikely(!d64))
  2121. d64 = 1;
  2122. ret = diffone / d64;
  2123. return ret;
  2124. }
  2125. static uint32_t scrypt_diff(const struct work *work)
  2126. {
  2127. const uint32_t scrypt_diffone = 0x0000fffful;
  2128. uint32_t d32 = work->outputhash;
  2129. if (unlikely(!d32))
  2130. d32 = 1;
  2131. return scrypt_diffone / d32;
  2132. }
  2133. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2134. {
  2135. char *hexstr = NULL;
  2136. json_t *val, *res, *err;
  2137. char *s, *sd;
  2138. bool rc = false;
  2139. int thr_id = work->thr_id;
  2140. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2141. struct pool *pool = work->pool;
  2142. int rolltime;
  2143. uint32_t *hash32;
  2144. struct timeval tv_submit, tv_submit_reply;
  2145. char hashshow[64 + 1] = "";
  2146. char worktime[200] = "";
  2147. if (work->tmpl) {
  2148. unsigned char data[80];
  2149. swap32yes(data, work->data, 80 / 4);
  2150. json_t *req = blkmk_submit_jansson(work->tmpl, data, work->dataid, *((uint32_t*)&work->data[76]));
  2151. s = json_dumps(req, 0);
  2152. sd = bin2hex(data, 80);
  2153. } else {
  2154. s = malloc(345);
  2155. sd = malloc(345);
  2156. /* build hex string */
  2157. hexstr = bin2hex(work->data, sizeof(work->data));
  2158. /* build JSON-RPC request */
  2159. sprintf(s,
  2160. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  2161. hexstr);
  2162. sprintf(sd,
  2163. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  2164. hexstr);
  2165. }
  2166. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  2167. gettimeofday(&tv_submit, NULL);
  2168. /* issue JSON-RPC request */
  2169. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2170. free(s);
  2171. free(sd);
  2172. gettimeofday(&tv_submit_reply, NULL);
  2173. if (unlikely(!val)) {
  2174. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2175. if (!pool_tset(pool, &pool->submit_fail)) {
  2176. total_ro++;
  2177. pool->remotefail_occasions++;
  2178. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2179. }
  2180. goto out;
  2181. } else if (pool_tclear(pool, &pool->submit_fail))
  2182. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2183. res = json_object_get(val, "result");
  2184. err = json_object_get(val, "error");
  2185. if (!QUIET) {
  2186. int intdiff = floor(work->work_difficulty);
  2187. char diffdisp[16];
  2188. hash32 = (uint32_t *)(work->hash);
  2189. if (opt_scrypt) {
  2190. uint32_t sharediff;
  2191. scrypt_outputhash(work);
  2192. sharediff = scrypt_diff(work);
  2193. suffix_string(sharediff, diffdisp, 0);
  2194. sprintf(hashshow, "%08lx Diff %s/%d", (unsigned long)work->outputhash, diffdisp, intdiff);
  2195. } else {
  2196. uint64_t sharediff = share_diff(work);
  2197. suffix_string(sharediff, diffdisp, 0);
  2198. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)(hash32[6]), diffdisp, intdiff,
  2199. work->block? " BLOCK!" : "");
  2200. }
  2201. if (opt_worktime) {
  2202. char workclone[20];
  2203. struct tm *tm, tm_getwork, tm_submit_reply;
  2204. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2205. (struct timeval *)&(work->tv_getwork));
  2206. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2207. (struct timeval *)&(work->tv_getwork_reply));
  2208. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2209. (struct timeval *)&(work->tv_work_start));
  2210. double work_to_submit = tdiff(&tv_submit,
  2211. (struct timeval *)&(work->tv_work_found));
  2212. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2213. int diffplaces = 3;
  2214. tm = localtime(&(work->tv_getwork.tv_sec));
  2215. memcpy(&tm_getwork, tm, sizeof(struct tm));
  2216. tm = localtime(&(tv_submit_reply.tv_sec));
  2217. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  2218. if (work->clone) {
  2219. sprintf(workclone, "C:%1.3f",
  2220. tdiff((struct timeval *)&(work->tv_cloned),
  2221. (struct timeval *)&(work->tv_getwork_reply)));
  2222. }
  2223. else
  2224. strcpy(workclone, "O");
  2225. if (work->work_difficulty < 1)
  2226. diffplaces = 6;
  2227. 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",
  2228. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  2229. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  2230. work->getwork_mode, diffplaces, work->work_difficulty,
  2231. tm_getwork.tm_hour, tm_getwork.tm_min,
  2232. tm_getwork.tm_sec, getwork_time, workclone,
  2233. getwork_to_work, work_time, work_to_submit, submit_time,
  2234. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  2235. tm_submit_reply.tm_sec);
  2236. }
  2237. }
  2238. share_result(val, res, err, work, hashshow, resubmit, worktime);
  2239. cgpu->utility = cgpu->accepted / total_secs * 60;
  2240. cgpu->utility_diff1 = cgpu->accepted_weighed / total_secs * 60;
  2241. if (!opt_realquiet)
  2242. print_status(thr_id);
  2243. if (!want_per_device_stats) {
  2244. char logline[255];
  2245. get_statline(logline, cgpu);
  2246. applog(LOG_INFO, "%s", logline);
  2247. }
  2248. json_decref(val);
  2249. rc = true;
  2250. out:
  2251. free(hexstr);
  2252. return rc;
  2253. }
  2254. static const char *getwork_rpc_req =
  2255. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  2256. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  2257. * rolling average per 10 minutes and if pools start getting more, it biases
  2258. * away from them to distribute work evenly. The share count is reset to the
  2259. * rolling average every 10 minutes to not send all work to one pool after it
  2260. * has been disabled/out for an extended period. */
  2261. static struct pool *select_balanced(struct pool *cp)
  2262. {
  2263. int i, lowest = cp->shares;
  2264. struct pool *ret = cp;
  2265. for (i = 0; i < total_pools; i++) {
  2266. struct pool *pool = pools[i];
  2267. if (pool->idle || pool->enabled != POOL_ENABLED)
  2268. continue;
  2269. if (pool->shares < lowest) {
  2270. lowest = pool->shares;
  2271. ret = pool;
  2272. }
  2273. }
  2274. ret->shares++;
  2275. return ret;
  2276. }
  2277. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2278. static inline struct pool *select_pool(bool lagging)
  2279. {
  2280. static int rotating_pool = 0;
  2281. struct pool *pool, *cp;
  2282. cp = current_pool();
  2283. if (pool_strategy == POOL_BALANCE)
  2284. return select_balanced(cp);
  2285. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  2286. pool = cp;
  2287. else
  2288. pool = NULL;
  2289. while (!pool) {
  2290. if (++rotating_pool >= total_pools)
  2291. rotating_pool = 0;
  2292. pool = pools[rotating_pool];
  2293. if ((!pool->idle && pool->enabled == POOL_ENABLED) || pool == cp)
  2294. break;
  2295. pool = NULL;
  2296. }
  2297. return pool;
  2298. }
  2299. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249216.0;
  2300. /*
  2301. * Calculate the work share difficulty
  2302. */
  2303. static void calc_diff(struct work *work, int known)
  2304. {
  2305. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  2306. if (opt_scrypt) {
  2307. uint64_t *data64, d64;
  2308. char rtarget[36];
  2309. swab256(rtarget, work->target);
  2310. data64 = (uint64_t *)(rtarget + 2);
  2311. d64 = be64toh(*data64);
  2312. if (unlikely(!d64))
  2313. d64 = 1;
  2314. work->work_difficulty = diffone / d64;
  2315. } else if (!known) {
  2316. double targ = 0;
  2317. int i;
  2318. for (i = 31; i >= 0; i--) {
  2319. targ *= 256;
  2320. targ += work->target[i];
  2321. }
  2322. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  2323. } else
  2324. work->work_difficulty = known;
  2325. pool_stats->last_diff = work->work_difficulty;
  2326. if (work->work_difficulty == pool_stats->min_diff)
  2327. pool_stats->min_diff_count++;
  2328. else if (work->work_difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  2329. pool_stats->min_diff = work->work_difficulty;
  2330. pool_stats->min_diff_count = 1;
  2331. }
  2332. if (work->work_difficulty == pool_stats->max_diff)
  2333. pool_stats->max_diff_count++;
  2334. else if (work->work_difficulty > pool_stats->max_diff) {
  2335. pool_stats->max_diff = work->work_difficulty;
  2336. pool_stats->max_diff_count = 1;
  2337. }
  2338. }
  2339. static void get_benchmark_work(struct work *work)
  2340. {
  2341. // Use a random work block pulled from a pool
  2342. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  2343. size_t bench_size = sizeof(work);
  2344. size_t work_size = sizeof(bench_block);
  2345. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  2346. memset(work, 0, sizeof(work));
  2347. memcpy(work, &bench_block, min_size);
  2348. work->mandatory = true;
  2349. work->pool = pools[0];
  2350. gettimeofday(&(work->tv_getwork), NULL);
  2351. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  2352. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  2353. calc_diff(work, 0);
  2354. }
  2355. static char *prepare_rpc_req(struct work *work, enum pool_protocol proto, const char *lpid)
  2356. {
  2357. char *rpc_req;
  2358. switch (proto) {
  2359. case PLP_GETWORK:
  2360. work->tmpl = NULL;
  2361. return strdup(getwork_rpc_req);
  2362. case PLP_GETBLOCKTEMPLATE:
  2363. work->tmpl_refcount = malloc(sizeof(*work->tmpl_refcount));
  2364. if (!work->tmpl_refcount)
  2365. return NULL;
  2366. work->tmpl = blktmpl_create();
  2367. if (!work->tmpl)
  2368. goto gbtfail2;
  2369. *work->tmpl_refcount = 1;
  2370. gbt_capabilities_t caps = blktmpl_addcaps(work->tmpl);
  2371. if (!caps)
  2372. goto gbtfail;
  2373. caps |= GBT_LONGPOLL;
  2374. json_t *req = blktmpl_request_jansson(caps, lpid);
  2375. if (!req)
  2376. goto gbtfail;
  2377. rpc_req = json_dumps(req, 0);
  2378. if (!rpc_req)
  2379. goto gbtfail;
  2380. json_decref(req);
  2381. return rpc_req;
  2382. default:
  2383. return NULL;
  2384. }
  2385. return NULL;
  2386. gbtfail:
  2387. blktmpl_free(work->tmpl);
  2388. work->tmpl = NULL;
  2389. gbtfail2:
  2390. free(work->tmpl_refcount);
  2391. work->tmpl_refcount = NULL;
  2392. return NULL;
  2393. }
  2394. static const char *pool_protocol_name(enum pool_protocol proto)
  2395. {
  2396. switch (proto) {
  2397. case PLP_GETBLOCKTEMPLATE:
  2398. return "getblocktemplate";
  2399. case PLP_GETWORK:
  2400. return "getwork";
  2401. default:
  2402. return "UNKNOWN";
  2403. }
  2404. }
  2405. static enum pool_protocol pool_protocol_fallback(enum pool_protocol proto)
  2406. {
  2407. switch (proto) {
  2408. case PLP_GETBLOCKTEMPLATE:
  2409. return PLP_GETWORK;
  2410. default:
  2411. return PLP_NONE;
  2412. }
  2413. }
  2414. static bool get_upstream_work(struct work *work, CURL *curl)
  2415. {
  2416. struct pool *pool = work->pool;
  2417. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  2418. struct timeval tv_elapsed;
  2419. json_t *val = NULL;
  2420. bool rc = false;
  2421. char *url;
  2422. enum pool_protocol proto;
  2423. char *rpc_req;
  2424. tryagain:
  2425. rpc_req = prepare_rpc_req(work, pool->proto, NULL);
  2426. if (!rpc_req)
  2427. return false;
  2428. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  2429. url = pool->rpc_url;
  2430. gettimeofday(&(work->tv_getwork), NULL);
  2431. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  2432. false, &work->rolltime, pool, false);
  2433. pool_stats->getwork_attempts++;
  2434. free(rpc_req);
  2435. if (likely(val)) {
  2436. rc = work_decode(json_object_get(val, "result"), work);
  2437. if (unlikely(!rc))
  2438. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  2439. } else if (PLP_NONE != (proto = pool_protocol_fallback(pool->proto))) {
  2440. applog(LOG_WARNING, "Pool %u failed getblocktemplate request; falling back to getwork protocol", pool->pool_no);
  2441. pool->proto = proto;
  2442. goto tryagain;
  2443. } else
  2444. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2445. gettimeofday(&(work->tv_getwork_reply), NULL);
  2446. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  2447. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  2448. pool_stats->getwork_wait_rolling /= 1.63;
  2449. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  2450. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  2451. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  2452. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  2453. }
  2454. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  2455. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  2456. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  2457. }
  2458. pool_stats->getwork_calls++;
  2459. work->pool = pool;
  2460. work->longpoll = false;
  2461. work->getwork_mode = GETWORK_MODE_POOL;
  2462. calc_diff(work, 0);
  2463. total_getworks++;
  2464. pool->getwork_requested++;
  2465. if (likely(val))
  2466. json_decref(val);
  2467. return rc;
  2468. }
  2469. static struct work *make_work(void)
  2470. {
  2471. struct work *work = calloc(1, sizeof(struct work));
  2472. if (unlikely(!work))
  2473. quit(1, "Failed to calloc work in make_work");
  2474. mutex_lock(&control_lock);
  2475. work->id = total_work++;
  2476. mutex_unlock(&control_lock);
  2477. return work;
  2478. }
  2479. static void free_work(struct work *work)
  2480. {
  2481. if (work->tmpl) {
  2482. struct pool *pool = work->pool;
  2483. mutex_lock(&pool->pool_lock);
  2484. bool free_tmpl = !--*work->tmpl_refcount;
  2485. mutex_unlock(&pool->pool_lock);
  2486. if (free_tmpl) {
  2487. blktmpl_free(work->tmpl);
  2488. free(work->tmpl_refcount);
  2489. }
  2490. }
  2491. free(work);
  2492. }
  2493. static void workio_cmd_free(struct workio_cmd *wc)
  2494. {
  2495. if (!wc)
  2496. return;
  2497. switch (wc->cmd) {
  2498. case WC_SUBMIT_WORK:
  2499. free_work(wc->work);
  2500. break;
  2501. default: /* do nothing */
  2502. break;
  2503. }
  2504. memset(wc, 0, sizeof(*wc)); /* poison */
  2505. free(wc);
  2506. }
  2507. #ifdef HAVE_CURSES
  2508. static void disable_curses(void)
  2509. {
  2510. if (curses_active_locked()) {
  2511. curses_active = false;
  2512. leaveok(logwin, false);
  2513. leaveok(statuswin, false);
  2514. leaveok(mainwin, false);
  2515. nocbreak();
  2516. echo();
  2517. delwin(logwin);
  2518. delwin(statuswin);
  2519. delwin(mainwin);
  2520. endwin();
  2521. #ifdef WIN32
  2522. // Move the cursor to after curses output.
  2523. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2524. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2525. COORD coord;
  2526. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2527. coord.X = 0;
  2528. coord.Y = csbi.dwSize.Y - 1;
  2529. SetConsoleCursorPosition(hout, coord);
  2530. }
  2531. #endif
  2532. unlock_curses();
  2533. }
  2534. }
  2535. #endif
  2536. static void print_summary(void);
  2537. static void __kill_work(void)
  2538. {
  2539. struct thr_info *thr;
  2540. int i;
  2541. if (!successful_connect)
  2542. return;
  2543. applog(LOG_INFO, "Received kill message");
  2544. applog(LOG_DEBUG, "Killing off watchpool thread");
  2545. /* Kill the watchpool thread */
  2546. thr = &thr_info[watchpool_thr_id];
  2547. thr_info_cancel(thr);
  2548. applog(LOG_DEBUG, "Killing off watchdog thread");
  2549. /* Kill the watchdog thread */
  2550. thr = &thr_info[watchdog_thr_id];
  2551. thr_info_cancel(thr);
  2552. applog(LOG_DEBUG, "Stopping mining threads");
  2553. /* Stop the mining threads*/
  2554. for (i = 0; i < mining_threads; i++) {
  2555. thr = &thr_info[i];
  2556. thr_info_freeze(thr);
  2557. thr->pause = true;
  2558. }
  2559. sleep(1);
  2560. applog(LOG_DEBUG, "Killing off mining threads");
  2561. /* Kill the mining threads*/
  2562. for (i = 0; i < mining_threads; i++) {
  2563. thr = &thr_info[i];
  2564. thr_info_cancel(thr);
  2565. }
  2566. applog(LOG_DEBUG, "Killing off stage thread");
  2567. /* Stop the others */
  2568. thr = &thr_info[stage_thr_id];
  2569. thr_info_cancel(thr);
  2570. applog(LOG_DEBUG, "Killing off API thread");
  2571. thr = &thr_info[api_thr_id];
  2572. thr_info_cancel(thr);
  2573. }
  2574. /* This should be the common exit path */
  2575. void kill_work(void)
  2576. {
  2577. __kill_work();
  2578. quit(0, "Shutdown signal received.");
  2579. }
  2580. static
  2581. #ifdef WIN32
  2582. const
  2583. #endif
  2584. char **initial_args;
  2585. static void clean_up(void);
  2586. static inline void __app_restart(void)
  2587. {
  2588. #if defined(unix)
  2589. if (forkpid > 0) {
  2590. kill(forkpid, SIGTERM);
  2591. forkpid = 0;
  2592. }
  2593. #endif
  2594. execv(initial_args[0], initial_args);
  2595. }
  2596. void app_restart(void)
  2597. {
  2598. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2599. __kill_work();
  2600. clean_up();
  2601. __app_restart();
  2602. /* We shouldn't reach here */
  2603. applog(LOG_WARNING, "Failed to restart application");
  2604. }
  2605. /* Returns all signal handlers to their defaults */
  2606. static inline void __sighandler(void)
  2607. {
  2608. /* Restore signal handlers so we can still quit if kill_work fails */
  2609. sigaction(SIGTERM, &termhandler, NULL);
  2610. sigaction(SIGINT, &inthandler, NULL);
  2611. if (opt_restart) {
  2612. sigaction(SIGSEGV, &segvhandler, NULL);
  2613. sigaction(SIGILL, &illhandler, NULL);
  2614. #ifndef WIN32
  2615. sigaction(SIGBUS, &bushandler, NULL);
  2616. #endif
  2617. }
  2618. }
  2619. static void sighandler(int __maybe_unused sig)
  2620. {
  2621. __sighandler();
  2622. kill_work();
  2623. }
  2624. /* Handles segfaults and other crashes by attempting to restart cgminer. Try to
  2625. * do as little as possible since we are probably corrupted. */
  2626. static void seghandler(int sig)
  2627. {
  2628. __sighandler();
  2629. fprintf(stderr, "\nCrashed with signal %d! Will attempt to restart\n", sig);
  2630. __app_restart();
  2631. /* We shouldn't reach here */
  2632. fprintf(stderr, "Failed to restart, exiting now\n");
  2633. exit(1);
  2634. }
  2635. static void start_longpoll(void);
  2636. static void stop_longpoll(void);
  2637. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2638. * this pool. */
  2639. static void recruit_curl(struct pool *pool)
  2640. {
  2641. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2642. ce->curl = curl_easy_init();
  2643. if (unlikely(!ce || !ce->curl))
  2644. quit(1, "Failed to init in recruit_curl");
  2645. list_add(&ce->node, &pool->curlring);
  2646. pool->curls++;
  2647. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2648. }
  2649. /* Grab an available curl if there is one. If not, then recruit extra curls
  2650. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2651. * and there are already 5 curls in circulation. Limit total number to the
  2652. * number of mining threads per pool as well to prevent blasting a pool during
  2653. * network delays/outages. */
  2654. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2655. {
  2656. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2657. struct curl_ent *ce;
  2658. mutex_lock(&pool->pool_lock);
  2659. retry:
  2660. if (!pool->curls)
  2661. recruit_curl(pool);
  2662. else if (list_empty(&pool->curlring)) {
  2663. if (pool->curls >= curl_limit) {
  2664. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2665. goto retry;
  2666. } else
  2667. recruit_curl(pool);
  2668. }
  2669. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2670. list_del(&ce->node);
  2671. mutex_unlock(&pool->pool_lock);
  2672. return ce;
  2673. }
  2674. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2675. {
  2676. mutex_lock(&pool->pool_lock);
  2677. if (!ce || !ce->curl)
  2678. quit(1, "Attempted to add NULL in push_curl_entry");
  2679. list_add_tail(&ce->node, &pool->curlring);
  2680. gettimeofday(&ce->tv, NULL);
  2681. pthread_cond_signal(&pool->cr_cond);
  2682. mutex_unlock(&pool->pool_lock);
  2683. }
  2684. /* This is overkill, but at least we'll know accurately how much work is
  2685. * queued to prevent ever being left without work */
  2686. static void inc_queued(struct pool *pool)
  2687. {
  2688. mutex_lock(&qd_lock);
  2689. total_queued++;
  2690. pool->queued++;
  2691. mutex_unlock(&qd_lock);
  2692. }
  2693. static void dec_queued(struct pool *pool)
  2694. {
  2695. mutex_lock(&qd_lock);
  2696. total_queued--;
  2697. pool->queued--;
  2698. mutex_unlock(&qd_lock);
  2699. }
  2700. static int __global_queued(void)
  2701. {
  2702. return total_queued;
  2703. }
  2704. static int global_queued(void)
  2705. {
  2706. int ret;
  2707. mutex_lock(&qd_lock);
  2708. ret = __global_queued();
  2709. mutex_unlock(&qd_lock);
  2710. return ret;
  2711. }
  2712. static bool stale_work(struct work *work, bool share);
  2713. static inline bool should_roll(struct work *work)
  2714. {
  2715. struct timeval now;
  2716. time_t expiry;
  2717. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2718. return false;
  2719. if (work->rolltime > opt_scantime)
  2720. expiry = work->rolltime;
  2721. else
  2722. expiry = opt_scantime;
  2723. expiry = expiry * 2 / 3;
  2724. /* We shouldn't roll if we're unlikely to get one shares' duration
  2725. * work out of doing so */
  2726. gettimeofday(&now, NULL);
  2727. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2728. return false;
  2729. return true;
  2730. }
  2731. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2732. * reject blocks as invalid. */
  2733. static inline bool can_roll(struct work *work)
  2734. {
  2735. if (work->stratum)
  2736. return false;
  2737. if (!(work->pool && !work->clone))
  2738. return false;
  2739. if (work->tmpl) {
  2740. if (stale_work(work, false))
  2741. return false;
  2742. return blkmk_work_left(work->tmpl);
  2743. }
  2744. return (work->rolltime &&
  2745. work->rolls < 7000 && !stale_work(work, false));
  2746. }
  2747. static void roll_work(struct work *work)
  2748. {
  2749. if (work->tmpl) {
  2750. if (blkmk_get_data(work->tmpl, work->data, 80, time(NULL), NULL, &work->dataid) < 76)
  2751. applog(LOG_ERR, "Failed to get next data from template; spinning wheels!");
  2752. swap32yes(work->data, work->data, 80 / 4);
  2753. calc_midstate(work);
  2754. applog(LOG_DEBUG, "Successfully rolled extranonce to dataid %u", work->dataid);
  2755. } else {
  2756. uint32_t *work_ntime;
  2757. uint32_t ntime;
  2758. work_ntime = (uint32_t *)(work->data + 68);
  2759. ntime = be32toh(*work_ntime);
  2760. ntime++;
  2761. *work_ntime = htobe32(ntime);
  2762. applog(LOG_DEBUG, "Successfully rolled time header in work");
  2763. }
  2764. local_work++;
  2765. work->rolls++;
  2766. work->blk.nonce = 0;
  2767. /* This is now a different work item so it needs a different ID for the
  2768. * hashtable */
  2769. work->id = total_work++;
  2770. }
  2771. static void workcpy(struct work *dest, const struct work *work)
  2772. {
  2773. memcpy(dest, work, sizeof(*dest));
  2774. if (work->tmpl) {
  2775. struct pool *pool = work->pool;
  2776. mutex_lock(&pool->pool_lock);
  2777. ++*work->tmpl_refcount;
  2778. mutex_unlock(&pool->pool_lock);
  2779. }
  2780. }
  2781. static struct work *make_clone(struct work *work)
  2782. {
  2783. struct work *work_clone = make_work();
  2784. workcpy(work_clone, work);
  2785. work_clone->clone = true;
  2786. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  2787. work_clone->longpoll = false;
  2788. work_clone->mandatory = false;
  2789. /* Make cloned work appear slightly older to bias towards keeping the
  2790. * master work item which can be further rolled */
  2791. work_clone->tv_staged.tv_sec -= 1;
  2792. return work_clone;
  2793. }
  2794. static bool stage_work(struct work *work);
  2795. static bool clone_available(void)
  2796. {
  2797. struct work *work, *tmp;
  2798. bool cloned = false;
  2799. if (!staged_rollable)
  2800. goto out;
  2801. mutex_lock(stgd_lock);
  2802. HASH_ITER(hh, staged_work, work, tmp) {
  2803. if (can_roll(work) && should_roll(work)) {
  2804. struct work *work_clone;
  2805. roll_work(work);
  2806. work_clone = make_clone(work);
  2807. roll_work(work);
  2808. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2809. if (unlikely(!stage_work(work_clone))) {
  2810. free(work_clone);
  2811. break;
  2812. }
  2813. cloned = true;
  2814. break;
  2815. }
  2816. }
  2817. mutex_unlock(stgd_lock);
  2818. out:
  2819. return cloned;
  2820. }
  2821. static bool queue_request(void);
  2822. static void pool_died(struct pool *pool)
  2823. {
  2824. if (!pool_tset(pool, &pool->idle)) {
  2825. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2826. gettimeofday(&pool->tv_idle, NULL);
  2827. switch_pools(NULL);
  2828. }
  2829. }
  2830. static void gen_stratum_work(struct pool *pool, struct work *work);
  2831. static void *get_work_thread(void *userdata)
  2832. {
  2833. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2834. struct work *ret_work= NULL;
  2835. struct curl_ent *ce = NULL;
  2836. struct pool *pool;
  2837. pthread_detach(pthread_self());
  2838. rename_thr("bfg-get_work");
  2839. applog(LOG_DEBUG, "Creating extra get work thread");
  2840. retry:
  2841. pool = wc->pool;
  2842. if (pool->has_stratum) {
  2843. while (!pool->stratum_active) {
  2844. struct pool *altpool = select_pool(true);
  2845. sleep(5);
  2846. if (altpool != pool) {
  2847. wc->pool = altpool;
  2848. inc_queued(altpool);
  2849. dec_queued(pool);
  2850. goto retry;
  2851. }
  2852. }
  2853. ret_work = make_work();
  2854. gen_stratum_work(pool, ret_work);
  2855. if (unlikely(!stage_work(ret_work))) {
  2856. applog(LOG_ERR, "Failed to stage stratum work in get_work_thread");
  2857. kill_work();
  2858. free(ret_work);
  2859. }
  2860. dec_queued(pool);
  2861. goto out;
  2862. }
  2863. if (clone_available()) {
  2864. applog(LOG_DEBUG, "dec_queued from get_work_thread due to clone available\n");
  2865. dec_queued(pool);
  2866. goto out;
  2867. }
  2868. ret_work = make_work();
  2869. ret_work->thr = NULL;
  2870. if (opt_benchmark) {
  2871. get_benchmark_work(ret_work);
  2872. ret_work->queued = true;
  2873. } else {
  2874. ret_work->pool = wc->pool;
  2875. if (!ce)
  2876. ce = pop_curl_entry(pool);
  2877. /* obtain new work from bitcoin via JSON-RPC */
  2878. if (!get_upstream_work(ret_work, ce->curl)) {
  2879. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  2880. sleep(5);
  2881. dec_queued(pool);
  2882. /* Make sure the pool just hasn't stopped serving
  2883. * requests but is up as we'll keep hammering it */
  2884. if (++pool->seq_getfails > mining_threads + opt_queue)
  2885. pool_died(pool);
  2886. queue_request();
  2887. free_work(ret_work);
  2888. goto out;
  2889. }
  2890. pool->seq_getfails = 0;
  2891. ret_work->queued = true;
  2892. }
  2893. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2894. /* send work to requesting thread */
  2895. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2896. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2897. kill_work();
  2898. free_work(ret_work);
  2899. dec_queued(pool);
  2900. }
  2901. out:
  2902. workio_cmd_free(wc);
  2903. if (ce)
  2904. push_curl_entry(ce, pool);
  2905. return NULL;
  2906. }
  2907. /* As per the submit work system, we try to reuse the existing curl handles,
  2908. * but start recruiting extra connections if we start accumulating queued
  2909. * requests */
  2910. static bool workio_get_work(struct workio_cmd *wc)
  2911. {
  2912. pthread_t get_thread;
  2913. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2914. applog(LOG_ERR, "Failed to create get_work_thread");
  2915. return false;
  2916. }
  2917. return true;
  2918. }
  2919. static bool stale_work(struct work *work, bool share)
  2920. {
  2921. struct timeval now;
  2922. time_t work_expiry;
  2923. struct pool *pool;
  2924. uint32_t block_id;
  2925. int getwork_delay;
  2926. block_id = ((uint32_t*)work->data)[1];
  2927. pool = work->pool;
  2928. /* Technically the rolltime should be correct but some pools
  2929. * advertise a broken expire= that is lower than a meaningful
  2930. * scantime */
  2931. if (work->rolltime > opt_scantime)
  2932. work_expiry = work->rolltime;
  2933. else
  2934. work_expiry = opt_expiry;
  2935. if (share) {
  2936. /* If the share isn't on this pool's latest block, it's stale */
  2937. if (pool->block_id && pool->block_id != block_id)
  2938. {
  2939. applog(LOG_DEBUG, "Share stale due to block mismatch (%08lx != %08lx)", (long)block_id, (long)pool->block_id);
  2940. return true;
  2941. }
  2942. /* If the pool doesn't want old shares, then any found in work before
  2943. * the most recent longpoll is stale */
  2944. if ((!pool->submit_old) && work->work_restart_id != pool->work_restart_id)
  2945. {
  2946. applog(LOG_DEBUG, "Share stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2947. return true;
  2948. }
  2949. } else {
  2950. /* If this work isn't for the latest Bitcoin block, it's stale */
  2951. /* But only care about the current pool if failover-only */
  2952. if (enabled_pools <= 1 || opt_fail_only) {
  2953. if (pool->block_id && block_id != pool->block_id)
  2954. {
  2955. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 1 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  2956. return true;
  2957. }
  2958. } else {
  2959. if (block_id != current_block_id)
  2960. {
  2961. applog(LOG_DEBUG, "Work stale due to block mismatch (%08lx != 0 ? %08lx : %08lx)", (long)block_id, (long)pool->block_id, (long)current_block_id);
  2962. return true;
  2963. }
  2964. }
  2965. /* If the pool has asked us to restart since this work, it's stale */
  2966. if (work->work_restart_id != pool->work_restart_id)
  2967. {
  2968. applog(LOG_DEBUG, "Work stale due to work restart (%02x != %02x)", work->work_restart_id, pool->work_restart_id);
  2969. return true;
  2970. }
  2971. /* Factor in the average getwork delay of this pool, rounding it up to
  2972. * the nearest second */
  2973. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2974. work_expiry -= getwork_delay;
  2975. if (unlikely(work_expiry < 5))
  2976. work_expiry = 5;
  2977. }
  2978. gettimeofday(&now, NULL);
  2979. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2980. applog(LOG_DEBUG, "%s stale due to expiry (%d - %d >= %d)", share?"Share":"Work", now.tv_sec, work->tv_staged.tv_sec, work_expiry);
  2981. return true;
  2982. }
  2983. /* If the user only wants strict failover, any work from a pool other than
  2984. * the current one is always considered stale */
  2985. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2986. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2987. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch (pool %u vs %u)", pool->pool_no, current_pool()->pool_no);
  2988. return true;
  2989. }
  2990. return false;
  2991. }
  2992. static void check_solve(struct work *work)
  2993. {
  2994. work->block = regeneratehash(work);
  2995. if (unlikely(work->block)) {
  2996. work->pool->solved++;
  2997. found_blocks++;
  2998. work->mandatory = true;
  2999. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  3000. }
  3001. }
  3002. static void submit_discard_share(struct work *work)
  3003. {
  3004. sharelog("discard", work);
  3005. ++total_stale;
  3006. ++(work->pool->stale_shares);
  3007. total_diff_stale += work->work_difficulty;
  3008. work->pool->diff_stale += work->work_difficulty;
  3009. }
  3010. static void *submit_work_thread(void *userdata)
  3011. {
  3012. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  3013. struct work *work;
  3014. struct pool *pool;
  3015. bool resubmit;
  3016. struct curl_ent *ce;
  3017. int failures;
  3018. time_t staleexpire;
  3019. pthread_detach(pthread_self());
  3020. rename_thr("bfg-submit_work");
  3021. applog(LOG_DEBUG, "Creating extra submit work thread");
  3022. next_submit:
  3023. work = wc->work;
  3024. pool = work->pool;
  3025. resubmit = false;
  3026. failures = 0;
  3027. check_solve(work);
  3028. if (stale_work(work, true)) {
  3029. work->stale = true;
  3030. if (unlikely(!list_empty(&submit_waiting))) {
  3031. applog(LOG_WARNING, "Stale share detected while queued submissions are waiting, discarding");
  3032. submit_discard_share(work);
  3033. goto out;
  3034. }
  3035. if (opt_submit_stale)
  3036. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  3037. else if (pool->submit_old)
  3038. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  3039. else {
  3040. applog(LOG_NOTICE, "Stale share detected, discarding");
  3041. submit_discard_share(work);
  3042. goto out;
  3043. }
  3044. staleexpire = time(NULL) + 300;
  3045. }
  3046. if (work->stratum) {
  3047. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  3048. uint32_t *hash32 = (uint32_t *)work->hash, nonce;
  3049. char *noncehex;
  3050. char s[1024];
  3051. memcpy(&sshare->work, work, sizeof(struct work));
  3052. /* Give the stratum share a unique id */
  3053. mutex_lock(&sshare_lock);
  3054. sshare->id = swork_id++;
  3055. HASH_ADD_INT(stratum_shares, id, sshare);
  3056. mutex_unlock(&sshare_lock);
  3057. nonce = *((uint32_t *)(work->data + 76));
  3058. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  3059. memset(s, 0, 1024);
  3060. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  3061. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  3062. free(noncehex);
  3063. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->stratum_url, s);
  3064. if (unlikely(!stratum_send(pool, s, strlen(s)))) {
  3065. mutex_lock(&sshare_lock);
  3066. HASH_DEL(stratum_shares, sshare);
  3067. mutex_unlock(&sshare_lock);
  3068. free(sshare);
  3069. }
  3070. goto out;
  3071. }
  3072. ce = pop_curl_entry(pool);
  3073. /* submit solution to bitcoin via JSON-RPC */
  3074. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  3075. resubmit = true;
  3076. if ((!work->stale) && stale_work(work, true)) {
  3077. work->stale = true;
  3078. if (opt_submit_stale)
  3079. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as user requested");
  3080. else if (pool->submit_old)
  3081. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as pool requested");
  3082. else {
  3083. applog(LOG_NOTICE, "Share become stale during submission failure, discarding");
  3084. submit_discard_share(work);
  3085. break;
  3086. }
  3087. staleexpire = time(NULL) + 300;
  3088. }
  3089. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  3090. applog(LOG_ERR, "Failed %d retries, discarding", opt_retries);
  3091. submit_discard_share(work);
  3092. break;
  3093. }
  3094. else if (work->stale) {
  3095. if (unlikely(!list_empty(&submit_waiting))) {
  3096. applog(LOG_WARNING, "Stale share failed to submit while queued submissions are waiting, discarding");
  3097. submit_discard_share(work);
  3098. break;
  3099. } else if (unlikely(opt_retries < 0 && staleexpire <= time(NULL))) {
  3100. applog(LOG_NOTICE, "Stale share failed to submit for 5 minutes, discarding");
  3101. submit_discard_share(work);
  3102. break;
  3103. }
  3104. }
  3105. /* pause, then restart work-request loop */
  3106. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3107. }
  3108. push_curl_entry(ce, pool);
  3109. out:
  3110. workio_cmd_free(wc);
  3111. mutex_lock(&submitting_lock);
  3112. if (!list_empty(&submit_waiting)) {
  3113. applog(LOG_DEBUG, "submit_work continuing with queued submission");
  3114. wc = list_entry(submit_waiting.next, struct workio_cmd, list);
  3115. list_del(&wc->list);
  3116. mutex_unlock(&submitting_lock);
  3117. goto next_submit;
  3118. }
  3119. --submitting;
  3120. mutex_unlock(&submitting_lock);
  3121. return NULL;
  3122. }
  3123. /* We try to reuse curl handles as much as possible, but if there is already
  3124. * work queued to be submitted, we start generating extra handles to submit
  3125. * the shares to avoid ever increasing backlogs. This allows us to scale to
  3126. * any size hardware */
  3127. static bool workio_submit_work(struct workio_cmd *wc)
  3128. {
  3129. pthread_t submit_thread;
  3130. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  3131. applog(LOG_ERR, "Failed to create submit_work_thread");
  3132. return false;
  3133. }
  3134. return true;
  3135. }
  3136. /* Find the pool that currently has the highest priority */
  3137. static struct pool *priority_pool(int choice)
  3138. {
  3139. struct pool *ret = NULL;
  3140. int i;
  3141. for (i = 0; i < total_pools; i++) {
  3142. struct pool *pool = pools[i];
  3143. if (pool->prio == choice) {
  3144. ret = pool;
  3145. break;
  3146. }
  3147. }
  3148. if (unlikely(!ret)) {
  3149. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3150. return pools[choice];
  3151. }
  3152. return ret;
  3153. }
  3154. void switch_pools(struct pool *selected)
  3155. {
  3156. struct pool *pool, *last_pool;
  3157. int i, pool_no, next_pool;
  3158. mutex_lock(&control_lock);
  3159. last_pool = currentpool;
  3160. pool_no = currentpool->pool_no;
  3161. /* Switch selected to pool number 0 and move the rest down */
  3162. if (selected) {
  3163. if (selected->prio != 0) {
  3164. for (i = 0; i < total_pools; i++) {
  3165. pool = pools[i];
  3166. if (pool->prio < selected->prio)
  3167. pool->prio++;
  3168. }
  3169. selected->prio = 0;
  3170. }
  3171. }
  3172. switch (pool_strategy) {
  3173. /* Both of these set to the master pool */
  3174. case POOL_BALANCE:
  3175. case POOL_FAILOVER:
  3176. case POOL_LOADBALANCE:
  3177. for (i = 0; i < total_pools; i++) {
  3178. pool = priority_pool(i);
  3179. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3180. pool_no = pool->pool_no;
  3181. break;
  3182. }
  3183. }
  3184. break;
  3185. /* Both of these simply increment and cycle */
  3186. case POOL_ROUNDROBIN:
  3187. case POOL_ROTATE:
  3188. if (selected && !selected->idle) {
  3189. pool_no = selected->pool_no;
  3190. break;
  3191. }
  3192. next_pool = pool_no;
  3193. /* Select the next alive pool */
  3194. for (i = 1; i < total_pools; i++) {
  3195. next_pool++;
  3196. if (next_pool >= total_pools)
  3197. next_pool = 0;
  3198. pool = pools[next_pool];
  3199. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3200. pool_no = next_pool;
  3201. break;
  3202. }
  3203. }
  3204. break;
  3205. default:
  3206. break;
  3207. }
  3208. currentpool = pools[pool_no];
  3209. pool = currentpool;
  3210. mutex_unlock(&control_lock);
  3211. /* Set the lagging flag to avoid pool not providing work fast enough
  3212. * messages in failover only mode since we have to get all fresh work
  3213. * as in restart_threads */
  3214. if (opt_fail_only)
  3215. pool_tset(pool, &pool->lagging);
  3216. if (pool != last_pool)
  3217. {
  3218. pool->block_id = 0;
  3219. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  3220. }
  3221. mutex_lock(&lp_lock);
  3222. pthread_cond_broadcast(&lp_cond);
  3223. mutex_unlock(&lp_lock);
  3224. }
  3225. static void discard_work(struct work *work)
  3226. {
  3227. if (!work->clone && !work->rolls && !work->mined) {
  3228. if (work->pool)
  3229. work->pool->discarded_work++;
  3230. total_discarded++;
  3231. applog(LOG_DEBUG, "Discarded work");
  3232. } else
  3233. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3234. free_work(work);
  3235. }
  3236. static void discard_stale(void)
  3237. {
  3238. struct work *work, *tmp;
  3239. int stale = 0;
  3240. mutex_lock(stgd_lock);
  3241. HASH_ITER(hh, staged_work, work, tmp) {
  3242. if (stale_work(work, false)) {
  3243. HASH_DEL(staged_work, work);
  3244. work->pool->staged--;
  3245. discard_work(work);
  3246. stale++;
  3247. }
  3248. }
  3249. mutex_unlock(stgd_lock);
  3250. if (stale) {
  3251. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3252. while (stale-- > 0)
  3253. queue_request();
  3254. }
  3255. }
  3256. void ms_to_abstime(unsigned int mstime, struct timespec *abstime)
  3257. {
  3258. struct timeval now, then, tdiff;
  3259. tdiff.tv_sec = mstime / 1000;
  3260. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  3261. gettimeofday(&now, NULL);
  3262. timeradd(&now, &tdiff, &then);
  3263. abstime->tv_sec = then.tv_sec;
  3264. abstime->tv_nsec = then.tv_usec * 1000;
  3265. }
  3266. /* A generic wait function for threads that poll that will wait a specified
  3267. * time tdiff waiting on the pthread conditional that is broadcast when a
  3268. * work restart is required. Returns the value of pthread_cond_timedwait
  3269. * which is zero if the condition was met or ETIMEDOUT if not.
  3270. */
  3271. int restart_wait(unsigned int mstime)
  3272. {
  3273. struct timespec abstime;
  3274. int rc;
  3275. ms_to_abstime(mstime, &abstime);
  3276. mutex_lock(&restart_lock);
  3277. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  3278. mutex_unlock(&restart_lock);
  3279. return rc;
  3280. }
  3281. /* A generic wait function for threads that poll that will wait a specified
  3282. * time waiting on a share to become stale. Returns positive if the share
  3283. * became stale or zero if the timer expired first. If checkend is true, will
  3284. * immediatley return negative if the share is guaranteed to become stale
  3285. * before the timer expires.
  3286. */
  3287. int stale_wait(unsigned int mstime, struct work*work, bool checkend)
  3288. {
  3289. struct timespec abstime;
  3290. int rc;
  3291. if (checkend) {
  3292. struct timeval tv, orig;
  3293. ldiv_t d;
  3294. d = ldiv(mstime, 1000);
  3295. tv.tv_sec = d.quot;
  3296. tv.tv_usec = d.rem * 1000;
  3297. orig = work->tv_staged;
  3298. timersub(&orig, &tv, &work->tv_staged);
  3299. rc = stale_work(work, true);
  3300. work->tv_staged = orig;
  3301. if (rc)
  3302. return -1;
  3303. }
  3304. ms_to_abstime(mstime, &abstime);
  3305. rc = -1;
  3306. while (1) {
  3307. mutex_lock(&restart_lock);
  3308. if (stale_work(work, true)) {
  3309. rc = 1;
  3310. } else if (pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime)) {
  3311. rc = 0;
  3312. }
  3313. mutex_unlock(&restart_lock);
  3314. if (rc != -1)
  3315. return rc;
  3316. }
  3317. }
  3318. static void restart_threads(void)
  3319. {
  3320. struct pool *cp = current_pool();
  3321. int i, fd;
  3322. struct thr_info *thr;
  3323. /* Artificially set the lagging flag to avoid pool not providing work
  3324. * fast enough messages after every long poll */
  3325. pool_tset(cp, &cp->lagging);
  3326. /* Discard staged work that is now stale */
  3327. discard_stale();
  3328. for (i = 0; i < mining_threads; i++)
  3329. {
  3330. thr = &thr_info[i];
  3331. fd = thr->_work_restart_fd_w;
  3332. thr->work_restart = true;
  3333. if (fd != -1)
  3334. write(fd, "\0", 1);
  3335. }
  3336. mutex_lock(&restart_lock);
  3337. pthread_cond_broadcast(&restart_cond);
  3338. mutex_unlock(&restart_lock);
  3339. }
  3340. static char *blkhashstr(unsigned char *hash)
  3341. {
  3342. unsigned char hash_swap[32];
  3343. swap256(hash_swap, hash);
  3344. swap32tole(hash_swap, hash_swap, 32 / 4);
  3345. return bin2hex(hash_swap, 32);
  3346. }
  3347. static void set_curblock(char *hexstr, unsigned char *hash)
  3348. {
  3349. unsigned char hash_swap[32];
  3350. char *old_hash;
  3351. current_block_id = ((uint32_t*)hash)[0];
  3352. strcpy(current_block, hexstr);
  3353. swap256(hash_swap, hash);
  3354. swap32tole(hash_swap, hash_swap, 32 / 4);
  3355. /* Don't free current_hash directly to avoid dereferencing when read
  3356. * elsewhere - and update block_timeval inside the same lock */
  3357. mutex_lock(&ch_lock);
  3358. gettimeofday(&block_timeval, NULL);
  3359. old_hash = current_hash;
  3360. current_hash = bin2hex(hash_swap + 4, 16);
  3361. free(old_hash);
  3362. old_hash = current_fullhash;
  3363. current_fullhash = bin2hex(hash_swap, 32);
  3364. free(old_hash);
  3365. mutex_unlock(&ch_lock);
  3366. get_timestamp(blocktime, &block_timeval);
  3367. if (unlikely(!current_hash))
  3368. quit (1, "set_curblock OOM");
  3369. applog(LOG_INFO, "New block: %s...", current_hash);
  3370. }
  3371. /* Search to see if this string is from a block that has been seen before */
  3372. static bool block_exists(char *hexstr)
  3373. {
  3374. struct block *s;
  3375. rd_lock(&blk_lock);
  3376. HASH_FIND_STR(blocks, hexstr, s);
  3377. rd_unlock(&blk_lock);
  3378. if (s)
  3379. return true;
  3380. return false;
  3381. }
  3382. /* Tests if this work is from a block that has been seen before */
  3383. static inline bool from_existing_block(struct work *work)
  3384. {
  3385. char *hexstr = bin2hex(work->data + 8, 18);
  3386. bool ret;
  3387. ret = block_exists(hexstr);
  3388. free(hexstr);
  3389. return ret;
  3390. }
  3391. static int block_sort(struct block *blocka, struct block *blockb)
  3392. {
  3393. return blocka->block_no - blockb->block_no;
  3394. }
  3395. static bool test_work_current(struct work *work)
  3396. {
  3397. bool ret = true;
  3398. char *hexstr;
  3399. if (work->mandatory)
  3400. return ret;
  3401. uint32_t block_id = ((uint32_t*)(work->data))[1];
  3402. hexstr = bin2hex(work->data + 8, 18);
  3403. /* Search to see if this block exists yet and if not, consider it a
  3404. * new block and set the current block details to this one */
  3405. if (!block_exists(hexstr)) {
  3406. struct block *s = calloc(sizeof(struct block), 1);
  3407. int deleted_block = 0;
  3408. ret = false;
  3409. if (unlikely(!s))
  3410. quit (1, "test_work_current OOM");
  3411. strcpy(s->hash, hexstr);
  3412. s->block_no = new_blocks++;
  3413. wr_lock(&blk_lock);
  3414. /* Only keep the last hour's worth of blocks in memory since
  3415. * work from blocks before this is virtually impossible and we
  3416. * want to prevent memory usage from continually rising */
  3417. if (HASH_COUNT(blocks) > 6) {
  3418. struct block *oldblock;
  3419. HASH_SORT(blocks, block_sort);
  3420. oldblock = blocks;
  3421. deleted_block = oldblock->block_no;
  3422. HASH_DEL(blocks, oldblock);
  3423. free(oldblock);
  3424. }
  3425. HASH_ADD_STR(blocks, hash, s);
  3426. wr_unlock(&blk_lock);
  3427. work->pool->block_id = block_id;
  3428. if (deleted_block)
  3429. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3430. set_curblock(hexstr, &work->data[4]);
  3431. if (unlikely(new_blocks == 1))
  3432. goto out_free;
  3433. if (!work->stratum) {
  3434. if (work->longpoll) {
  3435. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  3436. work->pool->pool_no);
  3437. work->longpoll = false;
  3438. } else if (have_longpoll)
  3439. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3440. else
  3441. applog(LOG_NOTICE, "New block detected on network");
  3442. }
  3443. restart_threads();
  3444. } else {
  3445. bool restart = false;
  3446. struct pool *curpool = NULL;
  3447. if (unlikely(work->pool->block_id != block_id)) {
  3448. bool was_active = work->pool->block_id != 0;
  3449. work->pool->block_id = block_id;
  3450. if (was_active) { // Pool actively changed block
  3451. if (work->pool == (curpool = current_pool()))
  3452. restart = true;
  3453. if (block_id == current_block_id) {
  3454. // Caught up, only announce if this pool is the one in use
  3455. if (restart)
  3456. applog(LOG_NOTICE, "%s %d caught up to new block",
  3457. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3458. work->pool->pool_no);
  3459. } else {
  3460. // Switched to a block we know, but not the latest... why?
  3461. // This might detect pools trying to double-spend or 51%,
  3462. // but let's not make any accusations until it's had time
  3463. // in the real world.
  3464. free(hexstr);
  3465. hexstr = blkhashstr(&work->data[4]);
  3466. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  3467. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3468. work->pool->pool_no,
  3469. hexstr);
  3470. }
  3471. }
  3472. }
  3473. if (work->longpoll) {
  3474. work->longpoll = false;
  3475. ++work->pool->work_restart_id;
  3476. if ((!restart) && work->pool == current_pool()) {
  3477. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  3478. work->pool->pool_no);
  3479. restart = true;
  3480. }
  3481. }
  3482. if (restart)
  3483. restart_threads();
  3484. }
  3485. out_free:
  3486. free(hexstr);
  3487. return ret;
  3488. }
  3489. static int tv_sort(struct work *worka, struct work *workb)
  3490. {
  3491. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3492. }
  3493. static bool work_rollable(struct work *work)
  3494. {
  3495. return (!work->clone && work->rolltime);
  3496. }
  3497. static bool hash_push(struct work *work)
  3498. {
  3499. bool rc = true;
  3500. mutex_lock(stgd_lock);
  3501. if (work_rollable(work))
  3502. staged_rollable++;
  3503. if (likely(!getq->frozen)) {
  3504. HASH_ADD_INT(staged_work, id, work);
  3505. HASH_SORT(staged_work, tv_sort);
  3506. } else
  3507. rc = false;
  3508. pthread_cond_signal(&getq->cond);
  3509. mutex_unlock(stgd_lock);
  3510. work->pool->staged++;
  3511. if (work->queued) {
  3512. work->queued = false;
  3513. applog(LOG_DEBUG, "dec_queued in hash_push\n");
  3514. dec_queued(work->pool);
  3515. }
  3516. return rc;
  3517. }
  3518. static void *stage_thread(void *userdata)
  3519. {
  3520. struct thr_info *mythr = userdata;
  3521. bool ok = true;
  3522. rename_thr("bfg-stage");
  3523. while (ok) {
  3524. struct work *work = NULL;
  3525. applog(LOG_DEBUG, "Popping work to stage thread");
  3526. work = tq_pop(mythr->q, NULL);
  3527. if (unlikely(!work)) {
  3528. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3529. ok = false;
  3530. break;
  3531. }
  3532. work->work_restart_id = work->pool->work_restart_id;
  3533. test_work_current(work);
  3534. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  3535. if (unlikely(!hash_push(work))) {
  3536. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3537. continue;
  3538. }
  3539. }
  3540. tq_freeze(mythr->q);
  3541. return NULL;
  3542. }
  3543. static bool stage_work(struct work *work)
  3544. {
  3545. applog(LOG_DEBUG, "Pushing work to stage thread");
  3546. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  3547. applog(LOG_ERR, "Could not tq_push work in stage_work");
  3548. return false;
  3549. }
  3550. return true;
  3551. }
  3552. #ifdef HAVE_CURSES
  3553. int curses_int(const char *query)
  3554. {
  3555. int ret;
  3556. char *cvar;
  3557. cvar = curses_input(query);
  3558. ret = atoi(cvar);
  3559. free(cvar);
  3560. return ret;
  3561. }
  3562. #endif
  3563. #ifdef HAVE_CURSES
  3564. static bool input_pool(bool live);
  3565. #endif
  3566. #ifdef HAVE_CURSES
  3567. static void display_pool_summary(struct pool *pool)
  3568. {
  3569. double efficiency = 0.0;
  3570. if (curses_active_locked()) {
  3571. wlog("Pool: %s\n", pool->rpc_url);
  3572. if (pool->solved)
  3573. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3574. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  3575. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3576. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3577. wlog(" Accepted shares: %d\n", pool->accepted);
  3578. wlog(" Rejected shares: %d\n", pool->rejected);
  3579. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3580. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3581. if (pool->accepted || pool->rejected)
  3582. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3583. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3584. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3585. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3586. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3587. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3588. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3589. unlock_curses();
  3590. }
  3591. }
  3592. #endif
  3593. /* We can't remove the memory used for this struct pool because there may
  3594. * still be work referencing it. We just remove it from the pools list */
  3595. void remove_pool(struct pool *pool)
  3596. {
  3597. int i, last_pool = total_pools - 1;
  3598. struct pool *other;
  3599. /* Boost priority of any lower prio than this one */
  3600. for (i = 0; i < total_pools; i++) {
  3601. other = pools[i];
  3602. if (other->prio > pool->prio)
  3603. other->prio--;
  3604. }
  3605. if (pool->pool_no < last_pool) {
  3606. /* Swap the last pool for this one */
  3607. (pools[last_pool])->pool_no = pool->pool_no;
  3608. pools[pool->pool_no] = pools[last_pool];
  3609. }
  3610. /* Give it an invalid number */
  3611. pool->pool_no = total_pools;
  3612. pool->removed = true;
  3613. pool->has_stratum = false;
  3614. total_pools--;
  3615. }
  3616. /* add a mutex if this needs to be thread safe in the future */
  3617. static struct JE {
  3618. char *buf;
  3619. struct JE *next;
  3620. } *jedata = NULL;
  3621. static void json_escape_free()
  3622. {
  3623. struct JE *jeptr = jedata;
  3624. struct JE *jenext;
  3625. jedata = NULL;
  3626. while (jeptr) {
  3627. jenext = jeptr->next;
  3628. free(jeptr->buf);
  3629. free(jeptr);
  3630. jeptr = jenext;
  3631. }
  3632. }
  3633. static char *json_escape(char *str)
  3634. {
  3635. struct JE *jeptr;
  3636. char *buf, *ptr;
  3637. /* 2x is the max, may as well just allocate that */
  3638. ptr = buf = malloc(strlen(str) * 2 + 1);
  3639. jeptr = malloc(sizeof(*jeptr));
  3640. jeptr->buf = buf;
  3641. jeptr->next = jedata;
  3642. jedata = jeptr;
  3643. while (*str) {
  3644. if (*str == '\\' || *str == '"')
  3645. *(ptr++) = '\\';
  3646. *(ptr++) = *(str++);
  3647. }
  3648. *ptr = '\0';
  3649. return buf;
  3650. }
  3651. void write_config(FILE *fcfg)
  3652. {
  3653. int i;
  3654. /* Write pool values */
  3655. fputs("{\n\"pools\" : [", fcfg);
  3656. for(i = 0; i < total_pools; i++) {
  3657. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  3658. if (pools[i]->rpc_proxy)
  3659. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  3660. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3661. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  3662. }
  3663. fputs("\n]\n", fcfg);
  3664. #ifdef HAVE_OPENCL
  3665. if (nDevs) {
  3666. /* Write GPU device values */
  3667. fputs(",\n\"intensity\" : \"", fcfg);
  3668. for(i = 0; i < nDevs; i++)
  3669. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3670. fputs("\",\n\"vectors\" : \"", fcfg);
  3671. for(i = 0; i < nDevs; i++)
  3672. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3673. gpus[i].vwidth);
  3674. fputs("\",\n\"worksize\" : \"", fcfg);
  3675. for(i = 0; i < nDevs; i++)
  3676. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3677. (int)gpus[i].work_size);
  3678. fputs("\",\n\"kernel\" : \"", fcfg);
  3679. for(i = 0; i < nDevs; i++) {
  3680. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3681. switch (gpus[i].kernel) {
  3682. case KL_NONE: // Shouldn't happen
  3683. break;
  3684. case KL_POCLBM:
  3685. fprintf(fcfg, "poclbm");
  3686. break;
  3687. case KL_PHATK:
  3688. fprintf(fcfg, "phatk");
  3689. break;
  3690. case KL_DIAKGCN:
  3691. fprintf(fcfg, "diakgcn");
  3692. break;
  3693. case KL_DIABLO:
  3694. fprintf(fcfg, "diablo");
  3695. break;
  3696. case KL_SCRYPT:
  3697. fprintf(fcfg, "scrypt");
  3698. break;
  3699. }
  3700. }
  3701. #ifdef USE_SCRYPT
  3702. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3703. for(i = 0; i < nDevs; i++)
  3704. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3705. (int)gpus[i].opt_lg);
  3706. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3707. for(i = 0; i < nDevs; i++)
  3708. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3709. (int)gpus[i].opt_tc);
  3710. fputs("\",\n\"shaders\" : \"", fcfg);
  3711. for(i = 0; i < nDevs; i++)
  3712. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3713. (int)gpus[i].shaders);
  3714. #endif
  3715. #ifdef HAVE_ADL
  3716. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3717. for(i = 0; i < nDevs; i++)
  3718. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3719. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3720. for(i = 0; i < nDevs; i++)
  3721. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3722. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3723. for(i = 0; i < nDevs; i++)
  3724. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3725. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3726. for(i = 0; i < nDevs; i++)
  3727. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3728. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3729. for(i = 0; i < nDevs; i++)
  3730. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3731. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3732. for(i = 0; i < nDevs; i++)
  3733. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3734. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3735. for(i = 0; i < nDevs; i++)
  3736. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3737. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3738. for(i = 0; i < nDevs; i++)
  3739. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3740. fputs("\",\n\"temp-target\" : \"", fcfg);
  3741. for(i = 0; i < nDevs; i++)
  3742. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].targettemp);
  3743. #endif
  3744. fputs("\"", fcfg);
  3745. }
  3746. #endif
  3747. #ifdef HAVE_ADL
  3748. if (opt_reorder)
  3749. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3750. #endif
  3751. #ifdef WANT_CPUMINE
  3752. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3753. #endif
  3754. /* Simple bool and int options */
  3755. struct opt_table *opt;
  3756. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3757. char *p, *name = strdup(opt->names);
  3758. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3759. if (p[1] != '-')
  3760. continue;
  3761. if (opt->type & OPT_NOARG &&
  3762. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3763. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3764. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3765. if (opt->type & OPT_HASARG &&
  3766. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3767. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3768. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3769. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  3770. opt->desc != opt_hidden &&
  3771. 0 <= *(int *)opt->u.arg)
  3772. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3773. }
  3774. }
  3775. /* Special case options */
  3776. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3777. if (pool_strategy == POOL_BALANCE)
  3778. fputs(",\n\"balance\" : true", fcfg);
  3779. if (pool_strategy == POOL_LOADBALANCE)
  3780. fputs(",\n\"load-balance\" : true", fcfg);
  3781. if (pool_strategy == POOL_ROUNDROBIN)
  3782. fputs(",\n\"round-robin\" : true", fcfg);
  3783. if (pool_strategy == POOL_ROTATE)
  3784. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3785. #if defined(unix)
  3786. if (opt_stderr_cmd && *opt_stderr_cmd)
  3787. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3788. #endif // defined(unix)
  3789. if (opt_kernel_path && *opt_kernel_path) {
  3790. char *kpath = strdup(opt_kernel_path);
  3791. if (kpath[strlen(kpath)-1] == '/')
  3792. kpath[strlen(kpath)-1] = 0;
  3793. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3794. }
  3795. if (schedstart.enable)
  3796. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3797. if (schedstop.enable)
  3798. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3799. if (opt_socks_proxy && *opt_socks_proxy)
  3800. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3801. #ifdef HAVE_OPENCL
  3802. for(i = 0; i < nDevs; i++)
  3803. if (gpus[i].deven == DEV_DISABLED)
  3804. break;
  3805. if (i < nDevs)
  3806. for (i = 0; i < nDevs; i++)
  3807. if (gpus[i].deven != DEV_DISABLED)
  3808. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3809. #endif
  3810. if (opt_api_allow)
  3811. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3812. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3813. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3814. if (opt_api_groups)
  3815. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3816. if (opt_icarus_options)
  3817. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3818. if (opt_icarus_timing)
  3819. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3820. fputs("\n}\n", fcfg);
  3821. json_escape_free();
  3822. }
  3823. #ifdef HAVE_CURSES
  3824. static void display_pools(void)
  3825. {
  3826. struct pool *pool;
  3827. int selected, i;
  3828. char input;
  3829. opt_loginput = true;
  3830. immedok(logwin, true);
  3831. clear_logwin();
  3832. updated:
  3833. for (i = 0; i < total_pools; i++) {
  3834. pool = pools[i];
  3835. if (pool == current_pool())
  3836. wattron(logwin, A_BOLD);
  3837. if (pool->enabled != POOL_ENABLED)
  3838. wattron(logwin, A_DIM);
  3839. wlogprint("%d: ", pool->pool_no);
  3840. switch (pool->enabled) {
  3841. case POOL_ENABLED:
  3842. wlogprint("Enabled ");
  3843. break;
  3844. case POOL_DISABLED:
  3845. wlogprint("Disabled ");
  3846. break;
  3847. case POOL_REJECTING:
  3848. wlogprint("Rejectin ");
  3849. break;
  3850. }
  3851. if (pool->idle)
  3852. wlogprint("Dead ");
  3853. else
  3854. if (pool->has_stratum)
  3855. wlogprint("Strtm");
  3856. else
  3857. if (pool->lp_url && pool->proto != pool->lp_proto)
  3858. wlogprint("Mixed");
  3859. else
  3860. switch (pool->proto) {
  3861. case PLP_GETBLOCKTEMPLATE:
  3862. wlogprint(" GBT ");
  3863. break;
  3864. case PLP_GETWORK:
  3865. wlogprint("GWork");
  3866. break;
  3867. default:
  3868. wlogprint("Alive");
  3869. }
  3870. wlogprint(" Priority %d: %s User:%s\n",
  3871. pool->prio,
  3872. pool->rpc_url, pool->rpc_user);
  3873. wattroff(logwin, A_BOLD | A_DIM);
  3874. }
  3875. retry:
  3876. wlogprint("\nCurrent pool management strategy: %s\n",
  3877. strategies[pool_strategy]);
  3878. if (pool_strategy == POOL_ROTATE)
  3879. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3880. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3881. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3882. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3883. wlogprint("Or press any other key to continue\n");
  3884. input = getch();
  3885. if (!strncasecmp(&input, "a", 1)) {
  3886. input_pool(true);
  3887. goto updated;
  3888. } else if (!strncasecmp(&input, "r", 1)) {
  3889. if (total_pools <= 1) {
  3890. wlogprint("Cannot remove last pool");
  3891. goto retry;
  3892. }
  3893. selected = curses_int("Select pool number");
  3894. if (selected < 0 || selected >= total_pools) {
  3895. wlogprint("Invalid selection\n");
  3896. goto retry;
  3897. }
  3898. pool = pools[selected];
  3899. if (pool == current_pool())
  3900. switch_pools(NULL);
  3901. if (pool == current_pool()) {
  3902. wlogprint("Unable to remove pool due to activity\n");
  3903. goto retry;
  3904. }
  3905. disable_pool(pool);
  3906. remove_pool(pool);
  3907. goto updated;
  3908. } else if (!strncasecmp(&input, "s", 1)) {
  3909. selected = curses_int("Select pool number");
  3910. if (selected < 0 || selected >= total_pools) {
  3911. wlogprint("Invalid selection\n");
  3912. goto retry;
  3913. }
  3914. pool = pools[selected];
  3915. enable_pool(pool);
  3916. switch_pools(pool);
  3917. goto updated;
  3918. } else if (!strncasecmp(&input, "d", 1)) {
  3919. if (enabled_pools <= 1) {
  3920. wlogprint("Cannot disable last pool");
  3921. goto retry;
  3922. }
  3923. selected = curses_int("Select pool number");
  3924. if (selected < 0 || selected >= total_pools) {
  3925. wlogprint("Invalid selection\n");
  3926. goto retry;
  3927. }
  3928. pool = pools[selected];
  3929. disable_pool(pool);
  3930. if (pool == current_pool())
  3931. switch_pools(NULL);
  3932. goto updated;
  3933. } else if (!strncasecmp(&input, "e", 1)) {
  3934. selected = curses_int("Select pool number");
  3935. if (selected < 0 || selected >= total_pools) {
  3936. wlogprint("Invalid selection\n");
  3937. goto retry;
  3938. }
  3939. pool = pools[selected];
  3940. enable_pool(pool);
  3941. if (pool->prio < current_pool()->prio)
  3942. switch_pools(pool);
  3943. goto updated;
  3944. } else if (!strncasecmp(&input, "c", 1)) {
  3945. for (i = 0; i <= TOP_STRATEGY; i++)
  3946. wlogprint("%d: %s\n", i, strategies[i]);
  3947. selected = curses_int("Select strategy number type");
  3948. if (selected < 0 || selected > TOP_STRATEGY) {
  3949. wlogprint("Invalid selection\n");
  3950. goto retry;
  3951. }
  3952. if (selected == POOL_ROTATE) {
  3953. opt_rotate_period = curses_int("Select interval in minutes");
  3954. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3955. opt_rotate_period = 0;
  3956. wlogprint("Invalid selection\n");
  3957. goto retry;
  3958. }
  3959. }
  3960. pool_strategy = selected;
  3961. switch_pools(NULL);
  3962. goto updated;
  3963. } else if (!strncasecmp(&input, "i", 1)) {
  3964. selected = curses_int("Select pool number");
  3965. if (selected < 0 || selected >= total_pools) {
  3966. wlogprint("Invalid selection\n");
  3967. goto retry;
  3968. }
  3969. pool = pools[selected];
  3970. display_pool_summary(pool);
  3971. goto retry;
  3972. } else if (!strncasecmp(&input, "f", 1)) {
  3973. opt_fail_only ^= true;
  3974. goto updated;
  3975. } else
  3976. clear_logwin();
  3977. immedok(logwin, false);
  3978. opt_loginput = false;
  3979. }
  3980. static void display_options(void)
  3981. {
  3982. int selected;
  3983. char input;
  3984. opt_loginput = true;
  3985. immedok(logwin, true);
  3986. clear_logwin();
  3987. retry:
  3988. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3989. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[W]orkTime details:%s\n[L]og interval:%d\n",
  3990. opt_debug_console ? "on" : "off",
  3991. want_per_device_stats? "on" : "off",
  3992. opt_quiet ? "on" : "off",
  3993. opt_log_output ? "on" : "off",
  3994. opt_protocol ? "on" : "off",
  3995. opt_worktime ? "on" : "off",
  3996. opt_log_interval);
  3997. wlogprint("Select an option or any other key to return\n");
  3998. input = getch();
  3999. if (!strncasecmp(&input, "q", 1)) {
  4000. opt_quiet ^= true;
  4001. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4002. goto retry;
  4003. } else if (!strncasecmp(&input, "v", 1)) {
  4004. opt_log_output ^= true;
  4005. if (opt_log_output)
  4006. opt_quiet = false;
  4007. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4008. goto retry;
  4009. } else if (!strncasecmp(&input, "n", 1)) {
  4010. opt_log_output = false;
  4011. opt_debug_console = false;
  4012. opt_quiet = false;
  4013. opt_protocol = false;
  4014. want_per_device_stats = false;
  4015. wlogprint("Output mode reset to normal\n");
  4016. goto retry;
  4017. } else if (!strncasecmp(&input, "d", 1)) {
  4018. opt_debug = true;
  4019. opt_debug_console ^= true;
  4020. opt_log_output = opt_debug_console;
  4021. if (opt_debug_console)
  4022. opt_quiet = false;
  4023. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  4024. goto retry;
  4025. } else if (!strncasecmp(&input, "p", 1)) {
  4026. want_per_device_stats ^= true;
  4027. opt_log_output = want_per_device_stats;
  4028. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4029. goto retry;
  4030. } else if (!strncasecmp(&input, "r", 1)) {
  4031. opt_protocol ^= true;
  4032. if (opt_protocol)
  4033. opt_quiet = false;
  4034. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4035. goto retry;
  4036. } else if (!strncasecmp(&input, "c", 1))
  4037. clear_logwin();
  4038. else if (!strncasecmp(&input, "l", 1)) {
  4039. selected = curses_int("Interval in seconds");
  4040. if (selected < 0 || selected > 9999) {
  4041. wlogprint("Invalid selection\n");
  4042. goto retry;
  4043. }
  4044. opt_log_interval = selected;
  4045. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4046. goto retry;
  4047. } else if (!strncasecmp(&input, "s", 1)) {
  4048. opt_realquiet = true;
  4049. } else if (!strncasecmp(&input, "w", 1)) {
  4050. opt_worktime ^= true;
  4051. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4052. goto retry;
  4053. } else
  4054. clear_logwin();
  4055. immedok(logwin, false);
  4056. opt_loginput = false;
  4057. }
  4058. #endif
  4059. void default_save_file(char *filename)
  4060. {
  4061. #if defined(unix)
  4062. if (getenv("HOME") && *getenv("HOME")) {
  4063. strcpy(filename, getenv("HOME"));
  4064. strcat(filename, "/");
  4065. }
  4066. else
  4067. strcpy(filename, "");
  4068. strcat(filename, ".bfgminer/");
  4069. mkdir(filename, 0777);
  4070. #else
  4071. strcpy(filename, "");
  4072. #endif
  4073. strcat(filename, def_conf);
  4074. }
  4075. #ifdef HAVE_CURSES
  4076. static void set_options(void)
  4077. {
  4078. int selected;
  4079. char input;
  4080. opt_loginput = true;
  4081. immedok(logwin, true);
  4082. clear_logwin();
  4083. retry:
  4084. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  4085. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  4086. "[W]rite config file\n[B]FGMiner restart\n",
  4087. opt_queue, opt_scantime, opt_expiry, opt_retries);
  4088. wlogprint("Select an option or any other key to return\n");
  4089. input = getch();
  4090. if (!strncasecmp(&input, "q", 1)) {
  4091. selected = curses_int("Extra work items to queue");
  4092. if (selected < 0 || selected > 9999) {
  4093. wlogprint("Invalid selection\n");
  4094. goto retry;
  4095. }
  4096. opt_queue = selected;
  4097. goto retry;
  4098. } else if (!strncasecmp(&input, "l", 1)) {
  4099. if (want_longpoll)
  4100. stop_longpoll();
  4101. else
  4102. start_longpoll();
  4103. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  4104. goto retry;
  4105. } else if (!strncasecmp(&input, "s", 1)) {
  4106. selected = curses_int("Set scantime in seconds");
  4107. if (selected < 0 || selected > 9999) {
  4108. wlogprint("Invalid selection\n");
  4109. goto retry;
  4110. }
  4111. opt_scantime = selected;
  4112. goto retry;
  4113. } else if (!strncasecmp(&input, "e", 1)) {
  4114. selected = curses_int("Set expiry time in seconds");
  4115. if (selected < 0 || selected > 9999) {
  4116. wlogprint("Invalid selection\n");
  4117. goto retry;
  4118. }
  4119. opt_expiry = selected;
  4120. goto retry;
  4121. } else if (!strncasecmp(&input, "r", 1)) {
  4122. selected = curses_int("Retries before failing (-1 infinite)");
  4123. if (selected < -1 || selected > 9999) {
  4124. wlogprint("Invalid selection\n");
  4125. goto retry;
  4126. }
  4127. opt_retries = selected;
  4128. goto retry;
  4129. } else if (!strncasecmp(&input, "w", 1)) {
  4130. FILE *fcfg;
  4131. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4132. default_save_file(filename);
  4133. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  4134. str = curses_input(prompt);
  4135. if (strcmp(str, "-1")) {
  4136. struct stat statbuf;
  4137. strcpy(filename, str);
  4138. if (!stat(filename, &statbuf)) {
  4139. wlogprint("File exists, overwrite?\n");
  4140. input = getch();
  4141. if (strncasecmp(&input, "y", 1))
  4142. goto retry;
  4143. }
  4144. }
  4145. fcfg = fopen(filename, "w");
  4146. if (!fcfg) {
  4147. wlogprint("Cannot open or create file\n");
  4148. goto retry;
  4149. }
  4150. write_config(fcfg);
  4151. fclose(fcfg);
  4152. goto retry;
  4153. } else if (!strncasecmp(&input, "b", 1)) {
  4154. wlogprint("Are you sure?\n");
  4155. input = getch();
  4156. if (!strncasecmp(&input, "y", 1))
  4157. app_restart();
  4158. else
  4159. clear_logwin();
  4160. } else
  4161. clear_logwin();
  4162. immedok(logwin, false);
  4163. opt_loginput = false;
  4164. }
  4165. static void *input_thread(void __maybe_unused *userdata)
  4166. {
  4167. rename_thr("bfg-input");
  4168. if (!curses_active)
  4169. return NULL;
  4170. while (1) {
  4171. int input;
  4172. input = getch();
  4173. switch (input) {
  4174. case 'q': case 'Q':
  4175. kill_work();
  4176. return NULL;
  4177. case 'd': case 'D':
  4178. display_options();
  4179. break;
  4180. case 'p': case 'P':
  4181. display_pools();
  4182. break;
  4183. case 's': case 'S':
  4184. set_options();
  4185. break;
  4186. case 'g': case 'G':
  4187. if (have_opencl)
  4188. manage_gpu();
  4189. break;
  4190. #ifdef HAVE_CURSES
  4191. case KEY_DOWN:
  4192. if (devsummaryYOffset < -(total_devices + devcursor - statusy))
  4193. break;
  4194. devsummaryYOffset -= 2;
  4195. case KEY_UP:
  4196. if (devsummaryYOffset == 0)
  4197. break;
  4198. ++devsummaryYOffset;
  4199. if (curses_active_locked()) {
  4200. int i;
  4201. for (i = 0; i < mining_threads; i++)
  4202. curses_print_devstatus(i);
  4203. touchwin(statuswin);
  4204. wrefresh(statuswin);
  4205. unlock_curses();
  4206. }
  4207. break;
  4208. #endif
  4209. }
  4210. if (opt_realquiet) {
  4211. disable_curses();
  4212. break;
  4213. }
  4214. }
  4215. return NULL;
  4216. }
  4217. #endif
  4218. /* This thread should not be shut down unless a problem occurs */
  4219. static void *workio_thread(void *userdata)
  4220. {
  4221. struct thr_info *mythr = userdata;
  4222. bool ok = true;
  4223. rename_thr("bfg-workio");
  4224. while (ok) {
  4225. struct workio_cmd *wc;
  4226. applog(LOG_DEBUG, "Popping work to work thread");
  4227. /* wait for workio_cmd sent to us, on our queue */
  4228. wc = tq_pop(mythr->q, NULL);
  4229. if (unlikely(!wc)) {
  4230. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  4231. ok = false;
  4232. break;
  4233. }
  4234. /* process workio_cmd */
  4235. switch (wc->cmd) {
  4236. case WC_GET_WORK:
  4237. ok = workio_get_work(wc);
  4238. break;
  4239. case WC_SUBMIT_WORK:
  4240. {
  4241. mutex_lock(&submitting_lock);
  4242. if (submitting >= opt_submit_threads) {
  4243. if (list_empty(&submit_waiting))
  4244. applog(LOG_WARNING, "workio_thread queuing submissions (see --submit-threads)");
  4245. else
  4246. applog(LOG_DEBUG, "workio_thread queuing submission");
  4247. list_add_tail(&wc->list, &submit_waiting);
  4248. mutex_unlock(&submitting_lock);
  4249. break;
  4250. }
  4251. ++submitting;
  4252. mutex_unlock(&submitting_lock);
  4253. ok = workio_submit_work(wc);
  4254. break;
  4255. }
  4256. default:
  4257. ok = false;
  4258. break;
  4259. }
  4260. }
  4261. tq_freeze(mythr->q);
  4262. return NULL;
  4263. }
  4264. static void *api_thread(void *userdata)
  4265. {
  4266. struct thr_info *mythr = userdata;
  4267. pthread_detach(pthread_self());
  4268. rename_thr("bfg-rpc");
  4269. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4270. api(api_thr_id);
  4271. PTH(mythr) = 0L;
  4272. return NULL;
  4273. }
  4274. void thread_reportin(struct thr_info *thr)
  4275. {
  4276. gettimeofday(&thr->last, NULL);
  4277. thr->cgpu->status = LIFE_WELL;
  4278. thr->getwork = 0;
  4279. thr->cgpu->device_last_well = time(NULL);
  4280. }
  4281. static inline void thread_reportout(struct thr_info *thr)
  4282. {
  4283. thr->getwork = time(NULL);
  4284. }
  4285. static void hashmeter(int thr_id, struct timeval *diff,
  4286. uint64_t hashes_done)
  4287. {
  4288. struct timeval temp_tv_end, total_diff;
  4289. double secs;
  4290. double local_secs;
  4291. double utility, efficiency = 0.0;
  4292. static double local_mhashes_done = 0;
  4293. static double rolling = 0;
  4294. double local_mhashes = (double)hashes_done / 1000000.0;
  4295. bool showlog = false;
  4296. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  4297. /* Update the last time this thread reported in */
  4298. if (thr_id >= 0) {
  4299. gettimeofday(&thr_info[thr_id].last, NULL);
  4300. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  4301. }
  4302. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4303. /* So we can call hashmeter from a non worker thread */
  4304. if (thr_id >= 0) {
  4305. struct thr_info *thr = &thr_info[thr_id];
  4306. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  4307. double thread_rolling = 0.0;
  4308. int i;
  4309. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  4310. thr_id, hashes_done, hashes_done / 1000 / secs);
  4311. /* Rolling average for each thread and each device */
  4312. decay_time(&thr->rolling, local_mhashes / secs);
  4313. for (i = 0; i < cgpu->threads; i++)
  4314. thread_rolling += cgpu->thr[i]->rolling;
  4315. mutex_lock(&hash_lock);
  4316. decay_time(&cgpu->rolling, thread_rolling);
  4317. cgpu->total_mhashes += local_mhashes;
  4318. mutex_unlock(&hash_lock);
  4319. // If needed, output detailed, per-device stats
  4320. if (want_per_device_stats) {
  4321. struct timeval now;
  4322. struct timeval elapsed;
  4323. gettimeofday(&now, NULL);
  4324. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  4325. if (opt_log_interval <= elapsed.tv_sec) {
  4326. struct cgpu_info *cgpu = thr->cgpu;
  4327. char logline[255];
  4328. cgpu->last_message_tv = now;
  4329. get_statline(logline, cgpu);
  4330. if (!curses_active) {
  4331. printf("%s \r", logline);
  4332. fflush(stdout);
  4333. } else
  4334. applog(LOG_INFO, "%s", logline);
  4335. }
  4336. }
  4337. }
  4338. /* Totals are updated by all threads so can race without locking */
  4339. mutex_lock(&hash_lock);
  4340. gettimeofday(&temp_tv_end, NULL);
  4341. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4342. total_mhashes_done += local_mhashes;
  4343. local_mhashes_done += local_mhashes;
  4344. if (total_diff.tv_sec < opt_log_interval)
  4345. /* Only update the total every opt_log_interval seconds */
  4346. goto out_unlock;
  4347. showlog = true;
  4348. gettimeofday(&total_tv_end, NULL);
  4349. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4350. decay_time(&rolling, local_mhashes_done / local_secs);
  4351. global_hashrate = roundl(rolling) * 1000000;
  4352. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4353. total_secs = (double)total_diff.tv_sec +
  4354. ((double)total_diff.tv_usec / 1000000.0);
  4355. utility = total_accepted / total_secs * 60;
  4356. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4357. ti_hashrate_bufstr(
  4358. (char*[]){cHr, aHr, uHr},
  4359. 1e6*rolling,
  4360. 1e6*total_mhashes_done / total_secs,
  4361. utility_to_hashrate(total_accepted_weighed / (total_secs ?: 1) * 60),
  4362. H2B_SPACED);
  4363. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  4364. want_per_device_stats ? "ALL " : "",
  4365. opt_log_interval,
  4366. cHr, aHr,
  4367. uHr,
  4368. total_accepted, total_rejected, hw_errors, efficiency, utility);
  4369. local_mhashes_done = 0;
  4370. out_unlock:
  4371. mutex_unlock(&hash_lock);
  4372. if (showlog) {
  4373. if (!curses_active) {
  4374. printf("%s \r", statusline);
  4375. fflush(stdout);
  4376. } else
  4377. applog(LOG_INFO, "%s", statusline);
  4378. }
  4379. }
  4380. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4381. struct stratum_share *sshare)
  4382. {
  4383. struct work *work = &sshare->work;
  4384. uint64_t sharediff = share_diff(work);
  4385. char hashshow[65];
  4386. uint32_t *hash32;
  4387. char diffdisp[16];
  4388. int intdiff;
  4389. hash32 = (uint32_t *)(work->hash);
  4390. intdiff = floor(work->work_difficulty);
  4391. suffix_string(sharediff, diffdisp, 0);
  4392. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)(hash32[6]), diffdisp, intdiff,
  4393. work->block? " BLOCK!" : "");
  4394. share_result(val, res_val, err_val, work, hashshow, false, "");
  4395. }
  4396. /* Parses stratum json responses and tries to find the id that the request
  4397. * matched to and treat it accordingly. */
  4398. static bool parse_stratum_response(char *s)
  4399. {
  4400. json_t *val = NULL, *err_val, *res_val, *id_val;
  4401. struct stratum_share *sshare;
  4402. json_error_t err;
  4403. bool ret = false;
  4404. int id;
  4405. val = JSON_LOADS(s, &err);
  4406. if (!val) {
  4407. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4408. goto out;
  4409. }
  4410. res_val = json_object_get(val, "result");
  4411. err_val = json_object_get(val, "error");
  4412. id_val = json_object_get(val, "id");
  4413. if (json_is_null(id_val) || !id_val) {
  4414. char *ss;
  4415. if (err_val)
  4416. ss = json_dumps(err_val, JSON_INDENT(3));
  4417. else
  4418. ss = strdup("(unknown reason)");
  4419. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4420. free(ss);
  4421. goto out;
  4422. }
  4423. id = json_integer_value(id_val);
  4424. mutex_lock(&sshare_lock);
  4425. HASH_FIND_INT(stratum_shares, &id, sshare);
  4426. if (sshare)
  4427. HASH_DEL(stratum_shares, sshare);
  4428. mutex_unlock(&sshare_lock);
  4429. if (!sshare) {
  4430. if (json_is_true(res_val))
  4431. applog(LOG_NOTICE, "Accepted untracked stratum share");
  4432. else
  4433. applog(LOG_NOTICE, "Rejected untracked stratum share");
  4434. goto out;
  4435. }
  4436. stratum_share_result(val, res_val, err_val, sshare);
  4437. free(sshare);
  4438. ret = true;
  4439. out:
  4440. if (val)
  4441. json_decref(val);
  4442. return ret;
  4443. }
  4444. static void shutdown_stratum(struct pool *pool)
  4445. {
  4446. // Shut down Stratum as if we never had it
  4447. pool->has_stratum = false;
  4448. shutdown(pool->sock, SHUT_RDWR);
  4449. free(pool->stratum_url);
  4450. if (pool->sockaddr_url == pool->stratum_url)
  4451. pool->sockaddr_url = NULL;
  4452. pool->stratum_url = NULL;
  4453. }
  4454. static void pool_resus(struct pool *pool);
  4455. static bool pool_active(struct pool *pool, bool pinging);
  4456. /* One stratum thread per pool that has stratum waits on the socket checking
  4457. * for new messages and for the integrity of the socket connection. We reset
  4458. * the connection based on the integrity of the receive side only as the send
  4459. * side will eventually expire data it fails to send. */
  4460. static void *stratum_thread(void *userdata)
  4461. {
  4462. struct pool *pool = (struct pool *)userdata;
  4463. pthread_detach(pthread_self());
  4464. while (42) {
  4465. struct timeval timeout;
  4466. fd_set rd;
  4467. char *s;
  4468. if (unlikely(!pool->has_stratum))
  4469. break;
  4470. FD_ZERO(&rd);
  4471. FD_SET(pool->sock, &rd);
  4472. timeout.tv_sec = 120;
  4473. timeout.tv_usec = 0;
  4474. /* The protocol specifies that notify messages should be sent
  4475. * every minute so if we fail to receive any for 2 minutes we
  4476. * assume the connection has been dropped and treat this pool
  4477. * as dead */
  4478. select(pool->sock + 1, &rd, NULL, NULL, &timeout);
  4479. s = recv_line(pool);
  4480. if (!s) {
  4481. if (!pool->has_stratum)
  4482. break;
  4483. applog(LOG_INFO, "Stratum connection to pool %d interrupted", pool->pool_no);
  4484. pool->getfail_occasions++;
  4485. total_go++;
  4486. if (initiate_stratum(pool) && auth_stratum(pool))
  4487. continue;
  4488. if (pool->rpc_url[0] != 's') {
  4489. shutdown_stratum(pool);
  4490. pool_active(pool, false);
  4491. break;
  4492. }
  4493. pool_died(pool);
  4494. while (!initiate_stratum(pool) || !auth_stratum(pool)) {
  4495. if (pool->removed)
  4496. goto out;
  4497. sleep(30);
  4498. }
  4499. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4500. pool_tclear(pool, &pool->idle);
  4501. pool_resus(pool);
  4502. continue;
  4503. }
  4504. if (!parse_method(pool, s) && !parse_stratum_response(s))
  4505. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4506. free(s);
  4507. if (pool->swork.clean) {
  4508. struct work work;
  4509. /* Generate a single work item to update the current
  4510. * block database */
  4511. pool->swork.clean = false;
  4512. gen_stratum_work(pool, &work);
  4513. if (test_work_current(&work)) {
  4514. /* Only accept a work restart if this stratum
  4515. * connection is from the current pool */
  4516. if (pool == current_pool()) {
  4517. restart_threads();
  4518. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4519. }
  4520. } else
  4521. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4522. }
  4523. }
  4524. out:
  4525. return NULL;
  4526. }
  4527. static void init_stratum_thread(struct pool *pool)
  4528. {
  4529. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  4530. quit(1, "Failed to create stratum thread");
  4531. }
  4532. static void *longpoll_thread(void *userdata);
  4533. static bool stratum_works(struct pool *pool)
  4534. {
  4535. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4536. if (!extract_sockaddr(pool, pool->stratum_url))
  4537. return false;
  4538. if (!initiate_stratum(pool))
  4539. return false;
  4540. return true;
  4541. }
  4542. // NOTE: This assumes reference URI is a root
  4543. static char *absolute_uri(char *uri, const char *ref)
  4544. {
  4545. if (strstr(uri, "://"))
  4546. return strdup(uri);
  4547. char *copy_start, *abs;
  4548. bool need_slash = false;
  4549. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  4550. if (ref[strlen(ref) - 1] != '/')
  4551. need_slash = true;
  4552. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  4553. if (!abs) {
  4554. applog(LOG_ERR, "Malloc failure in absolute_uri");
  4555. return NULL;
  4556. }
  4557. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  4558. return abs;
  4559. }
  4560. static bool pool_active(struct pool *pool, bool pinging)
  4561. {
  4562. struct timeval tv_getwork, tv_getwork_reply;
  4563. bool ret = false;
  4564. json_t *val;
  4565. CURL *curl;
  4566. int rolltime;
  4567. char *rpc_req;
  4568. struct work *work;
  4569. enum pool_protocol proto;
  4570. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4571. /* This is the central point we activate stratum when we can */
  4572. curl = curl_easy_init();
  4573. if (unlikely(!curl)) {
  4574. applog(LOG_ERR, "CURL initialisation failed");
  4575. return false;
  4576. }
  4577. work = make_work();
  4578. work->pool = pool;
  4579. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  4580. tryagain:
  4581. rpc_req = prepare_rpc_req(work, proto, NULL);
  4582. if (!rpc_req)
  4583. return false;
  4584. pool->probed = false;
  4585. gettimeofday(&tv_getwork, NULL);
  4586. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  4587. true, false, &rolltime, pool, false);
  4588. gettimeofday(&tv_getwork_reply, NULL);
  4589. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4590. * and if so, switch to that in preference to getwork if it works */
  4591. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  4592. curl_easy_cleanup(curl);
  4593. if (!pool->has_stratum) {
  4594. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4595. if (!pool->rpc_url)
  4596. pool->rpc_url = strdup(pool->stratum_url);
  4597. pool->has_stratum = true;
  4598. }
  4599. retry_stratum:
  4600. /* We create the stratum thread for each pool just after
  4601. * successful authorisation. Once the auth flag has been set
  4602. * we never unset it and the stratum thread is responsible for
  4603. * setting/unsetting the active flag */
  4604. if (pool->stratum_auth)
  4605. return pool->stratum_active;
  4606. if (!pool->stratum_active && !initiate_stratum(pool))
  4607. return false;
  4608. if (!auth_stratum(pool))
  4609. return false;
  4610. pool->idle = false;
  4611. pool->stratum_auth = true;
  4612. init_stratum_thread(pool);
  4613. return true;
  4614. }
  4615. else if (pool->has_stratum)
  4616. shutdown_stratum(pool);
  4617. if (val) {
  4618. bool rc;
  4619. json_t *res;
  4620. res = json_object_get(val, "result");
  4621. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  4622. goto badwork;
  4623. rc = work_decode(res, work);
  4624. if (rc) {
  4625. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4626. pool->pool_no, pool->rpc_url);
  4627. work->pool = pool;
  4628. work->rolltime = rolltime;
  4629. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  4630. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  4631. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4632. calc_diff(work, 0);
  4633. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4634. tq_push(thr_info[stage_thr_id].q, work);
  4635. total_getworks++;
  4636. pool->getwork_requested++;
  4637. ret = true;
  4638. gettimeofday(&pool->tv_idle, NULL);
  4639. } else {
  4640. badwork:
  4641. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4642. pool->pool_no, pool->rpc_url);
  4643. if (PLP_NONE != (proto = pool_protocol_fallback(proto)))
  4644. goto tryagain;
  4645. free_work(work);
  4646. goto out;
  4647. }
  4648. json_decref(val);
  4649. if (proto != pool->proto) {
  4650. pool->proto = proto;
  4651. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  4652. }
  4653. if (pool->lp_url)
  4654. goto out;
  4655. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4656. const struct blktmpl_longpoll_req *lp;
  4657. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  4658. // NOTE: work_decode takes care of lp id
  4659. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  4660. if (!pool->lp_url)
  4661. return false;
  4662. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  4663. }
  4664. else
  4665. if (pool->hdr_path) {
  4666. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  4667. if (!pool->lp_url)
  4668. return false;
  4669. pool->lp_proto = PLP_GETWORK;
  4670. } else
  4671. pool->lp_url = NULL;
  4672. if (want_longpoll && !pool->lp_started) {
  4673. pool->lp_started = true;
  4674. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4675. quit(1, "Failed to create pool longpoll thread");
  4676. }
  4677. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  4678. goto tryagain;
  4679. } else {
  4680. free_work(work);
  4681. /* If we failed to parse a getwork, this could be a stratum
  4682. * url without the prefix stratum+tcp:// so let's check it */
  4683. if (initiate_stratum(pool)) {
  4684. pool->has_stratum = true;
  4685. goto retry_stratum;
  4686. }
  4687. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4688. pool->pool_no, pool->rpc_url);
  4689. if (!pinging)
  4690. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4691. }
  4692. out:
  4693. curl_easy_cleanup(curl);
  4694. return ret;
  4695. }
  4696. static inline int cp_prio(void)
  4697. {
  4698. int prio;
  4699. mutex_lock(&control_lock);
  4700. prio = currentpool->prio;
  4701. mutex_unlock(&control_lock);
  4702. return prio;
  4703. }
  4704. static void pool_resus(struct pool *pool)
  4705. {
  4706. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4707. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  4708. switch_pools(NULL);
  4709. }
  4710. static bool queue_request(void)
  4711. {
  4712. int ts, tq, maxq = opt_queue + mining_threads;
  4713. struct pool *pool, *cp;
  4714. struct workio_cmd *wc;
  4715. bool lagging;
  4716. ts = total_staged();
  4717. tq = global_queued();
  4718. if (ts && ts + tq >= maxq)
  4719. return true;
  4720. cp = current_pool();
  4721. lagging = !opt_fail_only && cp->lagging && !ts && cp->queued >= maxq;
  4722. if (!lagging && cp->staged + cp->queued >= maxq)
  4723. return true;
  4724. pool = select_pool(lagging);
  4725. if (pool->staged + pool->queued >= maxq)
  4726. return true;
  4727. /* fill out work request message */
  4728. wc = calloc(1, sizeof(*wc));
  4729. if (unlikely(!wc)) {
  4730. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  4731. return false;
  4732. }
  4733. wc->cmd = WC_GET_WORK;
  4734. wc->pool = pool;
  4735. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  4736. /* send work request to workio thread */
  4737. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4738. applog(LOG_ERR, "Failed to tq_push in queue_request");
  4739. workio_cmd_free(wc);
  4740. return false;
  4741. }
  4742. inc_queued(pool);
  4743. return true;
  4744. }
  4745. static struct work *hash_pop(const struct timespec *abstime)
  4746. {
  4747. struct work *work = NULL, *tmp;
  4748. int rc = 0, hc;
  4749. mutex_lock(stgd_lock);
  4750. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  4751. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  4752. hc = HASH_COUNT(staged_work);
  4753. if (likely(hc)) {
  4754. /* Find clone work if possible, to allow masters to be reused */
  4755. if (hc > staged_rollable) {
  4756. HASH_ITER(hh, staged_work, work, tmp) {
  4757. if (!work_rollable(work))
  4758. break;
  4759. }
  4760. } else
  4761. work = staged_work;
  4762. HASH_DEL(staged_work, work);
  4763. work->pool->staged--;
  4764. if (work_rollable(work))
  4765. staged_rollable--;
  4766. }
  4767. mutex_unlock(stgd_lock);
  4768. queue_request();
  4769. return work;
  4770. }
  4771. static bool reuse_work(struct work *work, struct pool *pool)
  4772. {
  4773. if (pool->has_stratum) {
  4774. if (!pool->stratum_active)
  4775. return false;
  4776. applog(LOG_DEBUG, "Reusing stratum work");
  4777. gen_stratum_work(pool, work);;
  4778. return true;
  4779. }
  4780. if (can_roll(work) && should_roll(work)) {
  4781. roll_work(work);
  4782. return true;
  4783. }
  4784. return false;
  4785. }
  4786. /* Clones work by rolling it if possible, and returning a clone instead of the
  4787. * original work item which gets staged again to possibly be rolled again in
  4788. * the future */
  4789. static struct work *clone_work(struct work *work)
  4790. {
  4791. int mrs = mining_threads + opt_queue - total_staged();
  4792. struct work *work_clone;
  4793. bool cloned;
  4794. if (mrs < 1)
  4795. return work;
  4796. cloned = false;
  4797. work_clone = make_clone(work);
  4798. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4799. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4800. if (unlikely(!stage_work(work_clone))) {
  4801. cloned = false;
  4802. break;
  4803. }
  4804. roll_work(work);
  4805. work_clone = make_clone(work);
  4806. /* Roll it again to prevent duplicates should this be used
  4807. * directly later on */
  4808. roll_work(work);
  4809. cloned = true;
  4810. }
  4811. if (cloned) {
  4812. stage_work(work);
  4813. return work_clone;
  4814. }
  4815. free_work(work_clone);
  4816. return work;
  4817. }
  4818. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  4819. {
  4820. unsigned char hash1[36];
  4821. sha2(data, len, hash1, false);
  4822. sha2(hash1, 32, hash, false);
  4823. }
  4824. /* Diff 1 is a 256 bit unsigned integer of
  4825. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  4826. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  4827. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  4828. static void set_work_target(struct work *work, int diff)
  4829. {
  4830. unsigned char rtarget[36], target[36];
  4831. uint64_t *data64, h64;
  4832. h64 = diffone;
  4833. h64 /= (uint64_t)diff;
  4834. memset(rtarget, 0, 32);
  4835. data64 = (uint64_t *)(rtarget + 4);
  4836. *data64 = htobe64(h64);
  4837. swab256(target, rtarget);
  4838. if (opt_debug) {
  4839. char *htarget = bin2hex(target, 32);
  4840. applog(LOG_DEBUG, "Generated target %s", htarget);
  4841. free(htarget);
  4842. }
  4843. memcpy(work->target, target, 32);
  4844. }
  4845. /* Generates stratum based work based on the most recent notify information
  4846. * from the pool. This will keep generating work while a pool is down so we use
  4847. * other means to detect when the pool has died in stratum_thread */
  4848. static void gen_stratum_work(struct pool *pool, struct work *work)
  4849. {
  4850. unsigned char *coinbase, merkle_root[36], merkle_sha[68], *merkle_hash;
  4851. char header[260], hash1[132], *nonce2;
  4852. int len, cb1_len, n1_len, cb2_len, i;
  4853. uint32_t *data32, *swap32;
  4854. memset(work->job_id, 0, 64);
  4855. memset(work->nonce2, 0, 64);
  4856. memset(work->ntime, 0, 16);
  4857. mutex_lock(&pool->pool_lock);
  4858. /* Generate coinbase */
  4859. nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  4860. pool->nonce2++;
  4861. cb1_len = strlen(pool->swork.coinbase1) / 2;
  4862. n1_len = strlen(pool->nonce1) / 2;
  4863. cb2_len = strlen(pool->swork.coinbase2) / 2;
  4864. len = cb1_len + n1_len + pool->n2size + cb2_len;
  4865. coinbase = alloca(len + 1);
  4866. hex2bin(coinbase, pool->swork.coinbase1, cb1_len);
  4867. hex2bin(coinbase + cb1_len, pool->nonce1, n1_len);
  4868. hex2bin(coinbase + cb1_len + n1_len, nonce2, pool->n2size);
  4869. hex2bin(coinbase + cb1_len + n1_len + pool->n2size, pool->swork.coinbase2, cb2_len);
  4870. /* Generate merkle root */
  4871. gen_hash(coinbase, merkle_root, len);
  4872. memcpy(merkle_sha, merkle_root, 32);
  4873. for (i = 0; i < pool->swork.merkles; i++) {
  4874. unsigned char merkle_bin[36];
  4875. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  4876. memcpy(merkle_sha + 32, merkle_bin, 32);
  4877. gen_hash(merkle_sha, merkle_root, 64);
  4878. memcpy(merkle_sha, merkle_root, 32);
  4879. }
  4880. data32 = (uint32_t *)merkle_sha;
  4881. swap32 = (uint32_t *)merkle_root;
  4882. for (i = 0; i < 32 / 4; i++)
  4883. swap32[i] = swab32(data32[i]);
  4884. merkle_hash = (unsigned char *)bin2hex((const unsigned char *)merkle_root, 32);
  4885. sprintf(header, "%s", pool->swork.bbversion);
  4886. strcat(header, pool->swork.prev_hash);
  4887. strcat(header, (char *)merkle_hash);
  4888. strcat(header, pool->swork.ntime);
  4889. strcat(header, pool->swork.nbit);
  4890. strcat(header, "00000000"); /* nonce */
  4891. strcat(header, "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000");
  4892. /* Store the stratum work diff to check it still matches the pool's
  4893. * stratum diff when submitting shares */
  4894. work->sdiff = pool->swork.diff;
  4895. /* Copy parameters required for share submission */
  4896. sprintf(work->job_id, "%s", pool->swork.job_id);
  4897. sprintf(work->nonce2, "%s", nonce2);
  4898. sprintf(work->ntime, "%s", pool->swork.ntime);
  4899. free(nonce2);
  4900. mutex_unlock(&pool->pool_lock);
  4901. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  4902. applog(LOG_DEBUG, "Generated stratum header %s", header);
  4903. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  4904. free(merkle_hash);
  4905. /* Convert hex data to binary data for work */
  4906. if (unlikely(!hex2bin(work->data, header, 128)))
  4907. quit(1, "Failed to convert header to data in gen_stratum_work");
  4908. calc_midstate(work);
  4909. sprintf(hash1, "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000");
  4910. if (unlikely(!hex2bin(work->hash1, hash1, 64)))
  4911. quit(1, "Failed to convert hash1 in gen_stratum_work");
  4912. set_work_target(work, work->sdiff);
  4913. local_work++;
  4914. work->pool = pool;
  4915. work->stratum = true;
  4916. work->blk.nonce = 0;
  4917. work->id = total_work++;
  4918. work->longpoll = false;
  4919. work->getwork_mode = GETWORK_MODE_STRATUM;
  4920. work->work_restart_id = work->pool->work_restart_id;
  4921. calc_diff(work, work->sdiff);
  4922. gettimeofday(&work->tv_staged, NULL);
  4923. }
  4924. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  4925. {
  4926. struct timespec abstime = {0, 0};
  4927. struct work *work_heap;
  4928. struct timeval now;
  4929. struct pool *pool;
  4930. /* Tell the watchdog thread this thread is waiting on getwork and
  4931. * should not be restarted */
  4932. thread_reportout(thr);
  4933. if (opt_benchmark) {
  4934. get_benchmark_work(work);
  4935. goto out;
  4936. }
  4937. retry:
  4938. pool = current_pool();
  4939. if (reuse_work(work, pool))
  4940. goto out;
  4941. /* If we were unable to reuse work from a stratum pool, it implies the
  4942. * pool is inactive and unless we have another pool to grab work from
  4943. * we can only wait till it comes alive or another pool comes online */
  4944. if (pool->has_stratum) {
  4945. sleep(5);
  4946. goto retry;
  4947. }
  4948. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  4949. struct cgpu_info *cgpu = thr->cgpu;
  4950. bool stalled = true;
  4951. int i;
  4952. /* Check to see if all the threads on the device that called
  4953. * get_work are waiting on work and only consider the pool
  4954. * lagging if true */
  4955. for (i = 0; i < cgpu->threads; i++) {
  4956. if (!cgpu->thr[i]->getwork) {
  4957. stalled = false;
  4958. break;
  4959. }
  4960. }
  4961. if (stalled && !pool_tset(pool, &pool->lagging)) {
  4962. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  4963. pool->getfail_occasions++;
  4964. total_go++;
  4965. }
  4966. }
  4967. gettimeofday(&now, NULL);
  4968. abstime.tv_sec = now.tv_sec + 60;
  4969. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4970. keepwaiting:
  4971. /* wait for 1st response, or get cached response */
  4972. work_heap = hash_pop(&abstime);
  4973. if (unlikely(!work_heap)) {
  4974. /* Attempt to switch pools if this one times out */
  4975. pool_died(pool);
  4976. if (pool == current_pool())
  4977. goto keepwaiting;
  4978. goto retry;
  4979. }
  4980. if (stale_work(work_heap, false)) {
  4981. discard_work(work_heap);
  4982. goto retry;
  4983. }
  4984. pool = work_heap->pool;
  4985. /* If we make it here we have succeeded in getting fresh work */
  4986. if (!work_heap->mined) {
  4987. /* Only clear the lagging flag if we are staging them at a
  4988. * rate faster then we're using them */
  4989. if (pool->lagging && total_staged())
  4990. pool_tclear(pool, &pool->lagging);
  4991. if (pool_tclear(pool, &pool->idle))
  4992. pool_resus(pool);
  4993. }
  4994. memcpy(work, work_heap, sizeof(struct work));
  4995. free(work_heap);
  4996. out:
  4997. work->thr_id = thr_id;
  4998. thread_reportin(thr);
  4999. work->mined = true;
  5000. }
  5001. bool submit_work_sync(struct thr_info *thr, const struct work *work_in, struct timeval *tv_work_found)
  5002. {
  5003. struct workio_cmd *wc;
  5004. /* fill out work request message */
  5005. wc = calloc(1, sizeof(*wc));
  5006. if (unlikely(!wc)) {
  5007. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  5008. return false;
  5009. }
  5010. wc->work = make_work();
  5011. wc->cmd = WC_SUBMIT_WORK;
  5012. wc->thr = thr;
  5013. workcpy(wc->work, work_in);
  5014. if (tv_work_found)
  5015. memcpy(&(wc->work->tv_work_found), tv_work_found, sizeof(struct timeval));
  5016. applog(LOG_DEBUG, "Pushing submit work to work thread");
  5017. /* send solution to workio thread */
  5018. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  5019. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  5020. goto err_out;
  5021. }
  5022. return true;
  5023. err_out:
  5024. workio_cmd_free(wc);
  5025. return false;
  5026. }
  5027. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  5028. {
  5029. uint32_t *data32 = (uint32_t *)(work->data);
  5030. unsigned char swap[128];
  5031. uint32_t *swap32 = (uint32_t *)swap;
  5032. unsigned char hash1[32];
  5033. unsigned char hash2[32];
  5034. uint32_t *hash2_32 = (uint32_t *)hash2;
  5035. struct pool *pool = work->pool;
  5036. int diff;
  5037. swap32yes(swap32, data32, 80 / 4);
  5038. sha2(swap, 80, hash1, false);
  5039. sha2(hash1, 32, hash2, false);
  5040. if (hash2_32[7] != 0)
  5041. return TNR_BAD;
  5042. if (!checktarget)
  5043. return TNR_GOOD;
  5044. swap32yes(hash2_32, hash2_32, 32 / 4);
  5045. memcpy((void*)work->hash, hash2, 32);
  5046. if (work->stratum) {
  5047. mutex_lock(&pool->pool_lock);
  5048. diff = pool->swork.diff;
  5049. mutex_unlock(&pool->pool_lock);
  5050. if (unlikely(work->sdiff != diff)) {
  5051. applog(LOG_DEBUG, "Share needs retargetting to match pool");
  5052. set_work_target(work, diff);
  5053. }
  5054. }
  5055. if (!fulltest(work->hash, work->target))
  5056. return TNR_HIGH;
  5057. return TNR_GOOD;
  5058. }
  5059. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  5060. {
  5061. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5062. *work_nonce = nonce;
  5063. #ifdef USE_SCRYPT
  5064. if (opt_scrypt) {
  5065. if (!scrypt_test(work->data, work->target, nonce))
  5066. return TNR_BAD;
  5067. return TNR_GOOD;
  5068. }
  5069. #endif
  5070. return hashtest2(work, checktarget);
  5071. }
  5072. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  5073. {
  5074. struct timeval tv_work_found;
  5075. gettimeofday(&tv_work_found, NULL);
  5076. total_diff1++;
  5077. thr->cgpu->diff1++;
  5078. work->pool->diff1++;
  5079. /* Do one last check before attempting to submit the work */
  5080. /* Side effect: sets work->data for us */
  5081. switch (test_nonce2(work, nonce)) {
  5082. case TNR_BAD:
  5083. {
  5084. struct cgpu_info *cgpu = thr->cgpu;
  5085. applog(LOG_WARNING, "%s %u: invalid nonce - HW error",
  5086. cgpu->api->name, cgpu->device_id);
  5087. ++hw_errors;
  5088. ++thr->cgpu->hw_errors;
  5089. if (thr->cgpu->api->hw_error)
  5090. thr->cgpu->api->hw_error(thr);
  5091. return false;
  5092. }
  5093. case TNR_HIGH:
  5094. // Share above target, normal
  5095. return true;
  5096. case TNR_GOOD:
  5097. break;
  5098. }
  5099. return submit_work_sync(thr, work, &tv_work_found);
  5100. }
  5101. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  5102. {
  5103. if (wdiff->tv_sec > opt_scantime ||
  5104. work->blk.nonce >= MAXTHREADS - hashes ||
  5105. hashes >= 0xfffffffe ||
  5106. stale_work(work, false))
  5107. return true;
  5108. return false;
  5109. }
  5110. static void mt_disable(struct thr_info *mythr, const int thr_id,
  5111. const struct device_api *api)
  5112. {
  5113. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  5114. mythr->rolling = mythr->cgpu->rolling = 0;
  5115. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  5116. thread_reportout(mythr);
  5117. do {
  5118. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  5119. } while (mythr->pause);
  5120. thread_reportin(mythr);
  5121. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  5122. if (api->thread_enable)
  5123. api->thread_enable(mythr);
  5124. }
  5125. void *miner_thread(void *userdata)
  5126. {
  5127. struct thr_info *mythr = userdata;
  5128. const int thr_id = mythr->id;
  5129. struct cgpu_info *cgpu = mythr->cgpu;
  5130. const struct device_api *api = cgpu->api;
  5131. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5132. struct cgminer_stats *pool_stats;
  5133. struct timeval getwork_start;
  5134. {
  5135. char thrname[16];
  5136. sprintf(thrname, "bfg-miner-%s%d", api->name, cgpu->device_id);
  5137. rename_thr(thrname);
  5138. }
  5139. /* Try to cycle approximately 5 times before each log update */
  5140. const long cycle = opt_log_interval / 5 ? : 1;
  5141. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  5142. struct timeval diff, sdiff, wdiff = {0, 0};
  5143. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  5144. int64_t hashes_done = 0;
  5145. int64_t hashes;
  5146. bool scanhash_working = true;
  5147. struct work *work = make_work();
  5148. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  5149. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5150. gettimeofday(&getwork_start, NULL);
  5151. if (api->thread_init && !api->thread_init(mythr)) {
  5152. cgpu->device_last_not_well = time(NULL);
  5153. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  5154. cgpu->thread_fail_init_count++;
  5155. goto out;
  5156. }
  5157. thread_reportout(mythr);
  5158. applog(LOG_DEBUG, "Popping ping in miner thread");
  5159. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5160. sdiff.tv_sec = sdiff.tv_usec = 0;
  5161. gettimeofday(&tv_lastupdate, NULL);
  5162. while (1) {
  5163. mythr->work_restart = false;
  5164. if (api->free_work && likely(work->pool))
  5165. api->free_work(mythr, work);
  5166. get_work(work, mythr, thr_id);
  5167. cgpu->new_work = true;
  5168. gettimeofday(&tv_workstart, NULL);
  5169. work->blk.nonce = 0;
  5170. cgpu->max_hashes = 0;
  5171. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  5172. applog(LOG_ERR, "work prepare failed, exiting "
  5173. "mining thread %d", thr_id);
  5174. break;
  5175. }
  5176. do {
  5177. gettimeofday(&tv_start, NULL);
  5178. timersub(&tv_start, &getwork_start, &getwork_start);
  5179. timeradd(&getwork_start,
  5180. &(dev_stats->getwork_wait),
  5181. &(dev_stats->getwork_wait));
  5182. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  5183. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  5184. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  5185. }
  5186. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  5187. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  5188. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  5189. }
  5190. dev_stats->getwork_calls++;
  5191. pool_stats = &(work->pool->cgminer_stats);
  5192. timeradd(&getwork_start,
  5193. &(pool_stats->getwork_wait),
  5194. &(pool_stats->getwork_wait));
  5195. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  5196. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  5197. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  5198. }
  5199. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  5200. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  5201. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  5202. }
  5203. pool_stats->getwork_calls++;
  5204. gettimeofday(&(work->tv_work_start), NULL);
  5205. thread_reportin(mythr);
  5206. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  5207. thread_reportin(mythr);
  5208. gettimeofday(&getwork_start, NULL);
  5209. if (unlikely(hashes == -1)) {
  5210. time_t now = time(NULL);
  5211. if (difftime(now, cgpu->device_last_not_well) > 1.) {
  5212. cgpu->device_last_not_well = time(NULL);
  5213. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  5214. cgpu->thread_zero_hash_count++;
  5215. }
  5216. if (scanhash_working && opt_restart) {
  5217. applog(LOG_ERR, "%s %u failure, attempting to reinitialize", api->name, cgpu->device_id);
  5218. scanhash_working = false;
  5219. cgpu->reinit_backoff = 5.2734375;
  5220. hashes = 0;
  5221. } else {
  5222. applog(LOG_ERR, "%s %u failure, disabling!", api->name, cgpu->device_id);
  5223. cgpu->deven = DEV_RECOVER_ERR;
  5224. goto disabled;
  5225. }
  5226. }
  5227. else
  5228. scanhash_working = true;
  5229. hashes_done += hashes;
  5230. if (hashes > cgpu->max_hashes)
  5231. cgpu->max_hashes = hashes;
  5232. gettimeofday(&tv_end, NULL);
  5233. timersub(&tv_end, &tv_start, &diff);
  5234. sdiff.tv_sec += diff.tv_sec;
  5235. sdiff.tv_usec += diff.tv_usec;
  5236. if (sdiff.tv_usec > 1000000) {
  5237. ++sdiff.tv_sec;
  5238. sdiff.tv_usec -= 1000000;
  5239. }
  5240. timersub(&tv_end, &tv_workstart, &wdiff);
  5241. if (unlikely((long)sdiff.tv_sec < cycle)) {
  5242. int mult;
  5243. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  5244. continue;
  5245. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  5246. mult *= cycle;
  5247. if (max_nonce > (0xffffffff * 0x400) / mult)
  5248. max_nonce = 0xffffffff;
  5249. else
  5250. max_nonce = (max_nonce * mult) / 0x400;
  5251. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  5252. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  5253. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  5254. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  5255. timersub(&tv_end, &tv_lastupdate, &diff);
  5256. if (diff.tv_sec >= opt_log_interval) {
  5257. hashmeter(thr_id, &diff, hashes_done);
  5258. hashes_done = 0;
  5259. tv_lastupdate = tv_end;
  5260. }
  5261. if (unlikely(mythr->work_restart)) {
  5262. /* Apart from device_thread 0, we stagger the
  5263. * starting of every next thread to try and get
  5264. * all devices busy before worrying about
  5265. * getting work for their extra threads */
  5266. if (!primary) {
  5267. struct timespec rgtp;
  5268. rgtp.tv_sec = 0;
  5269. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  5270. nanosleep(&rgtp, NULL);
  5271. }
  5272. break;
  5273. }
  5274. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5275. disabled:
  5276. mt_disable(mythr, thr_id, api);
  5277. sdiff.tv_sec = sdiff.tv_usec = 0;
  5278. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  5279. }
  5280. out:
  5281. if (api->thread_shutdown)
  5282. api->thread_shutdown(mythr);
  5283. thread_reportin(mythr);
  5284. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5285. tq_freeze(mythr->q);
  5286. return NULL;
  5287. }
  5288. enum {
  5289. STAT_SLEEP_INTERVAL = 1,
  5290. STAT_CTR_INTERVAL = 10000000,
  5291. FAILURE_INTERVAL = 30,
  5292. };
  5293. /* Stage another work item from the work returned in a longpoll */
  5294. 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)
  5295. {
  5296. bool rc;
  5297. rc = work_decode(json_object_get(val, "result"), work);
  5298. if (unlikely(!rc)) {
  5299. applog(LOG_ERR, "Could not convert longpoll data to work");
  5300. free_work(work);
  5301. return;
  5302. }
  5303. work->pool = pool;
  5304. work->rolltime = rolltime;
  5305. work->longpoll = true;
  5306. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  5307. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  5308. work->getwork_mode = GETWORK_MODE_LP;
  5309. calc_diff(work, 0);
  5310. if (pool->enabled == POOL_REJECTING)
  5311. work->mandatory = true;
  5312. /* We'll be checking this work item twice, but we already know it's
  5313. * from a new block so explicitly force the new block detection now
  5314. * rather than waiting for it to hit the stage thread. This also
  5315. * allows testwork to know whether LP discovered the block or not. */
  5316. test_work_current(work);
  5317. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5318. * the longpoll work from a pool that has been rejecting shares as a
  5319. * way to detect when the pool has recovered.
  5320. */
  5321. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5322. free_work(work);
  5323. return;
  5324. }
  5325. work = clone_work(work);
  5326. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5327. if (unlikely(!stage_work(work)))
  5328. free_work(work);
  5329. else
  5330. applog(LOG_DEBUG, "Converted longpoll data to work");
  5331. }
  5332. /* If we want longpoll, enable it for the chosen default pool, or, if
  5333. * the pool does not support longpoll, find the first one that does
  5334. * and use its longpoll support */
  5335. static struct pool *select_longpoll_pool(struct pool *cp)
  5336. {
  5337. int i;
  5338. if (cp->lp_url)
  5339. return cp;
  5340. for (i = 0; i < total_pools; i++) {
  5341. struct pool *pool = pools[i];
  5342. if (pool->lp_url)
  5343. return pool;
  5344. }
  5345. return NULL;
  5346. }
  5347. /* This will make the longpoll thread wait till it's the current pool, or it
  5348. * has been flagged as rejecting, before attempting to open any connections.
  5349. */
  5350. static void wait_lpcurrent(struct pool *pool)
  5351. {
  5352. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  5353. return;
  5354. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5355. mutex_lock(&lp_lock);
  5356. pthread_cond_wait(&lp_cond, &lp_lock);
  5357. mutex_unlock(&lp_lock);
  5358. }
  5359. }
  5360. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  5361. struct pool *pool = vpool;
  5362. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  5363. pool->lp_socket = sock;
  5364. return sock;
  5365. }
  5366. static void *longpoll_thread(void *userdata)
  5367. {
  5368. struct pool *cp = (struct pool *)userdata;
  5369. /* This *pool is the source of the actual longpoll, not the pool we've
  5370. * tied it to */
  5371. struct pool *pool = NULL;
  5372. struct timeval start, reply, end;
  5373. CURL *curl = NULL;
  5374. int failures = 0;
  5375. int rolltime;
  5376. rename_thr("bfg-longpoll");
  5377. curl = curl_easy_init();
  5378. if (unlikely(!curl)) {
  5379. applog(LOG_ERR, "CURL initialisation failed");
  5380. goto out;
  5381. }
  5382. retry_pool:
  5383. pool = select_longpoll_pool(cp);
  5384. if (!pool) {
  5385. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  5386. while (!pool) {
  5387. sleep(60);
  5388. pool = select_longpoll_pool(cp);
  5389. }
  5390. }
  5391. /* Any longpoll from any pool is enough for this to be true */
  5392. have_longpoll = true;
  5393. wait_lpcurrent(cp);
  5394. if (cp == pool)
  5395. applog(LOG_WARNING, "Long-polling activated via %s (%s)", pool->lp_url, pool_protocol_name(pool->lp_proto));
  5396. else
  5397. applog(LOG_WARNING, "Long-polling activated for pool %s via %s (%s)", cp->rpc_url, pool->lp_url, pool_protocol_name(pool->lp_proto));
  5398. while (42) {
  5399. json_t *val, *soval;
  5400. struct work *work = make_work();
  5401. work->pool = pool;
  5402. const char *rpc_req;
  5403. rpc_req = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  5404. if (!rpc_req)
  5405. goto lpfail;
  5406. wait_lpcurrent(cp);
  5407. gettimeofday(&start, NULL);
  5408. /* Longpoll connections can be persistent for a very long time
  5409. * and any number of issues could have come up in the meantime
  5410. * so always establish a fresh connection instead of relying on
  5411. * a persistent one. */
  5412. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5413. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  5414. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  5415. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  5416. false, true, &rolltime, pool, false);
  5417. pool->lp_socket = CURL_SOCKET_BAD;
  5418. gettimeofday(&reply, NULL);
  5419. if (likely(val)) {
  5420. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5421. if (soval)
  5422. pool->submit_old = json_is_true(soval);
  5423. else
  5424. pool->submit_old = false;
  5425. convert_to_work(val, rolltime, pool, work, &start, &reply);
  5426. failures = 0;
  5427. json_decref(val);
  5428. } else {
  5429. /* Some pools regularly drop the longpoll request so
  5430. * only see this as longpoll failure if it happens
  5431. * immediately and just restart it the rest of the
  5432. * time. */
  5433. gettimeofday(&end, NULL);
  5434. free_work(work);
  5435. if (end.tv_sec - start.tv_sec > 30)
  5436. continue;
  5437. if (failures == 1)
  5438. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  5439. lpfail:
  5440. sleep(30);
  5441. }
  5442. if (pool != cp) {
  5443. pool = select_longpoll_pool(cp);
  5444. if (unlikely(!pool))
  5445. goto retry_pool;
  5446. }
  5447. if (unlikely(pool->removed))
  5448. break;
  5449. }
  5450. out:
  5451. if (curl)
  5452. curl_easy_cleanup(curl);
  5453. return NULL;
  5454. }
  5455. static void stop_longpoll(void)
  5456. {
  5457. int i;
  5458. want_longpoll = false;
  5459. for (i = 0; i < total_pools; ++i)
  5460. {
  5461. struct pool *pool = pools[i];
  5462. if (unlikely(!pool->lp_started))
  5463. continue;
  5464. pool->lp_started = false;
  5465. pthread_cancel(pool->longpoll_thread);
  5466. }
  5467. have_longpoll = false;
  5468. }
  5469. static void start_longpoll(void)
  5470. {
  5471. int i;
  5472. want_longpoll = true;
  5473. for (i = 0; i < total_pools; ++i)
  5474. {
  5475. struct pool *pool = pools[i];
  5476. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  5477. continue;
  5478. pool->lp_started = true;
  5479. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5480. quit(1, "Failed to create pool longpoll thread");
  5481. }
  5482. }
  5483. void reinit_device(struct cgpu_info *cgpu)
  5484. {
  5485. if (cgpu->api->reinit_device)
  5486. cgpu->api->reinit_device(cgpu);
  5487. }
  5488. static struct timeval rotate_tv;
  5489. /* We reap curls if they are unused for over a minute */
  5490. static void reap_curl(struct pool *pool)
  5491. {
  5492. struct curl_ent *ent, *iter;
  5493. struct timeval now;
  5494. int reaped = 0;
  5495. gettimeofday(&now, NULL);
  5496. mutex_lock(&pool->pool_lock);
  5497. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5498. if (pool->curls < 2)
  5499. break;
  5500. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5501. reaped++;
  5502. pool->curls--;
  5503. list_del(&ent->node);
  5504. curl_easy_cleanup(ent->curl);
  5505. free(ent);
  5506. }
  5507. }
  5508. mutex_unlock(&pool->pool_lock);
  5509. if (reaped)
  5510. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5511. }
  5512. static void *watchpool_thread(void __maybe_unused *userdata)
  5513. {
  5514. int intervals = 0;
  5515. rename_thr("bfg-watchpool");
  5516. while (42) {
  5517. struct timeval now;
  5518. int i;
  5519. if (++intervals > 20)
  5520. intervals = 0;
  5521. gettimeofday(&now, NULL);
  5522. for (i = 0; i < total_pools; i++) {
  5523. struct pool *pool = pools[i];
  5524. if (!opt_benchmark)
  5525. reap_curl(pool);
  5526. if (pool->enabled == POOL_DISABLED || pool->has_stratum)
  5527. continue;
  5528. /* Test pool is idle once every minute */
  5529. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  5530. gettimeofday(&pool->tv_idle, NULL);
  5531. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5532. pool_resus(pool);
  5533. }
  5534. /* Get a rolling utility per pool over 10 mins */
  5535. if (intervals > 19) {
  5536. int shares = pool->diff1 - pool->last_shares;
  5537. pool->last_shares = pool->diff1;
  5538. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5539. pool->shares = pool->utility;
  5540. }
  5541. }
  5542. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5543. gettimeofday(&rotate_tv, NULL);
  5544. switch_pools(NULL);
  5545. }
  5546. sleep(30);
  5547. }
  5548. return NULL;
  5549. }
  5550. void device_recovered(struct cgpu_info *cgpu)
  5551. {
  5552. struct thr_info *thr;
  5553. int j;
  5554. cgpu->deven = DEV_ENABLED;
  5555. for (j = 0; j < cgpu->threads; ++j) {
  5556. thr = cgpu->thr[j];
  5557. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5558. tq_push(thr->q, &ping);
  5559. }
  5560. }
  5561. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5562. * the screen at regular intervals, and restarts threads if they appear to have
  5563. * died. */
  5564. #define WATCHDOG_INTERVAL 3
  5565. #define WATCHDOG_SICK_TIME 60
  5566. #define WATCHDOG_DEAD_TIME 600
  5567. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5568. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5569. static void *watchdog_thread(void __maybe_unused *userdata)
  5570. {
  5571. const unsigned int interval = WATCHDOG_INTERVAL;
  5572. struct timeval zero_tv;
  5573. rename_thr("bfg-watchdog");
  5574. memset(&zero_tv, 0, sizeof(struct timeval));
  5575. gettimeofday(&rotate_tv, NULL);
  5576. while (1) {
  5577. int i;
  5578. struct timeval now;
  5579. sleep(interval);
  5580. discard_stale();
  5581. hashmeter(-1, &zero_tv, 0);
  5582. #ifdef HAVE_CURSES
  5583. if (curses_active_locked()) {
  5584. change_logwinsize();
  5585. curses_print_status();
  5586. for (i = 0; i < mining_threads; i++)
  5587. curses_print_devstatus(i);
  5588. touchwin(statuswin);
  5589. wrefresh(statuswin);
  5590. touchwin(logwin);
  5591. wrefresh(logwin);
  5592. unlock_curses();
  5593. }
  5594. #endif
  5595. gettimeofday(&now, NULL);
  5596. if (!sched_paused && !should_run()) {
  5597. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5598. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5599. if (!schedstart.enable) {
  5600. quit(0, "Terminating execution as planned");
  5601. break;
  5602. }
  5603. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5604. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5605. sched_paused = true;
  5606. for (i = 0; i < mining_threads; i++) {
  5607. struct thr_info *thr;
  5608. thr = &thr_info[i];
  5609. thr->pause = true;
  5610. }
  5611. } else if (sched_paused && should_run()) {
  5612. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5613. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5614. if (schedstop.enable)
  5615. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5616. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5617. sched_paused = false;
  5618. for (i = 0; i < mining_threads; i++) {
  5619. struct thr_info *thr;
  5620. thr = &thr_info[i];
  5621. /* Don't touch disabled devices */
  5622. if (thr->cgpu->deven == DEV_DISABLED)
  5623. continue;
  5624. thr->pause = false;
  5625. tq_push(thr->q, &ping);
  5626. }
  5627. }
  5628. for (i = 0; i < total_devices; ++i) {
  5629. struct cgpu_info *cgpu = devices[i];
  5630. struct thr_info *thr = cgpu->thr[0];
  5631. enum dev_enable *denable;
  5632. char dev_str[8];
  5633. int gpu;
  5634. if (cgpu->api->get_stats)
  5635. cgpu->api->get_stats(cgpu);
  5636. gpu = cgpu->device_id;
  5637. denable = &cgpu->deven;
  5638. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  5639. #ifdef HAVE_ADL
  5640. if (adl_active && cgpu->has_adl)
  5641. gpu_autotune(gpu, denable);
  5642. if (opt_debug && cgpu->has_adl) {
  5643. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5644. float temp = 0, vddc = 0;
  5645. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5646. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5647. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5648. }
  5649. #endif
  5650. /* Thread is disabled */
  5651. if (*denable == DEV_DISABLED)
  5652. continue;
  5653. else
  5654. if (*denable == DEV_RECOVER_ERR) {
  5655. if (opt_restart && difftime(time(NULL), cgpu->device_last_not_well) > cgpu->reinit_backoff) {
  5656. applog(LOG_NOTICE, "Attempting to reinitialize %s %u",
  5657. cgpu->api->name, cgpu->device_id);
  5658. if (cgpu->reinit_backoff < 300)
  5659. cgpu->reinit_backoff *= 2;
  5660. device_recovered(cgpu);
  5661. }
  5662. continue;
  5663. }
  5664. else
  5665. if (*denable == DEV_RECOVER) {
  5666. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  5667. applog(LOG_NOTICE, "%s %u recovered to temperature below target, re-enabling",
  5668. cgpu->api->name, cgpu->device_id);
  5669. device_recovered(cgpu);
  5670. }
  5671. cgpu->device_last_not_well = time(NULL);
  5672. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5673. continue;
  5674. }
  5675. else
  5676. if (cgpu->temp > cgpu->cutofftemp)
  5677. {
  5678. applog(LOG_WARNING, "%s %u hit thermal cutoff limit, disabling!",
  5679. cgpu->api->name, cgpu->device_id);
  5680. *denable = DEV_RECOVER;
  5681. cgpu->device_last_not_well = time(NULL);
  5682. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5683. ++cgpu->dev_thermal_cutoff_count;
  5684. }
  5685. if (thr->getwork) {
  5686. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  5687. int thrid;
  5688. bool cgpu_idle = true;
  5689. thr->rolling = 0;
  5690. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  5691. if (!cgpu->thr[thrid]->getwork)
  5692. cgpu_idle = false;
  5693. if (cgpu_idle) {
  5694. cgpu->rolling = 0;
  5695. cgpu->status = LIFE_WAIT;
  5696. }
  5697. }
  5698. continue;
  5699. }
  5700. else if (cgpu->status == LIFE_WAIT)
  5701. cgpu->status = LIFE_WELL;
  5702. #ifdef WANT_CPUMINE
  5703. if (!strcmp(cgpu->api->dname, "cpu"))
  5704. continue;
  5705. #endif
  5706. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5707. if (cgpu->status != LIFE_INIT)
  5708. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5709. cgpu->status = LIFE_WELL;
  5710. cgpu->device_last_well = time(NULL);
  5711. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5712. thr->rolling = cgpu->rolling = 0;
  5713. cgpu->status = LIFE_SICK;
  5714. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5715. gettimeofday(&thr->sick, NULL);
  5716. cgpu->device_last_not_well = time(NULL);
  5717. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  5718. cgpu->dev_sick_idle_60_count++;
  5719. #ifdef HAVE_ADL
  5720. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5721. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5722. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5723. } else
  5724. #endif
  5725. if (opt_restart) {
  5726. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5727. reinit_device(cgpu);
  5728. }
  5729. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5730. cgpu->status = LIFE_DEAD;
  5731. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5732. gettimeofday(&thr->sick, NULL);
  5733. cgpu->device_last_not_well = time(NULL);
  5734. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  5735. cgpu->dev_dead_idle_600_count++;
  5736. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5737. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5738. /* Attempt to restart a GPU that's sick or dead once every minute */
  5739. gettimeofday(&thr->sick, NULL);
  5740. #ifdef HAVE_ADL
  5741. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5742. /* Again do not attempt to restart a device that may have hard hung */
  5743. } else
  5744. #endif
  5745. if (opt_restart)
  5746. reinit_device(cgpu);
  5747. }
  5748. }
  5749. }
  5750. return NULL;
  5751. }
  5752. static void log_print_status(struct cgpu_info *cgpu)
  5753. {
  5754. char logline[255];
  5755. get_statline(logline, cgpu);
  5756. applog(LOG_WARNING, "%s", logline);
  5757. }
  5758. static void print_summary(void)
  5759. {
  5760. struct timeval diff;
  5761. int hours, mins, secs, i;
  5762. double utility, efficiency = 0.0, work_util;
  5763. timersub(&total_tv_end, &total_tv_start, &diff);
  5764. hours = diff.tv_sec / 3600;
  5765. mins = (diff.tv_sec % 3600) / 60;
  5766. secs = diff.tv_sec % 60;
  5767. utility = total_accepted / total_secs * 60;
  5768. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  5769. work_util = total_diff1 / total_secs * 60;
  5770. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5771. applog(LOG_WARNING, "Started at %s", datestamp);
  5772. if (total_pools == 1)
  5773. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5774. #ifdef WANT_CPUMINE
  5775. if (opt_n_threads)
  5776. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  5777. #endif
  5778. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5779. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  5780. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5781. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  5782. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5783. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5784. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5785. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5786. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5787. if (total_accepted || total_rejected)
  5788. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5789. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5790. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  5791. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  5792. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  5793. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5794. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5795. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5796. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5797. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5798. if (total_pools > 1) {
  5799. for (i = 0; i < total_pools; i++) {
  5800. struct pool *pool = pools[i];
  5801. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5802. if (pool->solved)
  5803. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5804. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  5805. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5806. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5807. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5808. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  5809. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  5810. if (pool->accepted || pool->rejected)
  5811. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  5812. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  5813. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  5814. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  5815. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  5816. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  5817. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  5818. }
  5819. }
  5820. applog(LOG_WARNING, "Summary of per device statistics:\n");
  5821. for (i = 0; i < total_devices; ++i)
  5822. log_print_status(devices[i]);
  5823. if (opt_shares)
  5824. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  5825. fflush(stdout);
  5826. fflush(stderr);
  5827. if (opt_shares > total_accepted)
  5828. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  5829. }
  5830. static void clean_up(void)
  5831. {
  5832. #ifdef HAVE_OPENCL
  5833. clear_adl(nDevs);
  5834. #endif
  5835. #ifdef HAVE_LIBUSB
  5836. libusb_exit(NULL);
  5837. #endif
  5838. gettimeofday(&total_tv_end, NULL);
  5839. #ifdef HAVE_CURSES
  5840. disable_curses();
  5841. #endif
  5842. if (!opt_realquiet && successful_connect)
  5843. print_summary();
  5844. if (opt_n_threads)
  5845. free(cpus);
  5846. curl_global_cleanup();
  5847. }
  5848. void quit(int status, const char *format, ...)
  5849. {
  5850. va_list ap;
  5851. clean_up();
  5852. if (format) {
  5853. va_start(ap, format);
  5854. vfprintf(stderr, format, ap);
  5855. va_end(ap);
  5856. }
  5857. fprintf(stderr, "\n");
  5858. fflush(stderr);
  5859. if (status) {
  5860. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  5861. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  5862. const char **p = NULL;
  5863. // NOTE debugger can bypass with: p = &p
  5864. *p = format; // Segfault, hopefully dumping core
  5865. }
  5866. }
  5867. #if defined(unix)
  5868. if (forkpid > 0) {
  5869. kill(forkpid, SIGTERM);
  5870. forkpid = 0;
  5871. }
  5872. #endif
  5873. exit(status);
  5874. }
  5875. #ifdef HAVE_CURSES
  5876. char *curses_input(const char *query)
  5877. {
  5878. char *input;
  5879. echo();
  5880. input = malloc(255);
  5881. if (!input)
  5882. quit(1, "Failed to malloc input");
  5883. leaveok(logwin, false);
  5884. wlogprint("%s:\n", query);
  5885. wgetnstr(logwin, input, 255);
  5886. if (!strlen(input))
  5887. strcpy(input, "-1");
  5888. leaveok(logwin, true);
  5889. noecho();
  5890. return input;
  5891. }
  5892. #endif
  5893. void add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  5894. {
  5895. pool->rpc_url = url;
  5896. pool->rpc_user = user;
  5897. pool->rpc_pass = pass;
  5898. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5899. if (!pool->rpc_userpass)
  5900. quit(1, "Failed to malloc userpass");
  5901. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5902. enable_pool(pool);
  5903. /* Prevent noise on startup */
  5904. pool->lagging = true;
  5905. /* Test the pool is not idle if we're live running, otherwise
  5906. * it will be tested separately */
  5907. if (live && !pool_active(pool, false))
  5908. pool->idle = true;
  5909. }
  5910. #ifdef HAVE_CURSES
  5911. static bool input_pool(bool live)
  5912. {
  5913. char *url = NULL, *user = NULL, *pass = NULL;
  5914. struct pool *pool;
  5915. bool ret = false;
  5916. immedok(logwin, true);
  5917. wlogprint("Input server details.\n");
  5918. url = curses_input("URL");
  5919. if (!url)
  5920. goto out;
  5921. user = curses_input("Username");
  5922. if (!user)
  5923. goto out;
  5924. pass = curses_input("Password");
  5925. if (!pass)
  5926. goto out;
  5927. pool = add_pool();
  5928. if (detect_stratum(pool, url))
  5929. url = strdup(pool->stratum_url);
  5930. else if (strncmp(url, "http://", 7) && strncmp(url, "https://", 8)) {
  5931. char *httpinput;
  5932. httpinput = malloc(255);
  5933. if (!httpinput)
  5934. quit(1, "Failed to malloc httpinput");
  5935. strcpy(httpinput, "http://");
  5936. strncat(httpinput, url, 248);
  5937. free(url);
  5938. url = httpinput;
  5939. }
  5940. add_pool_details(pool, live, url, user, pass);
  5941. ret = true;
  5942. out:
  5943. immedok(logwin, false);
  5944. if (!ret) {
  5945. if (url)
  5946. free(url);
  5947. if (user)
  5948. free(user);
  5949. if (pass)
  5950. free(pass);
  5951. }
  5952. return ret;
  5953. }
  5954. #endif
  5955. #if defined(unix)
  5956. static void fork_monitor()
  5957. {
  5958. // Make a pipe: [readFD, writeFD]
  5959. int pfd[2];
  5960. int r = pipe(pfd);
  5961. if (r < 0) {
  5962. perror("pipe - failed to create pipe for --monitor");
  5963. exit(1);
  5964. }
  5965. // Make stderr write end of pipe
  5966. fflush(stderr);
  5967. r = dup2(pfd[1], 2);
  5968. if (r < 0) {
  5969. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  5970. exit(1);
  5971. }
  5972. r = close(pfd[1]);
  5973. if (r < 0) {
  5974. perror("close - failed to close write end of pipe for --monitor");
  5975. exit(1);
  5976. }
  5977. // Don't allow a dying monitor to kill the main process
  5978. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  5979. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  5980. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  5981. perror("signal - failed to edit signal mask for --monitor");
  5982. exit(1);
  5983. }
  5984. // Fork a child process
  5985. forkpid = fork();
  5986. if (forkpid < 0) {
  5987. perror("fork - failed to fork child process for --monitor");
  5988. exit(1);
  5989. }
  5990. // Child: launch monitor command
  5991. if (0 == forkpid) {
  5992. // Make stdin read end of pipe
  5993. r = dup2(pfd[0], 0);
  5994. if (r < 0) {
  5995. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  5996. exit(1);
  5997. }
  5998. close(pfd[0]);
  5999. if (r < 0) {
  6000. perror("close - in child, failed to close read end of pipe for --monitor");
  6001. exit(1);
  6002. }
  6003. // Launch user specified command
  6004. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  6005. perror("execl - in child failed to exec user specified command for --monitor");
  6006. exit(1);
  6007. }
  6008. // Parent: clean up unused fds and bail
  6009. r = close(pfd[0]);
  6010. if (r < 0) {
  6011. perror("close - failed to close read end of pipe for --monitor");
  6012. exit(1);
  6013. }
  6014. }
  6015. #endif // defined(unix)
  6016. #ifdef HAVE_CURSES
  6017. void enable_curses(void) {
  6018. int x,y;
  6019. lock_curses();
  6020. if (curses_active) {
  6021. unlock_curses();
  6022. return;
  6023. }
  6024. mainwin = initscr();
  6025. keypad(mainwin, true);
  6026. getmaxyx(mainwin, y, x);
  6027. statuswin = newwin(logstart, x, 0, 0);
  6028. leaveok(statuswin, true);
  6029. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  6030. // We resize the window later anyway, so just start it off at 1 :)
  6031. logwin = newwin(1, 0, logcursor, 0);
  6032. idlok(logwin, true);
  6033. scrollok(logwin, true);
  6034. leaveok(logwin, true);
  6035. cbreak();
  6036. noecho();
  6037. curses_active = true;
  6038. statusy = logstart;
  6039. unlock_curses();
  6040. }
  6041. #endif
  6042. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  6043. #ifndef WANT_CPUMINE
  6044. struct device_api cpu_api;
  6045. struct device_api cpu_api = {
  6046. .name = "CPU",
  6047. };
  6048. #endif
  6049. #ifdef USE_BITFORCE
  6050. extern struct device_api bitforce_api;
  6051. #endif
  6052. #ifdef USE_ICARUS
  6053. extern struct device_api cairnsmore_api;
  6054. extern struct device_api icarus_api;
  6055. #endif
  6056. #ifdef USE_MODMINER
  6057. extern struct device_api modminer_api;
  6058. #endif
  6059. #ifdef USE_ZTEX
  6060. extern struct device_api ztex_api;
  6061. #endif
  6062. static int cgminer_id_count = 0;
  6063. void register_device(struct cgpu_info *cgpu)
  6064. {
  6065. cgpu->deven = DEV_ENABLED;
  6066. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  6067. mining_threads += cgpu->threads;
  6068. #ifdef HAVE_CURSES
  6069. adj_width(mining_threads, &dev_width);
  6070. #endif
  6071. #ifdef HAVE_OPENCL
  6072. if (cgpu->api == &opencl_api) {
  6073. gpu_threads += cgpu->threads;
  6074. }
  6075. #endif
  6076. }
  6077. struct _cgpu_devid_counter {
  6078. char name[4];
  6079. int lastid;
  6080. UT_hash_handle hh;
  6081. };
  6082. void renumber_cgpu(struct cgpu_info *cgpu)
  6083. {
  6084. static struct _cgpu_devid_counter *devids = NULL;
  6085. struct _cgpu_devid_counter *d;
  6086. HASH_FIND_STR(devids, cgpu->api->name, d);
  6087. if (d)
  6088. cgpu->device_id = ++d->lastid;
  6089. else {
  6090. d = malloc(sizeof(*d));
  6091. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  6092. cgpu->device_id = d->lastid = 0;
  6093. HASH_ADD_STR(devids, name, d);
  6094. }
  6095. }
  6096. bool add_cgpu(struct cgpu_info*cgpu)
  6097. {
  6098. renumber_cgpu(cgpu);
  6099. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  6100. devices[total_devices++] = cgpu;
  6101. return true;
  6102. }
  6103. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  6104. {
  6105. sha2(buffer, length, digest, false);
  6106. return true;
  6107. }
  6108. int main(int argc, char *argv[])
  6109. {
  6110. struct block *block, *tmpblock;
  6111. struct work *work, *tmpwork;
  6112. bool pools_active = false;
  6113. struct sigaction handler;
  6114. struct thr_info *thr;
  6115. char *s;
  6116. unsigned int k;
  6117. int i, j;
  6118. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  6119. /* This dangerous functions tramples random dynamically allocated
  6120. * variables so do it before anything at all */
  6121. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6122. quit(1, "Failed to curl_global_init");
  6123. initial_args = malloc(sizeof(char *) * (argc + 1));
  6124. for (i = 0; i < argc; i++)
  6125. initial_args[i] = strdup(argv[i]);
  6126. initial_args[argc] = NULL;
  6127. #ifdef HAVE_LIBUSB
  6128. libusb_init(NULL);
  6129. #endif
  6130. mutex_init(&hash_lock);
  6131. mutex_init(&qd_lock);
  6132. mutex_init(&console_lock);
  6133. mutex_init(&control_lock);
  6134. mutex_init(&sharelog_lock);
  6135. mutex_init(&ch_lock);
  6136. mutex_init(&sshare_lock);
  6137. rwlock_init(&blk_lock);
  6138. rwlock_init(&netacc_lock);
  6139. mutex_init(&lp_lock);
  6140. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6141. quit(1, "Failed to pthread_cond_init lp_cond");
  6142. mutex_init(&restart_lock);
  6143. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  6144. quit(1, "Failed to pthread_cond_init restart_cond");
  6145. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6146. #ifdef WANT_CPUMINE
  6147. init_max_name_len();
  6148. #endif
  6149. handler.sa_handler = &sighandler;
  6150. handler.sa_flags = 0;
  6151. sigemptyset(&handler.sa_mask);
  6152. sigaction(SIGTERM, &handler, &termhandler);
  6153. sigaction(SIGINT, &handler, &inthandler);
  6154. #ifndef WIN32
  6155. signal(SIGPIPE, SIG_IGN);
  6156. #endif
  6157. opt_kernel_path = alloca(PATH_MAX);
  6158. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6159. cgminer_path = alloca(PATH_MAX);
  6160. s = strdup(argv[0]);
  6161. strcpy(cgminer_path, dirname(s));
  6162. free(s);
  6163. strcat(cgminer_path, "/");
  6164. #ifdef WANT_CPUMINE
  6165. // Hack to make cgminer silent when called recursively on WIN32
  6166. int skip_to_bench = 0;
  6167. #if defined(WIN32)
  6168. char buf[32];
  6169. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  6170. skip_to_bench = 1;
  6171. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  6172. skip_to_bench = 1;
  6173. #endif // defined(WIN32)
  6174. #endif
  6175. devcursor = 8;
  6176. logstart = devcursor + 1;
  6177. logcursor = logstart + 1;
  6178. block = calloc(sizeof(struct block), 1);
  6179. if (unlikely(!block))
  6180. quit (1, "main OOM");
  6181. for (i = 0; i < 36; i++)
  6182. strcat(block->hash, "0");
  6183. HASH_ADD_STR(blocks, hash, block);
  6184. strcpy(current_block, block->hash);
  6185. INIT_LIST_HEAD(&scan_devices);
  6186. mutex_init(&submitting_lock);
  6187. INIT_LIST_HEAD(&submit_waiting);
  6188. #ifdef HAVE_OPENCL
  6189. memset(gpus, 0, sizeof(gpus));
  6190. for (i = 0; i < MAX_GPUDEVICES; i++)
  6191. gpus[i].dynamic = true;
  6192. #endif
  6193. schedstart.tm.tm_sec = 1;
  6194. schedstop .tm.tm_sec = 1;
  6195. /* parse command line */
  6196. opt_register_table(opt_config_table,
  6197. "Options for both config file and command line");
  6198. opt_register_table(opt_cmdline_table,
  6199. "Options for command line only");
  6200. opt_parse(&argc, argv, applog_and_exit);
  6201. if (argc != 1)
  6202. quit(1, "Unexpected extra commandline arguments");
  6203. if (!config_loaded)
  6204. load_default_config();
  6205. if (opt_restart) {
  6206. struct sigaction shandler;
  6207. shandler.sa_handler = &seghandler;
  6208. shandler.sa_flags = 0;
  6209. sigemptyset(&shandler.sa_mask);
  6210. sigaction(SIGSEGV, &shandler, &segvhandler);
  6211. sigaction(SIGILL, &shandler, &illhandler);
  6212. #ifndef WIN32
  6213. sigaction(SIGBUS, &shandler, &bushandler);
  6214. #endif
  6215. }
  6216. if (opt_benchmark) {
  6217. struct pool *pool;
  6218. want_longpoll = false;
  6219. pool = add_pool();
  6220. pool->rpc_url = malloc(255);
  6221. strcpy(pool->rpc_url, "Benchmark");
  6222. pool->rpc_user = pool->rpc_url;
  6223. pool->rpc_pass = pool->rpc_url;
  6224. enable_pool(pool);
  6225. pool->idle = false;
  6226. successful_connect = true;
  6227. }
  6228. #ifdef HAVE_CURSES
  6229. if (opt_realquiet || devices_enabled == -1)
  6230. use_curses = false;
  6231. if (use_curses)
  6232. enable_curses();
  6233. #endif
  6234. applog(LOG_WARNING, "Started %s", packagename);
  6235. if (cnfbuf) {
  6236. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6237. switch (fileconf_load) {
  6238. case 0:
  6239. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6240. applog(LOG_WARNING, "Configuration file could not be used.");
  6241. break;
  6242. case -1:
  6243. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6244. if (use_curses)
  6245. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  6246. break;
  6247. default:
  6248. break;
  6249. }
  6250. free(cnfbuf);
  6251. cnfbuf = NULL;
  6252. }
  6253. strcat(opt_kernel_path, "/");
  6254. if (want_per_device_stats)
  6255. opt_log_output = true;
  6256. #ifdef WANT_CPUMINE
  6257. #ifdef USE_SCRYPT
  6258. if (opt_scrypt)
  6259. set_scrypt_algo(&opt_algo);
  6260. else
  6261. #endif
  6262. if (0 <= opt_bench_algo) {
  6263. double rate = bench_algo_stage3(opt_bench_algo);
  6264. if (!skip_to_bench)
  6265. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  6266. else {
  6267. // Write result to shared memory for parent
  6268. #if defined(WIN32)
  6269. char unique_name[64];
  6270. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  6271. HANDLE map_handle = CreateFileMapping(
  6272. INVALID_HANDLE_VALUE, // use paging file
  6273. NULL, // default security attributes
  6274. PAGE_READWRITE, // read/write access
  6275. 0, // size: high 32-bits
  6276. 4096, // size: low 32-bits
  6277. unique_name // name of map object
  6278. );
  6279. if (NULL != map_handle) {
  6280. void *shared_mem = MapViewOfFile(
  6281. map_handle, // object to map view of
  6282. FILE_MAP_WRITE, // read/write access
  6283. 0, // high offset: map from
  6284. 0, // low offset: beginning
  6285. 0 // default: map entire file
  6286. );
  6287. if (NULL != shared_mem)
  6288. CopyMemory(shared_mem, &rate, sizeof(rate));
  6289. (void)UnmapViewOfFile(shared_mem);
  6290. }
  6291. (void)CloseHandle(map_handle);
  6292. }
  6293. #endif
  6294. }
  6295. exit(0);
  6296. }
  6297. #endif
  6298. #ifdef HAVE_OPENCL
  6299. if (!opt_nogpu)
  6300. opencl_api.api_detect();
  6301. gpu_threads = 0;
  6302. #endif
  6303. #ifdef USE_ICARUS
  6304. if (!opt_scrypt)
  6305. {
  6306. cairnsmore_api.api_detect();
  6307. icarus_api.api_detect();
  6308. }
  6309. #endif
  6310. #ifdef USE_BITFORCE
  6311. if (!opt_scrypt)
  6312. bitforce_api.api_detect();
  6313. #endif
  6314. #ifdef USE_MODMINER
  6315. if (!opt_scrypt)
  6316. modminer_api.api_detect();
  6317. #endif
  6318. #ifdef USE_ZTEX
  6319. if (!opt_scrypt)
  6320. ztex_api.api_detect();
  6321. #endif
  6322. #ifdef WANT_CPUMINE
  6323. cpu_api.api_detect();
  6324. #endif
  6325. for (i = 0; i < total_devices; ++i)
  6326. if (!devices[i]->devtype)
  6327. devices[i]->devtype = "PGA";
  6328. if (devices_enabled == -1) {
  6329. applog(LOG_ERR, "Devices detected:");
  6330. for (i = 0; i < total_devices; ++i) {
  6331. struct cgpu_info *cgpu = devices[i];
  6332. if (cgpu->name)
  6333. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  6334. else
  6335. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  6336. }
  6337. quit(0, "%d devices listed", total_devices);
  6338. }
  6339. mining_threads = 0;
  6340. if (devices_enabled) {
  6341. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  6342. if (devices_enabled & (1 << i)) {
  6343. if (i >= total_devices)
  6344. quit (1, "Command line options set a device that doesn't exist");
  6345. register_device(devices[i]);
  6346. } else if (i < total_devices) {
  6347. if (opt_removedisabled) {
  6348. if (devices[i]->api == &cpu_api)
  6349. --opt_n_threads;
  6350. } else {
  6351. register_device(devices[i]);
  6352. }
  6353. devices[i]->deven = DEV_DISABLED;
  6354. }
  6355. }
  6356. total_devices = cgminer_id_count;
  6357. } else {
  6358. for (i = 0; i < total_devices; ++i)
  6359. register_device(devices[i]);
  6360. }
  6361. if (!total_devices)
  6362. quit(1, "All devices disabled, cannot mine!");
  6363. load_temp_config();
  6364. for (i = 0; i < total_devices; ++i)
  6365. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6366. logstart += total_devices;
  6367. logcursor = logstart + 1;
  6368. #ifdef HAVE_CURSES
  6369. check_winsizes();
  6370. #endif
  6371. if (!total_pools) {
  6372. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6373. #ifdef HAVE_CURSES
  6374. if (!use_curses || !input_pool(false))
  6375. #endif
  6376. quit(1, "Pool setup failed");
  6377. }
  6378. for (i = 0; i < total_pools; i++) {
  6379. struct pool *pool = pools[i];
  6380. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6381. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6382. if (!pool->rpc_userpass) {
  6383. if (!pool->rpc_user || !pool->rpc_pass)
  6384. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6385. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6386. if (!pool->rpc_userpass)
  6387. quit(1, "Failed to malloc userpass");
  6388. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6389. }
  6390. }
  6391. /* Set the currentpool to pool 0 */
  6392. currentpool = pools[0];
  6393. #ifdef HAVE_SYSLOG_H
  6394. if (use_syslog)
  6395. openlog(PACKAGE, LOG_PID, LOG_USER);
  6396. #endif
  6397. #if defined(unix)
  6398. if (opt_stderr_cmd)
  6399. fork_monitor();
  6400. #endif // defined(unix)
  6401. total_threads = mining_threads + 7;
  6402. thr_info = calloc(total_threads, sizeof(*thr));
  6403. if (!thr_info)
  6404. quit(1, "Failed to calloc thr_info");
  6405. /* init workio thread info */
  6406. work_thr_id = mining_threads;
  6407. thr = &thr_info[work_thr_id];
  6408. thr->id = work_thr_id;
  6409. thr->q = tq_new();
  6410. if (!thr->q)
  6411. quit(1, "Failed to tq_new");
  6412. /* start work I/O thread */
  6413. if (thr_info_create(thr, NULL, workio_thread, thr))
  6414. quit(1, "workio thread create failed");
  6415. stage_thr_id = mining_threads + 1;
  6416. thr = &thr_info[stage_thr_id];
  6417. thr->q = tq_new();
  6418. if (!thr->q)
  6419. quit(1, "Failed to tq_new");
  6420. /* start stage thread */
  6421. if (thr_info_create(thr, NULL, stage_thread, thr))
  6422. quit(1, "stage thread create failed");
  6423. pthread_detach(thr->pth);
  6424. /* Create a unique get work queue */
  6425. getq = tq_new();
  6426. if (!getq)
  6427. quit(1, "Failed to create getq");
  6428. /* We use the getq mutex as the staged lock */
  6429. stgd_lock = &getq->mutex;
  6430. if (opt_benchmark)
  6431. goto begin_bench;
  6432. for (i = 0; i < total_pools; i++) {
  6433. struct pool *pool = pools[i];
  6434. enable_pool(pool);
  6435. pool->idle = true;
  6436. }
  6437. applog(LOG_NOTICE, "Probing for an alive pool");
  6438. do {
  6439. /* Look for at least one active pool before starting */
  6440. for (i = 0; i < total_pools; i++) {
  6441. struct pool *pool = pools[i];
  6442. if (pool_active(pool, false)) {
  6443. if (!currentpool)
  6444. currentpool = pool;
  6445. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  6446. pools_active = true;
  6447. break;
  6448. } else {
  6449. if (pool == currentpool)
  6450. currentpool = NULL;
  6451. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  6452. }
  6453. }
  6454. if (!pools_active) {
  6455. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  6456. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  6457. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  6458. for (i = 0; i < total_pools; i++) {
  6459. struct pool *pool;
  6460. pool = pools[i];
  6461. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  6462. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  6463. }
  6464. #ifdef HAVE_CURSES
  6465. if (use_curses) {
  6466. halfdelay(150);
  6467. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  6468. if (getch() != ERR)
  6469. quit(0, "No servers could be used! Exiting.");
  6470. nocbreak();
  6471. } else
  6472. #endif
  6473. quit(0, "No servers could be used! Exiting.");
  6474. }
  6475. } while (!pools_active);
  6476. #ifdef USE_SCRYPT
  6477. if (detect_algo == 1 && !opt_scrypt) {
  6478. applog(LOG_NOTICE, "Detected scrypt algorithm");
  6479. opt_scrypt = true;
  6480. }
  6481. #endif
  6482. detect_algo = 0;
  6483. begin_bench:
  6484. total_mhashes_done = 0;
  6485. for (i = 0; i < total_devices; i++) {
  6486. struct cgpu_info *cgpu = devices[i];
  6487. cgpu->rolling = cgpu->total_mhashes = 0;
  6488. }
  6489. gettimeofday(&total_tv_start, NULL);
  6490. gettimeofday(&total_tv_end, NULL);
  6491. miner_started = total_tv_start;
  6492. if (schedstart.tm.tm_sec)
  6493. schedstart.tm = *localtime(&miner_started.tv_sec);
  6494. if (schedstop.tm.tm_sec)
  6495. schedstop .tm = *localtime(&miner_started.tv_sec);
  6496. get_datestamp(datestamp, &total_tv_start);
  6497. // Start threads
  6498. k = 0;
  6499. for (i = 0; i < total_devices; ++i) {
  6500. struct cgpu_info *cgpu = devices[i];
  6501. cgpu->thr = calloc(cgpu->threads+1, sizeof(*cgpu->thr));
  6502. cgpu->thr[cgpu->threads] = NULL;
  6503. cgpu->status = LIFE_INIT;
  6504. // Setup thread structs before starting any of the threads, in case they try to interact
  6505. for (j = 0; j < cgpu->threads; ++j, ++k) {
  6506. thr = &thr_info[k];
  6507. thr->id = k;
  6508. thr->cgpu = cgpu;
  6509. thr->device_thread = j;
  6510. thr->work_restart_fd = thr->_work_restart_fd_w = -1;
  6511. thr->q = tq_new();
  6512. if (!thr->q)
  6513. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  6514. /* Enable threads for devices set not to mine but disable
  6515. * their queue in case we wish to enable them later */
  6516. if (cgpu->deven != DEV_DISABLED) {
  6517. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  6518. tq_push(thr->q, &ping);
  6519. }
  6520. cgpu->thr[j] = thr;
  6521. }
  6522. for (j = 0; j < cgpu->threads; ++j) {
  6523. thr = cgpu->thr[j];
  6524. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  6525. continue;
  6526. if (!thr->work_restart_fd)
  6527. {
  6528. #if defined(unix)
  6529. int pipefd[2];
  6530. if (!pipe(pipefd))
  6531. {
  6532. thr->work_restart_fd = pipefd[0];
  6533. thr->_work_restart_fd_w = pipefd[1];
  6534. }
  6535. else
  6536. #endif
  6537. thr->work_restart_fd = -1;
  6538. }
  6539. thread_reportout(thr);
  6540. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6541. quit(1, "thread %d create failed", thr->id);
  6542. }
  6543. }
  6544. #ifdef HAVE_OPENCL
  6545. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  6546. for (i = 0; i < nDevs; i++)
  6547. pause_dynamic_threads(i);
  6548. #endif
  6549. #ifdef WANT_CPUMINE
  6550. applog(LOG_INFO, "%d cpu miner threads started, "
  6551. "using SHA256 '%s' algorithm.",
  6552. opt_n_threads,
  6553. algo_names[opt_algo]);
  6554. #endif
  6555. gettimeofday(&total_tv_start, NULL);
  6556. gettimeofday(&total_tv_end, NULL);
  6557. watchpool_thr_id = mining_threads + 2;
  6558. thr = &thr_info[watchpool_thr_id];
  6559. /* start watchpool thread */
  6560. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  6561. quit(1, "watchpool thread create failed");
  6562. pthread_detach(thr->pth);
  6563. watchdog_thr_id = mining_threads + 3;
  6564. thr = &thr_info[watchdog_thr_id];
  6565. /* start watchdog thread */
  6566. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  6567. quit(1, "watchdog thread create failed");
  6568. pthread_detach(thr->pth);
  6569. #ifdef HAVE_OPENCL
  6570. /* Create reinit gpu thread */
  6571. gpur_thr_id = mining_threads + 4;
  6572. thr = &thr_info[gpur_thr_id];
  6573. thr->q = tq_new();
  6574. if (!thr->q)
  6575. quit(1, "tq_new failed for gpur_thr_id");
  6576. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  6577. quit(1, "reinit_gpu thread create failed");
  6578. #endif
  6579. /* Create API socket thread */
  6580. api_thr_id = mining_threads + 5;
  6581. thr = &thr_info[api_thr_id];
  6582. if (thr_info_create(thr, NULL, api_thread, thr))
  6583. quit(1, "API thread create failed");
  6584. #ifdef HAVE_CURSES
  6585. /* Create curses input thread for keyboard input. Create this last so
  6586. * that we know all threads are created since this can call kill_work
  6587. * to try and shut down ll previous threads. */
  6588. input_thr_id = mining_threads + 6;
  6589. thr = &thr_info[input_thr_id];
  6590. if (thr_info_create(thr, NULL, input_thread, thr))
  6591. quit(1, "input thread create failed");
  6592. pthread_detach(thr->pth);
  6593. #endif
  6594. for (i = 0; i < mining_threads + opt_queue; i++)
  6595. queue_request();
  6596. /* main loop - simply wait for workio thread to exit. This is not the
  6597. * normal exit path and only occurs should the workio_thread die
  6598. * unexpectedly */
  6599. pthread_join(thr_info[work_thr_id].pth, NULL);
  6600. applog(LOG_INFO, "workio thread dead, exiting.");
  6601. clean_up();
  6602. /* Not really necessary, but let's clean this up too anyway */
  6603. HASH_ITER(hh, staged_work, work, tmpwork) {
  6604. HASH_DEL(staged_work, work);
  6605. free_work(work);
  6606. }
  6607. HASH_ITER(hh, blocks, block, tmpblock) {
  6608. HASH_DEL(blocks, block);
  6609. free(block);
  6610. }
  6611. #if defined(unix)
  6612. if (forkpid > 0) {
  6613. kill(forkpid, SIGTERM);
  6614. forkpid = 0;
  6615. }
  6616. #endif
  6617. return 0;
  6618. }