miner.c 224 KB

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