miner.c 223 KB

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