miner.c 216 KB

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