miner.c 218 KB

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