miner.c 237 KB

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