miner.c 221 KB

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