miner.c 224 KB

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