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