miner.c 259 KB

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