miner.c 238 KB

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