miner.c 179 KB

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