miner.c 245 KB

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