miner.c 196 KB

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