miner.c 199 KB

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