miner.c 239 KB

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