miner.c 218 KB

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