miner.c 235 KB

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