miner.c 237 KB

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