miner.c 229 KB

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