miner.c 245 KB

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