miner.c 215 KB

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