miner.c 220 KB

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