miner.c 258 KB

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