miner.c 234 KB

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