miner.c 228 KB

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