miner.c 210 KB

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