miner.c 205 KB

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