miner.c 228 KB

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