miner.c 226 KB

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