miner.c 216 KB

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