miner.c 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936
  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. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  3138. memcpy(&sshare->work, work, sizeof(struct work));
  3139. mutex_lock(&sshare_lock);
  3140. sshare->id = swork_id;
  3141. HASH_ADD_INT(stratum_shares, id, sshare);
  3142. mutex_unlock(&sshare_lock);
  3143. }
  3144. goto out;
  3145. }
  3146. ce = pop_curl_entry(pool);
  3147. /* submit solution to bitcoin via JSON-RPC */
  3148. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  3149. resubmit = true;
  3150. if ((!work->stale) && stale_work(work, true)) {
  3151. work->stale = true;
  3152. if (opt_submit_stale)
  3153. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as user requested");
  3154. else if (pool->submit_old)
  3155. applog(LOG_NOTICE, "Share become stale during submission failure, will retry as pool requested");
  3156. else {
  3157. applog(LOG_NOTICE, "Share become stale during submission failure, discarding");
  3158. submit_discard_share(work);
  3159. break;
  3160. }
  3161. staleexpire = time(NULL) + 300;
  3162. }
  3163. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  3164. applog(LOG_ERR, "Failed %d retries, discarding", opt_retries);
  3165. submit_discard_share(work);
  3166. break;
  3167. }
  3168. else if (work->stale) {
  3169. if (unlikely(!list_empty(&submit_waiting))) {
  3170. applog(LOG_WARNING, "Stale share failed to submit while queued submissions are waiting, discarding");
  3171. submit_discard_share(work);
  3172. break;
  3173. } else if (unlikely(opt_retries < 0 && staleexpire <= time(NULL))) {
  3174. applog(LOG_NOTICE, "Stale share failed to submit for 5 minutes, discarding");
  3175. submit_discard_share(work);
  3176. break;
  3177. }
  3178. }
  3179. /* pause, then restart work-request loop */
  3180. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3181. }
  3182. push_curl_entry(ce, pool);
  3183. out:
  3184. workio_cmd_free(wc);
  3185. mutex_lock(&submitting_lock);
  3186. if (!list_empty(&submit_waiting)) {
  3187. applog(LOG_DEBUG, "submit_work continuing with queued submission");
  3188. wc = list_entry(submit_waiting.next, struct workio_cmd, list);
  3189. list_del(&wc->list);
  3190. mutex_unlock(&submitting_lock);
  3191. goto next_submit;
  3192. }
  3193. --submitting;
  3194. mutex_unlock(&submitting_lock);
  3195. return NULL;
  3196. }
  3197. /* We try to reuse curl handles as much as possible, but if there is already
  3198. * work queued to be submitted, we start generating extra handles to submit
  3199. * the shares to avoid ever increasing backlogs. This allows us to scale to
  3200. * any size hardware */
  3201. static bool workio_submit_work(struct workio_cmd *wc)
  3202. {
  3203. pthread_t submit_thread;
  3204. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  3205. applog(LOG_ERR, "Failed to create submit_work_thread");
  3206. return false;
  3207. }
  3208. return true;
  3209. }
  3210. /* Find the pool that currently has the highest priority */
  3211. static struct pool *priority_pool(int choice)
  3212. {
  3213. struct pool *ret = NULL;
  3214. int i;
  3215. for (i = 0; i < total_pools; i++) {
  3216. struct pool *pool = pools[i];
  3217. if (pool->prio == choice) {
  3218. ret = pool;
  3219. break;
  3220. }
  3221. }
  3222. if (unlikely(!ret)) {
  3223. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3224. return pools[choice];
  3225. }
  3226. return ret;
  3227. }
  3228. int prioritize_pools(char *param, int *pid)
  3229. {
  3230. char *ptr, *next;
  3231. int i, pr, prio = 0;
  3232. if (total_pools == 0) {
  3233. return MSG_NOPOOL;
  3234. }
  3235. if (param == NULL || *param == '\0') {
  3236. return MSG_MISPID;
  3237. }
  3238. bool pools_changed[total_pools];
  3239. int new_prio[total_pools];
  3240. for (i = 0; i < total_pools; ++i)
  3241. pools_changed[i] = false;
  3242. next = param;
  3243. while (next && *next) {
  3244. ptr = next;
  3245. next = strchr(ptr, ',');
  3246. if (next)
  3247. *(next++) = '\0';
  3248. i = atoi(ptr);
  3249. if (i < 0 || i >= total_pools) {
  3250. *pid = i;
  3251. return MSG_INVPID;
  3252. }
  3253. if (pools_changed[i]) {
  3254. *pid = i;
  3255. return MSG_DUPPID;
  3256. }
  3257. pools_changed[i] = true;
  3258. new_prio[i] = prio++;
  3259. }
  3260. // Only change them if no errors
  3261. for (i = 0; i < total_pools; i++) {
  3262. if (pools_changed[i])
  3263. pools[i]->prio = new_prio[i];
  3264. }
  3265. // In priority order, cycle through the unchanged pools and append them
  3266. for (pr = 0; pr < total_pools; pr++)
  3267. for (i = 0; i < total_pools; i++) {
  3268. if (!pools_changed[i] && pools[i]->prio == pr) {
  3269. pools[i]->prio = prio++;
  3270. pools_changed[i] = true;
  3271. break;
  3272. }
  3273. }
  3274. if (current_pool()->prio)
  3275. switch_pools(NULL);
  3276. return MSG_POOLPRIO;
  3277. }
  3278. void validate_pool_priorities(void)
  3279. {
  3280. // TODO: this should probably do some sort of logging
  3281. int i, j;
  3282. bool used[total_pools];
  3283. bool valid[total_pools];
  3284. for (i = 0; i < total_pools; i++)
  3285. used[i] = valid[i] = false;
  3286. for (i = 0; i < total_pools; i++) {
  3287. if (pools[i]->prio >=0 && pools[i]->prio < total_pools) {
  3288. if (!used[pools[i]->prio]) {
  3289. valid[i] = true;
  3290. used[pools[i]->prio] = true;
  3291. }
  3292. }
  3293. }
  3294. for (i = 0; i < total_pools; i++) {
  3295. if (!valid[i]) {
  3296. for (j = 0; j < total_pools; j++) {
  3297. if (!used[j]) {
  3298. applog(LOG_WARNING, "Pool %d priority changed from %d to %d", i, pools[i]->prio, j);
  3299. pools[i]->prio = j;
  3300. used[j] = true;
  3301. break;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. }
  3307. void switch_pools(struct pool *selected)
  3308. {
  3309. struct pool *pool, *last_pool;
  3310. int i, pool_no, next_pool;
  3311. mutex_lock(&control_lock);
  3312. last_pool = currentpool;
  3313. pool_no = currentpool->pool_no;
  3314. /* Switch selected to pool number 0 and move the rest down */
  3315. if (selected) {
  3316. if (selected->prio != 0) {
  3317. for (i = 0; i < total_pools; i++) {
  3318. pool = pools[i];
  3319. if (pool->prio < selected->prio)
  3320. pool->prio++;
  3321. }
  3322. selected->prio = 0;
  3323. }
  3324. }
  3325. switch (pool_strategy) {
  3326. /* Both of these set to the master pool */
  3327. case POOL_BALANCE:
  3328. case POOL_FAILOVER:
  3329. case POOL_LOADBALANCE:
  3330. for (i = 0; i < total_pools; i++) {
  3331. pool = priority_pool(i);
  3332. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3333. pool_no = pool->pool_no;
  3334. break;
  3335. }
  3336. }
  3337. break;
  3338. /* Both of these simply increment and cycle */
  3339. case POOL_ROUNDROBIN:
  3340. case POOL_ROTATE:
  3341. if (selected && !selected->idle) {
  3342. pool_no = selected->pool_no;
  3343. break;
  3344. }
  3345. next_pool = pool_no;
  3346. /* Select the next alive pool */
  3347. for (i = 1; i < total_pools; i++) {
  3348. next_pool++;
  3349. if (next_pool >= total_pools)
  3350. next_pool = 0;
  3351. pool = pools[next_pool];
  3352. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  3353. pool_no = next_pool;
  3354. break;
  3355. }
  3356. }
  3357. break;
  3358. default:
  3359. break;
  3360. }
  3361. currentpool = pools[pool_no];
  3362. pool = currentpool;
  3363. mutex_unlock(&control_lock);
  3364. /* Set the lagging flag to avoid pool not providing work fast enough
  3365. * messages in failover only mode since we have to get all fresh work
  3366. * as in restart_threads */
  3367. if (opt_fail_only)
  3368. pool_tset(pool, &pool->lagging);
  3369. if (pool != last_pool)
  3370. {
  3371. pool->block_id = 0;
  3372. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  3373. }
  3374. mutex_lock(&lp_lock);
  3375. pthread_cond_broadcast(&lp_cond);
  3376. mutex_unlock(&lp_lock);
  3377. }
  3378. static void discard_work(struct work *work)
  3379. {
  3380. if (!work->clone && !work->rolls && !work->mined) {
  3381. if (work->pool)
  3382. work->pool->discarded_work++;
  3383. total_discarded++;
  3384. applog(LOG_DEBUG, "Discarded work");
  3385. } else
  3386. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  3387. free_work(work);
  3388. }
  3389. static void discard_stale(void)
  3390. {
  3391. struct work *work, *tmp;
  3392. int stale = 0;
  3393. mutex_lock(stgd_lock);
  3394. HASH_ITER(hh, staged_work, work, tmp) {
  3395. if (stale_work(work, false)) {
  3396. HASH_DEL(staged_work, work);
  3397. work->pool->staged--;
  3398. discard_work(work);
  3399. stale++;
  3400. }
  3401. }
  3402. mutex_unlock(stgd_lock);
  3403. if (stale) {
  3404. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  3405. while (stale-- > 0)
  3406. queue_request();
  3407. }
  3408. }
  3409. void ms_to_abstime(unsigned int mstime, struct timespec *abstime)
  3410. {
  3411. struct timeval now, then, tdiff;
  3412. tdiff.tv_sec = mstime / 1000;
  3413. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  3414. gettimeofday(&now, NULL);
  3415. timeradd(&now, &tdiff, &then);
  3416. abstime->tv_sec = then.tv_sec;
  3417. abstime->tv_nsec = then.tv_usec * 1000;
  3418. }
  3419. /* A generic wait function for threads that poll that will wait a specified
  3420. * time tdiff waiting on the pthread conditional that is broadcast when a
  3421. * work restart is required. Returns the value of pthread_cond_timedwait
  3422. * which is zero if the condition was met or ETIMEDOUT if not.
  3423. */
  3424. int restart_wait(unsigned int mstime)
  3425. {
  3426. struct timespec abstime;
  3427. int rc;
  3428. ms_to_abstime(mstime, &abstime);
  3429. mutex_lock(&restart_lock);
  3430. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  3431. mutex_unlock(&restart_lock);
  3432. return rc;
  3433. }
  3434. /* A generic wait function for threads that poll that will wait a specified
  3435. * time waiting on a share to become stale. Returns positive if the share
  3436. * became stale or zero if the timer expired first. If checkend is true, will
  3437. * immediatley return negative if the share is guaranteed to become stale
  3438. * before the timer expires.
  3439. */
  3440. int stale_wait(unsigned int mstime, struct work*work, bool checkend)
  3441. {
  3442. struct timespec abstime;
  3443. int rc;
  3444. if (checkend) {
  3445. struct timeval tv, orig;
  3446. ldiv_t d;
  3447. d = ldiv(mstime, 1000);
  3448. tv.tv_sec = d.quot;
  3449. tv.tv_usec = d.rem * 1000;
  3450. orig = work->tv_staged;
  3451. timersub(&orig, &tv, &work->tv_staged);
  3452. rc = stale_work(work, true);
  3453. work->tv_staged = orig;
  3454. if (rc)
  3455. return -1;
  3456. }
  3457. ms_to_abstime(mstime, &abstime);
  3458. rc = -1;
  3459. while (1) {
  3460. mutex_lock(&restart_lock);
  3461. if (stale_work(work, true)) {
  3462. rc = 1;
  3463. } else if (pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime)) {
  3464. rc = 0;
  3465. }
  3466. mutex_unlock(&restart_lock);
  3467. if (rc != -1)
  3468. return rc;
  3469. }
  3470. }
  3471. static void restart_threads(void)
  3472. {
  3473. struct pool *cp = current_pool();
  3474. int i, fd;
  3475. struct thr_info *thr;
  3476. /* Artificially set the lagging flag to avoid pool not providing work
  3477. * fast enough messages after every long poll */
  3478. pool_tset(cp, &cp->lagging);
  3479. /* Discard staged work that is now stale */
  3480. discard_stale();
  3481. for (i = 0; i < mining_threads; i++)
  3482. {
  3483. thr = &thr_info[i];
  3484. fd = thr->_work_restart_fd_w;
  3485. thr->work_restart = true;
  3486. if (fd != -1)
  3487. (void)write(fd, "\0", 1);
  3488. }
  3489. mutex_lock(&restart_lock);
  3490. pthread_cond_broadcast(&restart_cond);
  3491. mutex_unlock(&restart_lock);
  3492. }
  3493. static char *blkhashstr(unsigned char *hash)
  3494. {
  3495. unsigned char hash_swap[32];
  3496. swap256(hash_swap, hash);
  3497. swap32tole(hash_swap, hash_swap, 32 / 4);
  3498. return bin2hex(hash_swap, 32);
  3499. }
  3500. static void set_curblock(char *hexstr, unsigned char *hash)
  3501. {
  3502. unsigned char hash_swap[32];
  3503. char *old_hash;
  3504. current_block_id = ((uint32_t*)hash)[0];
  3505. strcpy(current_block, hexstr);
  3506. swap256(hash_swap, hash);
  3507. swap32tole(hash_swap, hash_swap, 32 / 4);
  3508. /* Don't free current_hash directly to avoid dereferencing when read
  3509. * elsewhere - and update block_timeval inside the same lock */
  3510. mutex_lock(&ch_lock);
  3511. gettimeofday(&block_timeval, NULL);
  3512. old_hash = current_hash;
  3513. current_hash = bin2hex(hash_swap + 4, 12);
  3514. free(old_hash);
  3515. old_hash = current_fullhash;
  3516. current_fullhash = bin2hex(hash_swap, 32);
  3517. free(old_hash);
  3518. mutex_unlock(&ch_lock);
  3519. get_timestamp(blocktime, &block_timeval);
  3520. applog(LOG_INFO, "New block: %s...", current_hash);
  3521. }
  3522. /* Search to see if this string is from a block that has been seen before */
  3523. static bool block_exists(char *hexstr)
  3524. {
  3525. struct block *s;
  3526. rd_lock(&blk_lock);
  3527. HASH_FIND_STR(blocks, hexstr, s);
  3528. rd_unlock(&blk_lock);
  3529. if (s)
  3530. return true;
  3531. return false;
  3532. }
  3533. /* Tests if this work is from a block that has been seen before */
  3534. static inline bool from_existing_block(struct work *work)
  3535. {
  3536. char *hexstr = bin2hex(work->data + 8, 18);
  3537. bool ret;
  3538. ret = block_exists(hexstr);
  3539. free(hexstr);
  3540. return ret;
  3541. }
  3542. static int block_sort(struct block *blocka, struct block *blockb)
  3543. {
  3544. return blocka->block_no - blockb->block_no;
  3545. }
  3546. static bool test_work_current(struct work *work)
  3547. {
  3548. bool ret = true;
  3549. char *hexstr;
  3550. if (work->mandatory)
  3551. return ret;
  3552. uint32_t block_id = ((uint32_t*)(work->data))[1];
  3553. hexstr = bin2hex(work->data + 8, 18);
  3554. /* Search to see if this block exists yet and if not, consider it a
  3555. * new block and set the current block details to this one */
  3556. if (!block_exists(hexstr)) {
  3557. struct block *s = calloc(sizeof(struct block), 1);
  3558. int deleted_block = 0;
  3559. ret = false;
  3560. if (unlikely(!s))
  3561. quit (1, "test_work_current OOM");
  3562. strcpy(s->hash, hexstr);
  3563. s->block_no = new_blocks++;
  3564. wr_lock(&blk_lock);
  3565. /* Only keep the last hour's worth of blocks in memory since
  3566. * work from blocks before this is virtually impossible and we
  3567. * want to prevent memory usage from continually rising */
  3568. if (HASH_COUNT(blocks) > 6) {
  3569. struct block *oldblock;
  3570. HASH_SORT(blocks, block_sort);
  3571. oldblock = blocks;
  3572. deleted_block = oldblock->block_no;
  3573. HASH_DEL(blocks, oldblock);
  3574. free(oldblock);
  3575. }
  3576. HASH_ADD_STR(blocks, hash, s);
  3577. wr_unlock(&blk_lock);
  3578. work->pool->block_id = block_id;
  3579. if (deleted_block)
  3580. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  3581. set_curblock(hexstr, &work->data[4]);
  3582. if (unlikely(new_blocks == 1))
  3583. goto out_free;
  3584. if (!work->stratum) {
  3585. if (work->longpoll) {
  3586. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  3587. work->pool->pool_no);
  3588. work->longpoll = false;
  3589. } else if (have_longpoll)
  3590. applog(LOG_NOTICE, "New block detected on network before longpoll");
  3591. else
  3592. applog(LOG_NOTICE, "New block detected on network");
  3593. }
  3594. restart_threads();
  3595. } else {
  3596. bool restart = false;
  3597. struct pool *curpool = NULL;
  3598. if (unlikely(work->pool->block_id != block_id)) {
  3599. bool was_active = work->pool->block_id != 0;
  3600. work->pool->block_id = block_id;
  3601. if (was_active) { // Pool actively changed block
  3602. if (work->pool == (curpool = current_pool()))
  3603. restart = true;
  3604. if (block_id == current_block_id) {
  3605. // Caught up, only announce if this pool is the one in use
  3606. if (restart)
  3607. applog(LOG_NOTICE, "%s %d caught up to new block",
  3608. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3609. work->pool->pool_no);
  3610. } else {
  3611. // Switched to a block we know, but not the latest... why?
  3612. // This might detect pools trying to double-spend or 51%,
  3613. // but let's not make any accusations until it's had time
  3614. // in the real world.
  3615. free(hexstr);
  3616. hexstr = blkhashstr(&work->data[4]);
  3617. applog(LOG_WARNING, "%s %d is issuing work for an old block: %s",
  3618. work->longpoll ? "LONGPOLL from pool" : "Pool",
  3619. work->pool->pool_no,
  3620. hexstr);
  3621. }
  3622. }
  3623. }
  3624. if (work->longpoll) {
  3625. work->longpoll = false;
  3626. ++work->pool->work_restart_id;
  3627. if ((!restart) && work->pool == current_pool()) {
  3628. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  3629. work->pool->pool_no);
  3630. restart = true;
  3631. }
  3632. }
  3633. if (restart)
  3634. restart_threads();
  3635. }
  3636. out_free:
  3637. free(hexstr);
  3638. return ret;
  3639. }
  3640. static int tv_sort(struct work *worka, struct work *workb)
  3641. {
  3642. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  3643. }
  3644. static bool work_rollable(struct work *work)
  3645. {
  3646. return (!work->clone && work->rolltime);
  3647. }
  3648. static bool hash_push(struct work *work)
  3649. {
  3650. bool rc = true, dec = false;
  3651. struct pool *pool = work->pool;
  3652. if (work->queued) {
  3653. work->queued = false;
  3654. dec = true;
  3655. }
  3656. mutex_lock(stgd_lock);
  3657. pool->staged++;
  3658. if (work_rollable(work))
  3659. staged_rollable++;
  3660. if (likely(!getq->frozen)) {
  3661. HASH_ADD_INT(staged_work, id, work);
  3662. HASH_SORT(staged_work, tv_sort);
  3663. } else
  3664. rc = false;
  3665. pthread_cond_signal(&getq->cond);
  3666. mutex_unlock(stgd_lock);
  3667. if (dec) {
  3668. dec_queued(pool);
  3669. applog(LOG_DEBUG, "dec_queued from hash_push");
  3670. }
  3671. return rc;
  3672. }
  3673. static void *stage_thread(void *userdata)
  3674. {
  3675. struct thr_info *mythr = userdata;
  3676. bool ok = true;
  3677. rename_thr("bfg-stage");
  3678. while (ok) {
  3679. struct work *work = NULL;
  3680. applog(LOG_DEBUG, "Popping work to stage thread");
  3681. work = tq_pop(mythr->q, NULL);
  3682. if (unlikely(!work)) {
  3683. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  3684. ok = false;
  3685. break;
  3686. }
  3687. work->work_restart_id = work->pool->work_restart_id;
  3688. test_work_current(work);
  3689. applog(LOG_DEBUG, "Pushing work to getwork queue (queued=%c)", work->queued?'Y':'N');
  3690. if (unlikely(!hash_push(work))) {
  3691. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  3692. continue;
  3693. }
  3694. }
  3695. tq_freeze(mythr->q);
  3696. return NULL;
  3697. }
  3698. static bool stage_work(struct work *work)
  3699. {
  3700. applog(LOG_DEBUG, "Pushing work to stage thread");
  3701. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  3702. applog(LOG_ERR, "Could not tq_push work in stage_work");
  3703. return false;
  3704. }
  3705. return true;
  3706. }
  3707. #ifdef HAVE_CURSES
  3708. int curses_int(const char *query)
  3709. {
  3710. int ret;
  3711. char *cvar;
  3712. cvar = curses_input(query);
  3713. ret = atoi(cvar);
  3714. free(cvar);
  3715. return ret;
  3716. }
  3717. #endif
  3718. #ifdef HAVE_CURSES
  3719. static bool input_pool(bool live);
  3720. #endif
  3721. #ifdef HAVE_CURSES
  3722. static void display_pool_summary(struct pool *pool)
  3723. {
  3724. double efficiency = 0.0;
  3725. if (curses_active_locked()) {
  3726. wlog("Pool: %s\n", pool->rpc_url);
  3727. if (pool->solved)
  3728. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  3729. wlog("%s own long-poll support\n", pool->lp_url ? "Has" : "Does not have");
  3730. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  3731. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  3732. wlog(" Accepted shares: %d\n", pool->accepted);
  3733. wlog(" Rejected shares: %d\n", pool->rejected);
  3734. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  3735. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  3736. if (pool->accepted || pool->rejected)
  3737. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3738. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3739. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  3740. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  3741. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  3742. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  3743. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  3744. unlock_curses();
  3745. }
  3746. }
  3747. #endif
  3748. /* We can't remove the memory used for this struct pool because there may
  3749. * still be work referencing it. We just remove it from the pools list */
  3750. void remove_pool(struct pool *pool)
  3751. {
  3752. int i, last_pool = total_pools - 1;
  3753. struct pool *other;
  3754. /* Boost priority of any lower prio than this one */
  3755. for (i = 0; i < total_pools; i++) {
  3756. other = pools[i];
  3757. if (other->prio > pool->prio)
  3758. other->prio--;
  3759. }
  3760. if (pool->pool_no < last_pool) {
  3761. /* Swap the last pool for this one */
  3762. (pools[last_pool])->pool_no = pool->pool_no;
  3763. pools[pool->pool_no] = pools[last_pool];
  3764. }
  3765. /* Give it an invalid number */
  3766. pool->pool_no = total_pools;
  3767. pool->removed = true;
  3768. pool->has_stratum = false;
  3769. total_pools--;
  3770. }
  3771. /* add a mutex if this needs to be thread safe in the future */
  3772. static struct JE {
  3773. char *buf;
  3774. struct JE *next;
  3775. } *jedata = NULL;
  3776. static void json_escape_free()
  3777. {
  3778. struct JE *jeptr = jedata;
  3779. struct JE *jenext;
  3780. jedata = NULL;
  3781. while (jeptr) {
  3782. jenext = jeptr->next;
  3783. free(jeptr->buf);
  3784. free(jeptr);
  3785. jeptr = jenext;
  3786. }
  3787. }
  3788. static char *json_escape(char *str)
  3789. {
  3790. struct JE *jeptr;
  3791. char *buf, *ptr;
  3792. /* 2x is the max, may as well just allocate that */
  3793. ptr = buf = malloc(strlen(str) * 2 + 1);
  3794. jeptr = malloc(sizeof(*jeptr));
  3795. jeptr->buf = buf;
  3796. jeptr->next = jedata;
  3797. jedata = jeptr;
  3798. while (*str) {
  3799. if (*str == '\\' || *str == '"')
  3800. *(ptr++) = '\\';
  3801. *(ptr++) = *(str++);
  3802. }
  3803. *ptr = '\0';
  3804. return buf;
  3805. }
  3806. void write_config(FILE *fcfg)
  3807. {
  3808. int i;
  3809. /* Write pool values */
  3810. fputs("{\n\"pools\" : [", fcfg);
  3811. for(i = 0; i < total_pools; i++) {
  3812. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", json_escape(pools[i]->rpc_url));
  3813. if (pools[i]->rpc_proxy)
  3814. fprintf(fcfg, "\n\t\t\"pool-proxy\" : \"%s\",", json_escape(pools[i]->rpc_proxy));
  3815. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  3816. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\",", json_escape(pools[i]->rpc_pass));
  3817. fprintf(fcfg, "\n\t\t\"pool-priority\" : \"%d\"\n\t}", pools[i]->prio);
  3818. }
  3819. fputs("\n]\n", fcfg);
  3820. #ifdef HAVE_OPENCL
  3821. if (nDevs) {
  3822. /* Write GPU device values */
  3823. fputs(",\n\"intensity\" : \"", fcfg);
  3824. for(i = 0; i < nDevs; i++)
  3825. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  3826. fputs("\",\n\"vectors\" : \"", fcfg);
  3827. for(i = 0; i < nDevs; i++)
  3828. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3829. gpus[i].vwidth);
  3830. fputs("\",\n\"worksize\" : \"", fcfg);
  3831. for(i = 0; i < nDevs; i++)
  3832. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3833. (int)gpus[i].work_size);
  3834. fputs("\",\n\"kernel\" : \"", fcfg);
  3835. for(i = 0; i < nDevs; i++) {
  3836. fprintf(fcfg, "%s", i > 0 ? "," : "");
  3837. switch (gpus[i].kernel) {
  3838. case KL_NONE: // Shouldn't happen
  3839. break;
  3840. case KL_POCLBM:
  3841. fprintf(fcfg, "poclbm");
  3842. break;
  3843. case KL_PHATK:
  3844. fprintf(fcfg, "phatk");
  3845. break;
  3846. case KL_DIAKGCN:
  3847. fprintf(fcfg, "diakgcn");
  3848. break;
  3849. case KL_DIABLO:
  3850. fprintf(fcfg, "diablo");
  3851. break;
  3852. case KL_SCRYPT:
  3853. fprintf(fcfg, "scrypt");
  3854. break;
  3855. }
  3856. }
  3857. #ifdef USE_SCRYPT
  3858. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  3859. for(i = 0; i < nDevs; i++)
  3860. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3861. (int)gpus[i].opt_lg);
  3862. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  3863. for(i = 0; i < nDevs; i++)
  3864. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3865. (int)gpus[i].opt_tc);
  3866. fputs("\",\n\"shaders\" : \"", fcfg);
  3867. for(i = 0; i < nDevs; i++)
  3868. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  3869. (int)gpus[i].shaders);
  3870. #endif
  3871. #ifdef HAVE_ADL
  3872. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  3873. for(i = 0; i < nDevs; i++)
  3874. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  3875. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  3876. for(i = 0; i < nDevs; i++)
  3877. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  3878. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  3879. for(i = 0; i < nDevs; i++)
  3880. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  3881. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  3882. for(i = 0; i < nDevs; i++)
  3883. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  3884. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  3885. for(i = 0; i < nDevs; i++)
  3886. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  3887. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  3888. for(i = 0; i < nDevs; i++)
  3889. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  3890. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  3891. for(i = 0; i < nDevs; i++)
  3892. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  3893. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  3894. for(i = 0; i < nDevs; i++)
  3895. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  3896. fputs("\",\n\"temp-target\" : \"", fcfg);
  3897. for(i = 0; i < nDevs; i++)
  3898. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].targettemp);
  3899. #endif
  3900. fputs("\"", fcfg);
  3901. }
  3902. #endif
  3903. #ifdef HAVE_ADL
  3904. if (opt_reorder)
  3905. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  3906. #endif
  3907. #ifdef WANT_CPUMINE
  3908. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  3909. #endif
  3910. /* Simple bool and int options */
  3911. struct opt_table *opt;
  3912. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  3913. char *p, *name = strdup(opt->names);
  3914. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  3915. if (p[1] != '-')
  3916. continue;
  3917. if (opt->type & OPT_NOARG &&
  3918. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  3919. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  3920. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  3921. if (opt->type & OPT_HASARG &&
  3922. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  3923. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  3924. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  3925. (void *)opt->cb_arg == (void *)set_int_1_to_10) &&
  3926. opt->desc != opt_hidden &&
  3927. 0 <= *(int *)opt->u.arg)
  3928. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  3929. }
  3930. }
  3931. /* Special case options */
  3932. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  3933. if (pool_strategy == POOL_BALANCE)
  3934. fputs(",\n\"balance\" : true", fcfg);
  3935. if (pool_strategy == POOL_LOADBALANCE)
  3936. fputs(",\n\"load-balance\" : true", fcfg);
  3937. if (pool_strategy == POOL_ROUNDROBIN)
  3938. fputs(",\n\"round-robin\" : true", fcfg);
  3939. if (pool_strategy == POOL_ROTATE)
  3940. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  3941. #if defined(unix)
  3942. if (opt_stderr_cmd && *opt_stderr_cmd)
  3943. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  3944. #endif // defined(unix)
  3945. if (opt_kernel_path && *opt_kernel_path) {
  3946. char *kpath = strdup(opt_kernel_path);
  3947. if (kpath[strlen(kpath)-1] == '/')
  3948. kpath[strlen(kpath)-1] = 0;
  3949. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  3950. }
  3951. if (schedstart.enable)
  3952. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3953. if (schedstop.enable)
  3954. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3955. if (opt_socks_proxy && *opt_socks_proxy)
  3956. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  3957. #ifdef HAVE_OPENCL
  3958. for(i = 0; i < nDevs; i++)
  3959. if (gpus[i].deven == DEV_DISABLED)
  3960. break;
  3961. if (i < nDevs)
  3962. for (i = 0; i < nDevs; i++)
  3963. if (gpus[i].deven != DEV_DISABLED)
  3964. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3965. #endif
  3966. if (opt_api_allow)
  3967. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3968. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3969. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3970. if (opt_api_groups)
  3971. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3972. if (opt_icarus_options)
  3973. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3974. if (opt_icarus_timing)
  3975. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3976. fputs("\n}\n", fcfg);
  3977. json_escape_free();
  3978. }
  3979. #ifdef HAVE_CURSES
  3980. static void display_pools(void)
  3981. {
  3982. struct pool *pool;
  3983. int selected, i, j;
  3984. char input;
  3985. opt_loginput = true;
  3986. immedok(logwin, true);
  3987. clear_logwin();
  3988. updated:
  3989. for (j = 0; j < total_pools; j++) {
  3990. for (i = 0; i < total_pools; i++) {
  3991. pool = pools[i];
  3992. if (pool->prio != j)
  3993. continue;
  3994. if (pool == current_pool())
  3995. wattron(logwin, A_BOLD);
  3996. if (pool->enabled != POOL_ENABLED)
  3997. wattron(logwin, A_DIM);
  3998. wlogprint("%d: ", pool->prio);
  3999. switch (pool->enabled) {
  4000. case POOL_ENABLED:
  4001. wlogprint("Enabled ");
  4002. break;
  4003. case POOL_DISABLED:
  4004. wlogprint("Disabled ");
  4005. break;
  4006. case POOL_REJECTING:
  4007. wlogprint("Rejectin ");
  4008. break;
  4009. }
  4010. if (pool->idle)
  4011. wlogprint("Dead ");
  4012. else
  4013. if (pool->has_stratum)
  4014. wlogprint("Strtm");
  4015. else
  4016. if (pool->lp_url && pool->proto != pool->lp_proto)
  4017. wlogprint("Mixed");
  4018. else
  4019. switch (pool->proto) {
  4020. case PLP_GETBLOCKTEMPLATE:
  4021. wlogprint(" GBT ");
  4022. break;
  4023. case PLP_GETWORK:
  4024. wlogprint("GWork");
  4025. break;
  4026. default:
  4027. wlogprint("Alive");
  4028. }
  4029. wlogprint(" Pool %d: %s User:%s\n",
  4030. pool->pool_no,
  4031. pool->rpc_url, pool->rpc_user);
  4032. wattroff(logwin, A_BOLD | A_DIM);
  4033. break; //for (i = 0; i < total_pools; i++)
  4034. }
  4035. }
  4036. retry:
  4037. wlogprint("\nCurrent pool management strategy: %s\n",
  4038. strategies[pool_strategy]);
  4039. if (pool_strategy == POOL_ROTATE)
  4040. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4041. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4042. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool [P]rioritize pool\n");
  4043. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4044. wlogprint("Or press any other key to continue\n");
  4045. input = getch();
  4046. if (!strncasecmp(&input, "a", 1)) {
  4047. input_pool(true);
  4048. goto updated;
  4049. } else if (!strncasecmp(&input, "r", 1)) {
  4050. if (total_pools <= 1) {
  4051. wlogprint("Cannot remove last pool");
  4052. goto retry;
  4053. }
  4054. selected = curses_int("Select pool number");
  4055. if (selected < 0 || selected >= total_pools) {
  4056. wlogprint("Invalid selection\n");
  4057. goto retry;
  4058. }
  4059. pool = pools[selected];
  4060. if (pool == current_pool())
  4061. switch_pools(NULL);
  4062. if (pool == current_pool()) {
  4063. wlogprint("Unable to remove pool due to activity\n");
  4064. goto retry;
  4065. }
  4066. disable_pool(pool);
  4067. remove_pool(pool);
  4068. goto updated;
  4069. } else if (!strncasecmp(&input, "s", 1)) {
  4070. selected = curses_int("Select pool number");
  4071. if (selected < 0 || selected >= total_pools) {
  4072. wlogprint("Invalid selection\n");
  4073. goto retry;
  4074. }
  4075. pool = pools[selected];
  4076. enable_pool(pool);
  4077. switch_pools(pool);
  4078. goto updated;
  4079. } else if (!strncasecmp(&input, "d", 1)) {
  4080. if (enabled_pools <= 1) {
  4081. wlogprint("Cannot disable last pool");
  4082. goto retry;
  4083. }
  4084. selected = curses_int("Select pool number");
  4085. if (selected < 0 || selected >= total_pools) {
  4086. wlogprint("Invalid selection\n");
  4087. goto retry;
  4088. }
  4089. pool = pools[selected];
  4090. disable_pool(pool);
  4091. if (pool == current_pool())
  4092. switch_pools(NULL);
  4093. goto updated;
  4094. } else if (!strncasecmp(&input, "e", 1)) {
  4095. selected = curses_int("Select pool number");
  4096. if (selected < 0 || selected >= total_pools) {
  4097. wlogprint("Invalid selection\n");
  4098. goto retry;
  4099. }
  4100. pool = pools[selected];
  4101. enable_pool(pool);
  4102. if (pool->prio < current_pool()->prio)
  4103. switch_pools(pool);
  4104. goto updated;
  4105. } else if (!strncasecmp(&input, "c", 1)) {
  4106. for (i = 0; i <= TOP_STRATEGY; i++)
  4107. wlogprint("%d: %s\n", i, strategies[i]);
  4108. selected = curses_int("Select strategy number type");
  4109. if (selected < 0 || selected > TOP_STRATEGY) {
  4110. wlogprint("Invalid selection\n");
  4111. goto retry;
  4112. }
  4113. if (selected == POOL_ROTATE) {
  4114. opt_rotate_period = curses_int("Select interval in minutes");
  4115. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4116. opt_rotate_period = 0;
  4117. wlogprint("Invalid selection\n");
  4118. goto retry;
  4119. }
  4120. }
  4121. pool_strategy = selected;
  4122. switch_pools(NULL);
  4123. goto updated;
  4124. } else if (!strncasecmp(&input, "i", 1)) {
  4125. selected = curses_int("Select pool number");
  4126. if (selected < 0 || selected >= total_pools) {
  4127. wlogprint("Invalid selection\n");
  4128. goto retry;
  4129. }
  4130. pool = pools[selected];
  4131. display_pool_summary(pool);
  4132. goto retry;
  4133. } else if (!strncasecmp(&input, "f", 1)) {
  4134. opt_fail_only ^= true;
  4135. goto updated;
  4136. } else if (!strncasecmp(&input, "p", 1)) {
  4137. switch (prioritize_pools(curses_input("Enter new pool priority (comma separated list)"), &i)) {
  4138. case MSG_NOPOOL:
  4139. wlogprint("No pools\n");
  4140. goto retry;
  4141. case MSG_MISPID:
  4142. wlogprint("Missing pool id parameter\n");
  4143. goto retry;
  4144. case MSG_INVPID:
  4145. wlogprint("Invalid pool id %d - range is 0 - %d\n", i, total_pools - 1);
  4146. goto retry;
  4147. case MSG_DUPPID:
  4148. wlogprint("Duplicate pool specified %d\n", i);
  4149. goto retry;
  4150. case MSG_POOLPRIO:
  4151. default:
  4152. goto updated;
  4153. }
  4154. } else
  4155. clear_logwin();
  4156. immedok(logwin, false);
  4157. opt_loginput = false;
  4158. }
  4159. static void display_options(void)
  4160. {
  4161. int selected;
  4162. char input;
  4163. opt_loginput = true;
  4164. immedok(logwin, true);
  4165. clear_logwin();
  4166. retry:
  4167. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4168. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4169. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  4170. "[L]og interval:%d\n",
  4171. opt_debug_console ? "on" : "off",
  4172. want_per_device_stats? "on" : "off",
  4173. opt_quiet ? "on" : "off",
  4174. opt_log_output ? "on" : "off",
  4175. opt_protocol ? "on" : "off",
  4176. opt_worktime ? "on" : "off",
  4177. opt_compact ? "on" : "off",
  4178. opt_log_interval);
  4179. wlogprint("Select an option or any other key to return\n");
  4180. input = getch();
  4181. if (!strncasecmp(&input, "q", 1)) {
  4182. opt_quiet ^= true;
  4183. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4184. goto retry;
  4185. } else if (!strncasecmp(&input, "v", 1)) {
  4186. opt_log_output ^= true;
  4187. if (opt_log_output)
  4188. opt_quiet = false;
  4189. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4190. goto retry;
  4191. } else if (!strncasecmp(&input, "n", 1)) {
  4192. opt_log_output = false;
  4193. opt_debug_console = false;
  4194. opt_quiet = false;
  4195. opt_protocol = false;
  4196. opt_compact = false;
  4197. want_per_device_stats = false;
  4198. wlogprint("Output mode reset to normal\n");
  4199. switch_compact();
  4200. goto retry;
  4201. } else if (!strncasecmp(&input, "d", 1)) {
  4202. opt_debug = true;
  4203. opt_debug_console ^= true;
  4204. opt_log_output = opt_debug_console;
  4205. if (opt_debug_console)
  4206. opt_quiet = false;
  4207. wlogprint("Debug mode %s\n", opt_debug_console ? "enabled" : "disabled");
  4208. goto retry;
  4209. } else if (!strncasecmp(&input, "m", 1)) {
  4210. opt_compact ^= true;
  4211. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  4212. switch_compact();
  4213. goto retry;
  4214. } else if (!strncasecmp(&input, "p", 1)) {
  4215. want_per_device_stats ^= true;
  4216. opt_log_output = want_per_device_stats;
  4217. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4218. goto retry;
  4219. } else if (!strncasecmp(&input, "r", 1)) {
  4220. opt_protocol ^= true;
  4221. if (opt_protocol)
  4222. opt_quiet = false;
  4223. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4224. goto retry;
  4225. } else if (!strncasecmp(&input, "c", 1))
  4226. clear_logwin();
  4227. else if (!strncasecmp(&input, "l", 1)) {
  4228. selected = curses_int("Interval in seconds");
  4229. if (selected < 0 || selected > 9999) {
  4230. wlogprint("Invalid selection\n");
  4231. goto retry;
  4232. }
  4233. opt_log_interval = selected;
  4234. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4235. goto retry;
  4236. } else if (!strncasecmp(&input, "s", 1)) {
  4237. opt_realquiet = true;
  4238. } else if (!strncasecmp(&input, "w", 1)) {
  4239. opt_worktime ^= true;
  4240. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4241. goto retry;
  4242. } else
  4243. clear_logwin();
  4244. immedok(logwin, false);
  4245. opt_loginput = false;
  4246. }
  4247. #endif
  4248. void default_save_file(char *filename)
  4249. {
  4250. #if defined(unix)
  4251. if (getenv("HOME") && *getenv("HOME")) {
  4252. strcpy(filename, getenv("HOME"));
  4253. strcat(filename, "/");
  4254. }
  4255. else
  4256. strcpy(filename, "");
  4257. strcat(filename, ".bfgminer/");
  4258. mkdir(filename, 0777);
  4259. #else
  4260. strcpy(filename, "");
  4261. #endif
  4262. strcat(filename, def_conf);
  4263. }
  4264. #ifdef HAVE_CURSES
  4265. static void set_options(void)
  4266. {
  4267. int selected;
  4268. char input;
  4269. opt_loginput = true;
  4270. immedok(logwin, true);
  4271. clear_logwin();
  4272. retry:
  4273. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  4274. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n[R]etries: %d\n"
  4275. "[W]rite config file\n[B]FGMiner restart\n",
  4276. opt_queue, opt_scantime, opt_expiry, opt_retries);
  4277. wlogprint("Select an option or any other key to return\n");
  4278. input = getch();
  4279. if (!strncasecmp(&input, "q", 1)) {
  4280. selected = curses_int("Extra work items to queue");
  4281. if (selected < 0 || selected > 9999) {
  4282. wlogprint("Invalid selection\n");
  4283. goto retry;
  4284. }
  4285. opt_queue = selected;
  4286. goto retry;
  4287. } else if (!strncasecmp(&input, "l", 1)) {
  4288. if (want_longpoll)
  4289. stop_longpoll();
  4290. else
  4291. start_longpoll();
  4292. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  4293. goto retry;
  4294. } else if (!strncasecmp(&input, "s", 1)) {
  4295. selected = curses_int("Set scantime in seconds");
  4296. if (selected < 0 || selected > 9999) {
  4297. wlogprint("Invalid selection\n");
  4298. goto retry;
  4299. }
  4300. opt_scantime = selected;
  4301. goto retry;
  4302. } else if (!strncasecmp(&input, "e", 1)) {
  4303. selected = curses_int("Set expiry time in seconds");
  4304. if (selected < 0 || selected > 9999) {
  4305. wlogprint("Invalid selection\n");
  4306. goto retry;
  4307. }
  4308. opt_expiry = selected;
  4309. goto retry;
  4310. } else if (!strncasecmp(&input, "r", 1)) {
  4311. selected = curses_int("Retries before failing (-1 infinite)");
  4312. if (selected < -1 || selected > 9999) {
  4313. wlogprint("Invalid selection\n");
  4314. goto retry;
  4315. }
  4316. opt_retries = selected;
  4317. goto retry;
  4318. } else if (!strncasecmp(&input, "w", 1)) {
  4319. FILE *fcfg;
  4320. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4321. default_save_file(filename);
  4322. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  4323. str = curses_input(prompt);
  4324. if (strcmp(str, "-1")) {
  4325. struct stat statbuf;
  4326. strcpy(filename, str);
  4327. if (!stat(filename, &statbuf)) {
  4328. wlogprint("File exists, overwrite?\n");
  4329. input = getch();
  4330. if (strncasecmp(&input, "y", 1))
  4331. goto retry;
  4332. }
  4333. }
  4334. fcfg = fopen(filename, "w");
  4335. if (!fcfg) {
  4336. wlogprint("Cannot open or create file\n");
  4337. goto retry;
  4338. }
  4339. write_config(fcfg);
  4340. fclose(fcfg);
  4341. goto retry;
  4342. } else if (!strncasecmp(&input, "b", 1)) {
  4343. wlogprint("Are you sure?\n");
  4344. input = getch();
  4345. if (!strncasecmp(&input, "y", 1))
  4346. app_restart();
  4347. else
  4348. clear_logwin();
  4349. } else
  4350. clear_logwin();
  4351. immedok(logwin, false);
  4352. opt_loginput = false;
  4353. }
  4354. static void *input_thread(void __maybe_unused *userdata)
  4355. {
  4356. rename_thr("bfg-input");
  4357. if (!curses_active)
  4358. return NULL;
  4359. while (1) {
  4360. int input;
  4361. input = getch();
  4362. switch (input) {
  4363. case 'q': case 'Q':
  4364. kill_work();
  4365. return NULL;
  4366. case 'd': case 'D':
  4367. display_options();
  4368. break;
  4369. case 'p': case 'P':
  4370. display_pools();
  4371. break;
  4372. case 's': case 'S':
  4373. set_options();
  4374. break;
  4375. case 'g': case 'G':
  4376. if (have_opencl)
  4377. manage_gpu();
  4378. break;
  4379. #ifdef HAVE_CURSES
  4380. case KEY_DOWN:
  4381. if (devsummaryYOffset < -(total_devices + devcursor - statusy))
  4382. break;
  4383. devsummaryYOffset -= 2;
  4384. case KEY_UP:
  4385. if (devsummaryYOffset == 0)
  4386. break;
  4387. ++devsummaryYOffset;
  4388. if (curses_active_locked()) {
  4389. int i;
  4390. for (i = 0; i < mining_threads; i++)
  4391. curses_print_devstatus(i);
  4392. touchwin(statuswin);
  4393. wrefresh(statuswin);
  4394. unlock_curses();
  4395. }
  4396. break;
  4397. #endif
  4398. }
  4399. if (opt_realquiet) {
  4400. disable_curses();
  4401. break;
  4402. }
  4403. }
  4404. return NULL;
  4405. }
  4406. #endif
  4407. /* This thread should not be shut down unless a problem occurs */
  4408. static void *workio_thread(void *userdata)
  4409. {
  4410. struct thr_info *mythr = userdata;
  4411. bool ok = true;
  4412. rename_thr("bfg-workio");
  4413. while (ok) {
  4414. struct workio_cmd *wc;
  4415. applog(LOG_DEBUG, "Popping work to work thread");
  4416. /* wait for workio_cmd sent to us, on our queue */
  4417. wc = tq_pop(mythr->q, NULL);
  4418. if (unlikely(!wc)) {
  4419. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  4420. ok = false;
  4421. break;
  4422. }
  4423. /* process workio_cmd */
  4424. switch (wc->cmd) {
  4425. case WC_GET_WORK:
  4426. ok = workio_get_work(wc);
  4427. break;
  4428. case WC_SUBMIT_WORK:
  4429. {
  4430. mutex_lock(&submitting_lock);
  4431. if (submitting >= opt_submit_threads) {
  4432. if (list_empty(&submit_waiting))
  4433. applog(LOG_WARNING, "workio_thread queuing submissions (see --submit-threads)");
  4434. else
  4435. applog(LOG_DEBUG, "workio_thread queuing submission");
  4436. list_add_tail(&wc->list, &submit_waiting);
  4437. mutex_unlock(&submitting_lock);
  4438. break;
  4439. }
  4440. ++submitting;
  4441. mutex_unlock(&submitting_lock);
  4442. ok = workio_submit_work(wc);
  4443. break;
  4444. }
  4445. default:
  4446. ok = false;
  4447. break;
  4448. }
  4449. }
  4450. tq_freeze(mythr->q);
  4451. return NULL;
  4452. }
  4453. static void *api_thread(void *userdata)
  4454. {
  4455. struct thr_info *mythr = userdata;
  4456. pthread_detach(pthread_self());
  4457. rename_thr("bfg-rpc");
  4458. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4459. api(api_thr_id);
  4460. PTH(mythr) = 0L;
  4461. return NULL;
  4462. }
  4463. void thread_reportin(struct thr_info *thr)
  4464. {
  4465. gettimeofday(&thr->last, NULL);
  4466. thr->cgpu->status = LIFE_WELL;
  4467. thr->getwork = 0;
  4468. thr->cgpu->device_last_well = time(NULL);
  4469. }
  4470. static inline void thread_reportout(struct thr_info *thr)
  4471. {
  4472. thr->getwork = time(NULL);
  4473. }
  4474. static void hashmeter(int thr_id, struct timeval *diff,
  4475. uint64_t hashes_done)
  4476. {
  4477. struct timeval temp_tv_end, total_diff;
  4478. double secs;
  4479. double local_secs;
  4480. double utility, efficiency = 0.0;
  4481. static double local_mhashes_done = 0;
  4482. static double rolling = 0;
  4483. double local_mhashes = (double)hashes_done / 1000000.0;
  4484. bool showlog = false;
  4485. char cHr[h2bs_fmt_size[H2B_NOUNIT]], aHr[h2bs_fmt_size[H2B_NOUNIT]], uHr[h2bs_fmt_size[H2B_SPACED]];
  4486. /* Update the last time this thread reported in */
  4487. if (thr_id >= 0) {
  4488. gettimeofday(&thr_info[thr_id].last, NULL);
  4489. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  4490. }
  4491. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  4492. /* So we can call hashmeter from a non worker thread */
  4493. if (thr_id >= 0) {
  4494. struct thr_info *thr = &thr_info[thr_id];
  4495. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  4496. double thread_rolling = 0.0;
  4497. int i;
  4498. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f khash/sec]",
  4499. thr_id, hashes_done, hashes_done / 1000 / secs);
  4500. /* Rolling average for each thread and each device */
  4501. decay_time(&thr->rolling, local_mhashes / secs);
  4502. for (i = 0; i < cgpu->threads; i++)
  4503. thread_rolling += cgpu->thr[i]->rolling;
  4504. mutex_lock(&hash_lock);
  4505. decay_time(&cgpu->rolling, thread_rolling);
  4506. cgpu->total_mhashes += local_mhashes;
  4507. mutex_unlock(&hash_lock);
  4508. // If needed, output detailed, per-device stats
  4509. if (want_per_device_stats) {
  4510. struct timeval now;
  4511. struct timeval elapsed;
  4512. gettimeofday(&now, NULL);
  4513. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  4514. if (opt_log_interval <= elapsed.tv_sec) {
  4515. struct cgpu_info *cgpu = thr->cgpu;
  4516. char logline[255];
  4517. cgpu->last_message_tv = now;
  4518. get_statline(logline, cgpu);
  4519. if (!curses_active) {
  4520. printf("%s \r", logline);
  4521. fflush(stdout);
  4522. } else
  4523. applog(LOG_INFO, "%s", logline);
  4524. }
  4525. }
  4526. }
  4527. /* Totals are updated by all threads so can race without locking */
  4528. mutex_lock(&hash_lock);
  4529. gettimeofday(&temp_tv_end, NULL);
  4530. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  4531. total_mhashes_done += local_mhashes;
  4532. local_mhashes_done += local_mhashes;
  4533. if (total_diff.tv_sec < opt_log_interval)
  4534. /* Only update the total every opt_log_interval seconds */
  4535. goto out_unlock;
  4536. showlog = true;
  4537. gettimeofday(&total_tv_end, NULL);
  4538. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  4539. decay_time(&rolling, local_mhashes_done / local_secs);
  4540. global_hashrate = roundl(rolling) * 1000000;
  4541. timersub(&total_tv_end, &total_tv_start, &total_diff);
  4542. total_secs = (double)total_diff.tv_sec +
  4543. ((double)total_diff.tv_usec / 1000000.0);
  4544. utility = total_accepted / total_secs * 60;
  4545. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4546. ti_hashrate_bufstr(
  4547. (char*[]){cHr, aHr, uHr},
  4548. 1e6*rolling,
  4549. 1e6*total_mhashes_done / total_secs,
  4550. utility_to_hashrate(total_accepted_weighed / (total_secs ?: 1) * 60),
  4551. H2B_SPACED);
  4552. sprintf(statusline, "%s%ds:%s avg:%s u:%s | A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  4553. want_per_device_stats ? "ALL " : "",
  4554. opt_log_interval,
  4555. cHr, aHr,
  4556. uHr,
  4557. total_accepted, total_rejected, hw_errors, efficiency, utility);
  4558. local_mhashes_done = 0;
  4559. out_unlock:
  4560. mutex_unlock(&hash_lock);
  4561. if (showlog) {
  4562. if (!curses_active) {
  4563. printf("%s \r", statusline);
  4564. fflush(stdout);
  4565. } else
  4566. applog(LOG_INFO, "%s", statusline);
  4567. }
  4568. }
  4569. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  4570. struct stratum_share *sshare)
  4571. {
  4572. struct work *work = &sshare->work;
  4573. uint64_t sharediff = share_diff(work);
  4574. char hashshow[65];
  4575. uint32_t *hash32;
  4576. char diffdisp[16];
  4577. int intdiff;
  4578. hash32 = (uint32_t *)(work->hash);
  4579. intdiff = floor(work->work_difficulty);
  4580. suffix_string(sharediff, diffdisp, 0);
  4581. sprintf(hashshow, "%08lx Diff %s/%d%s", (unsigned long)(hash32[6]), diffdisp, intdiff,
  4582. work->block? " BLOCK!" : "");
  4583. share_result(val, res_val, err_val, work, hashshow, false, "");
  4584. }
  4585. /* Parses stratum json responses and tries to find the id that the request
  4586. * matched to and treat it accordingly. */
  4587. static bool parse_stratum_response(char *s)
  4588. {
  4589. json_t *val = NULL, *err_val, *res_val, *id_val;
  4590. struct stratum_share *sshare;
  4591. json_error_t err;
  4592. bool ret = false;
  4593. int id;
  4594. val = JSON_LOADS(s, &err);
  4595. if (!val) {
  4596. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  4597. goto out;
  4598. }
  4599. res_val = json_object_get(val, "result");
  4600. err_val = json_object_get(val, "error");
  4601. id_val = json_object_get(val, "id");
  4602. if (json_is_null(id_val) || !id_val) {
  4603. char *ss;
  4604. if (err_val)
  4605. ss = json_dumps(err_val, JSON_INDENT(3));
  4606. else
  4607. ss = strdup("(unknown reason)");
  4608. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  4609. free(ss);
  4610. goto out;
  4611. }
  4612. id = json_integer_value(id_val);
  4613. mutex_lock(&sshare_lock);
  4614. HASH_FIND_INT(stratum_shares, &id, sshare);
  4615. if (sshare)
  4616. HASH_DEL(stratum_shares, sshare);
  4617. mutex_unlock(&sshare_lock);
  4618. if (!sshare) {
  4619. if (json_is_true(res_val))
  4620. applog(LOG_NOTICE, "Accepted untracked stratum share");
  4621. else
  4622. applog(LOG_NOTICE, "Rejected untracked stratum share");
  4623. goto out;
  4624. }
  4625. stratum_share_result(val, res_val, err_val, sshare);
  4626. free(sshare);
  4627. ret = true;
  4628. out:
  4629. if (val)
  4630. json_decref(val);
  4631. return ret;
  4632. }
  4633. static void shutdown_stratum(struct pool *pool)
  4634. {
  4635. // Shut down Stratum as if we never had it
  4636. pool->has_stratum = false;
  4637. shutdown(pool->sock, SHUT_RDWR);
  4638. free(pool->stratum_url);
  4639. if (pool->sockaddr_url == pool->stratum_url)
  4640. pool->sockaddr_url = NULL;
  4641. pool->stratum_url = NULL;
  4642. }
  4643. static void pool_resus(struct pool *pool);
  4644. static bool pool_active(struct pool *pool, bool pinging);
  4645. /* One stratum thread per pool that has stratum waits on the socket checking
  4646. * for new messages and for the integrity of the socket connection. We reset
  4647. * the connection based on the integrity of the receive side only as the send
  4648. * side will eventually expire data it fails to send. */
  4649. static void *stratum_thread(void *userdata)
  4650. {
  4651. struct pool *pool = (struct pool *)userdata;
  4652. pthread_detach(pthread_self());
  4653. while (42) {
  4654. struct timeval timeout;
  4655. fd_set rd;
  4656. char *s;
  4657. if (unlikely(!pool->has_stratum))
  4658. break;
  4659. FD_ZERO(&rd);
  4660. FD_SET(pool->sock, &rd);
  4661. timeout.tv_sec = 120;
  4662. timeout.tv_usec = 0;
  4663. /* The protocol specifies that notify messages should be sent
  4664. * every minute so if we fail to receive any for 2 minutes we
  4665. * assume the connection has been dropped and treat this pool
  4666. * as dead */
  4667. select(pool->sock + 1, &rd, NULL, NULL, &timeout);
  4668. s = recv_line(pool);
  4669. if (!s) {
  4670. if (!pool->has_stratum)
  4671. break;
  4672. applog(LOG_INFO, "Stratum connection to pool %d interrupted", pool->pool_no);
  4673. pool->getfail_occasions++;
  4674. total_go++;
  4675. if (initiate_stratum(pool) && auth_stratum(pool))
  4676. continue;
  4677. if (pool->rpc_url[0] != 's') {
  4678. shutdown_stratum(pool);
  4679. pool_active(pool, false);
  4680. break;
  4681. }
  4682. pool_died(pool);
  4683. while (!initiate_stratum(pool) || !auth_stratum(pool)) {
  4684. if (pool->removed)
  4685. goto out;
  4686. sleep(30);
  4687. }
  4688. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  4689. pool_tclear(pool, &pool->idle);
  4690. pool_resus(pool);
  4691. continue;
  4692. }
  4693. if (!parse_method(pool, s) && !parse_stratum_response(s))
  4694. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  4695. free(s);
  4696. if (pool->swork.clean) {
  4697. struct work work;
  4698. /* Generate a single work item to update the current
  4699. * block database */
  4700. pool->swork.clean = false;
  4701. gen_stratum_work(pool, &work);
  4702. if (test_work_current(&work)) {
  4703. /* Only accept a work restart if this stratum
  4704. * connection is from the current pool */
  4705. if (pool == current_pool()) {
  4706. restart_threads();
  4707. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  4708. }
  4709. } else
  4710. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  4711. }
  4712. }
  4713. out:
  4714. return NULL;
  4715. }
  4716. static void init_stratum_thread(struct pool *pool)
  4717. {
  4718. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  4719. quit(1, "Failed to create stratum thread");
  4720. }
  4721. static void *longpoll_thread(void *userdata);
  4722. static bool stratum_works(struct pool *pool)
  4723. {
  4724. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  4725. if (!extract_sockaddr(pool, pool->stratum_url))
  4726. return false;
  4727. if (!initiate_stratum(pool))
  4728. return false;
  4729. return true;
  4730. }
  4731. // NOTE: This assumes reference URI is a root
  4732. static char *absolute_uri(char *uri, const char *ref)
  4733. {
  4734. if (strstr(uri, "://"))
  4735. return strdup(uri);
  4736. char *copy_start, *abs;
  4737. bool need_slash = false;
  4738. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  4739. if (ref[strlen(ref) - 1] != '/')
  4740. need_slash = true;
  4741. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  4742. if (!abs) {
  4743. applog(LOG_ERR, "Malloc failure in absolute_uri");
  4744. return NULL;
  4745. }
  4746. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  4747. return abs;
  4748. }
  4749. static bool pool_active(struct pool *pool, bool pinging)
  4750. {
  4751. struct timeval tv_getwork, tv_getwork_reply;
  4752. bool ret = false;
  4753. json_t *val;
  4754. CURL *curl;
  4755. int rolltime;
  4756. char *rpc_req;
  4757. struct work *work;
  4758. enum pool_protocol proto;
  4759. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  4760. /* This is the central point we activate stratum when we can */
  4761. curl = curl_easy_init();
  4762. if (unlikely(!curl)) {
  4763. applog(LOG_ERR, "CURL initialisation failed");
  4764. return false;
  4765. }
  4766. work = make_work();
  4767. work->pool = pool;
  4768. proto = want_gbt ? PLP_GETBLOCKTEMPLATE : PLP_GETWORK;
  4769. tryagain:
  4770. rpc_req = prepare_rpc_req(work, proto, NULL);
  4771. if (!rpc_req)
  4772. return false;
  4773. pool->probed = false;
  4774. gettimeofday(&tv_getwork, NULL);
  4775. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  4776. true, false, &rolltime, pool, false);
  4777. gettimeofday(&tv_getwork_reply, NULL);
  4778. free(rpc_req);
  4779. /* Detect if a http getwork pool has an X-Stratum header at startup,
  4780. * and if so, switch to that in preference to getwork if it works */
  4781. if (pool->stratum_url && want_stratum && (pool->has_stratum || stratum_works(pool))) {
  4782. curl_easy_cleanup(curl);
  4783. if (!pool->has_stratum) {
  4784. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  4785. if (!pool->rpc_url)
  4786. pool->rpc_url = strdup(pool->stratum_url);
  4787. pool->has_stratum = true;
  4788. }
  4789. retry_stratum:
  4790. /* We create the stratum thread for each pool just after
  4791. * successful authorisation. Once the auth flag has been set
  4792. * we never unset it and the stratum thread is responsible for
  4793. * setting/unsetting the active flag */
  4794. if (pool->stratum_auth)
  4795. return pool->stratum_active;
  4796. if (!pool->stratum_active && !initiate_stratum(pool))
  4797. return false;
  4798. if (!auth_stratum(pool))
  4799. return false;
  4800. pool->idle = false;
  4801. pool->stratum_auth = true;
  4802. init_stratum_thread(pool);
  4803. return true;
  4804. }
  4805. else if (pool->has_stratum)
  4806. shutdown_stratum(pool);
  4807. if (val) {
  4808. bool rc;
  4809. json_t *res;
  4810. res = json_object_get(val, "result");
  4811. if ((!json_is_object(res)) || (proto == PLP_GETBLOCKTEMPLATE && !json_object_get(res, "bits")))
  4812. goto badwork;
  4813. rc = work_decode(res, work);
  4814. if (rc) {
  4815. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  4816. pool->pool_no, pool->rpc_url);
  4817. work->pool = pool;
  4818. work->rolltime = rolltime;
  4819. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  4820. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  4821. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  4822. calc_diff(work, 0);
  4823. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  4824. tq_push(thr_info[stage_thr_id].q, work);
  4825. total_getworks++;
  4826. pool->getwork_requested++;
  4827. ret = true;
  4828. gettimeofday(&pool->tv_idle, NULL);
  4829. } else {
  4830. badwork:
  4831. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  4832. pool->pool_no, pool->rpc_url);
  4833. if (PLP_NONE != (proto = pool_protocol_fallback(proto)))
  4834. goto tryagain;
  4835. free_work(work);
  4836. goto out;
  4837. }
  4838. json_decref(val);
  4839. if (proto != pool->proto) {
  4840. pool->proto = proto;
  4841. applog(LOG_INFO, "Selected %s protocol for pool %u", pool_protocol_name(proto), pool->pool_no);
  4842. }
  4843. if (pool->lp_url)
  4844. goto out;
  4845. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  4846. const struct blktmpl_longpoll_req *lp;
  4847. if (work->tmpl && (lp = blktmpl_get_longpoll(work->tmpl))) {
  4848. // NOTE: work_decode takes care of lp id
  4849. pool->lp_url = lp->uri ? absolute_uri(lp->uri, pool->rpc_url) : pool->rpc_url;
  4850. if (!pool->lp_url)
  4851. return false;
  4852. pool->lp_proto = PLP_GETBLOCKTEMPLATE;
  4853. }
  4854. else
  4855. if (pool->hdr_path) {
  4856. pool->lp_url = absolute_uri(pool->hdr_path, pool->rpc_url);
  4857. if (!pool->lp_url)
  4858. return false;
  4859. pool->lp_proto = PLP_GETWORK;
  4860. } else
  4861. pool->lp_url = NULL;
  4862. if (want_longpoll && !pool->lp_started) {
  4863. pool->lp_started = true;
  4864. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  4865. quit(1, "Failed to create pool longpoll thread");
  4866. }
  4867. } else if (PLP_NONE != (proto = pool_protocol_fallback(proto))) {
  4868. goto tryagain;
  4869. } else {
  4870. free_work(work);
  4871. /* If we failed to parse a getwork, this could be a stratum
  4872. * url without the prefix stratum+tcp:// so let's check it */
  4873. if (initiate_stratum(pool)) {
  4874. pool->has_stratum = true;
  4875. goto retry_stratum;
  4876. }
  4877. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  4878. pool->pool_no, pool->rpc_url);
  4879. if (!pinging)
  4880. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  4881. }
  4882. out:
  4883. curl_easy_cleanup(curl);
  4884. return ret;
  4885. }
  4886. static inline int cp_prio(void)
  4887. {
  4888. int prio;
  4889. mutex_lock(&control_lock);
  4890. prio = currentpool->prio;
  4891. mutex_unlock(&control_lock);
  4892. return prio;
  4893. }
  4894. static void pool_resus(struct pool *pool)
  4895. {
  4896. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  4897. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  4898. switch_pools(NULL);
  4899. }
  4900. static bool queue_request(void)
  4901. {
  4902. int ts, tq, maxq = opt_queue + mining_threads;
  4903. struct pool *pool, *cp;
  4904. struct workio_cmd *wc;
  4905. bool lagging;
  4906. ts = total_staged();
  4907. tq = global_queued();
  4908. if (ts && ts + tq >= maxq)
  4909. return true;
  4910. cp = current_pool();
  4911. lagging = !opt_fail_only && cp->lagging && !ts && cp->queued >= maxq;
  4912. if (!lagging && cp->staged + cp->queued >= maxq)
  4913. return true;
  4914. pool = select_pool(lagging);
  4915. if (pool->staged + pool->queued >= maxq)
  4916. return true;
  4917. /* fill out work request message */
  4918. wc = calloc(1, sizeof(*wc));
  4919. if (unlikely(!wc)) {
  4920. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  4921. return false;
  4922. }
  4923. wc->cmd = WC_GET_WORK;
  4924. wc->pool = pool;
  4925. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  4926. /* send work request to workio thread */
  4927. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4928. applog(LOG_ERR, "Failed to tq_push in queue_request");
  4929. workio_cmd_free(wc);
  4930. return false;
  4931. }
  4932. inc_queued(pool);
  4933. return true;
  4934. }
  4935. static struct work *hash_pop(const struct timespec *abstime)
  4936. {
  4937. struct work *work = NULL, *tmp;
  4938. int rc = 0, hc;
  4939. mutex_lock(stgd_lock);
  4940. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  4941. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  4942. hc = HASH_COUNT(staged_work);
  4943. if (likely(hc)) {
  4944. /* Find clone work if possible, to allow masters to be reused */
  4945. if (hc > staged_rollable) {
  4946. HASH_ITER(hh, staged_work, work, tmp) {
  4947. if (!work_rollable(work))
  4948. break;
  4949. }
  4950. } else
  4951. work = staged_work;
  4952. HASH_DEL(staged_work, work);
  4953. work->pool->staged--;
  4954. if (work_rollable(work))
  4955. staged_rollable--;
  4956. }
  4957. mutex_unlock(stgd_lock);
  4958. queue_request();
  4959. return work;
  4960. }
  4961. static bool reuse_work(struct work *work, struct pool *pool)
  4962. {
  4963. if (pool->has_stratum) {
  4964. if (!pool->stratum_active)
  4965. return false;
  4966. applog(LOG_DEBUG, "Reusing stratum work");
  4967. gen_stratum_work(pool, work);;
  4968. return true;
  4969. }
  4970. if (can_roll(work) && should_roll(work)) {
  4971. roll_work(work);
  4972. return true;
  4973. }
  4974. return false;
  4975. }
  4976. /* Clones work by rolling it if possible, and returning a clone instead of the
  4977. * original work item which gets staged again to possibly be rolled again in
  4978. * the future */
  4979. static struct work *clone_work(struct work *work)
  4980. {
  4981. int mrs = mining_threads + opt_queue - total_staged();
  4982. struct work *work_clone;
  4983. bool cloned;
  4984. if (mrs < 1)
  4985. return work;
  4986. cloned = false;
  4987. work_clone = make_clone(work);
  4988. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  4989. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  4990. if (unlikely(!stage_work(work_clone))) {
  4991. cloned = false;
  4992. break;
  4993. }
  4994. roll_work(work);
  4995. work_clone = make_clone(work);
  4996. /* Roll it again to prevent duplicates should this be used
  4997. * directly later on */
  4998. roll_work(work);
  4999. cloned = true;
  5000. }
  5001. if (cloned) {
  5002. stage_work(work);
  5003. return work_clone;
  5004. }
  5005. free_work(work_clone);
  5006. return work;
  5007. }
  5008. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  5009. {
  5010. unsigned char hash1[36];
  5011. sha2(data, len, hash1, false);
  5012. sha2(hash1, 32, hash, false);
  5013. }
  5014. /* Diff 1 is a 256 bit unsigned integer of
  5015. * 0x00000000ffff0000000000000000000000000000000000000000000000000000
  5016. * so we use a big endian 64 bit unsigned integer centred on the 5th byte to
  5017. * cover a huge range of difficulty targets, though not all 256 bits' worth */
  5018. static void set_work_target(struct work *work, int diff)
  5019. {
  5020. unsigned char rtarget[36], target[36];
  5021. uint64_t *data64, h64;
  5022. h64 = diffone;
  5023. h64 /= (uint64_t)diff;
  5024. memset(rtarget, 0, 32);
  5025. data64 = (uint64_t *)(rtarget + 4);
  5026. *data64 = htobe64(h64);
  5027. swab256(target, rtarget);
  5028. if (opt_debug) {
  5029. char *htarget = bin2hex(target, 32);
  5030. applog(LOG_DEBUG, "Generated target %s", htarget);
  5031. free(htarget);
  5032. }
  5033. memcpy(work->target, target, 32);
  5034. }
  5035. /* Generates stratum based work based on the most recent notify information
  5036. * from the pool. This will keep generating work while a pool is down so we use
  5037. * other means to detect when the pool has died in stratum_thread */
  5038. static void gen_stratum_work(struct pool *pool, struct work *work)
  5039. {
  5040. unsigned char *coinbase, merkle_root[36], merkle_sha[68], *merkle_hash;
  5041. char header[260], hash1[132], *nonce2;
  5042. int len, cb1_len, n1_len, cb2_len, i;
  5043. uint32_t *data32, *swap32;
  5044. memset(work->job_id, 0, 64);
  5045. memset(work->nonce2, 0, 64);
  5046. memset(work->ntime, 0, 16);
  5047. mutex_lock(&pool->pool_lock);
  5048. /* Generate coinbase */
  5049. nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  5050. pool->nonce2++;
  5051. cb1_len = strlen(pool->swork.coinbase1) / 2;
  5052. n1_len = strlen(pool->nonce1) / 2;
  5053. cb2_len = strlen(pool->swork.coinbase2) / 2;
  5054. len = cb1_len + n1_len + pool->n2size + cb2_len;
  5055. coinbase = alloca(len + 1);
  5056. hex2bin(coinbase, pool->swork.coinbase1, cb1_len);
  5057. hex2bin(coinbase + cb1_len, pool->nonce1, n1_len);
  5058. hex2bin(coinbase + cb1_len + n1_len, nonce2, pool->n2size);
  5059. hex2bin(coinbase + cb1_len + n1_len + pool->n2size, pool->swork.coinbase2, cb2_len);
  5060. /* Generate merkle root */
  5061. gen_hash(coinbase, merkle_root, len);
  5062. memcpy(merkle_sha, merkle_root, 32);
  5063. for (i = 0; i < pool->swork.merkles; i++) {
  5064. unsigned char merkle_bin[36];
  5065. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  5066. memcpy(merkle_sha + 32, merkle_bin, 32);
  5067. gen_hash(merkle_sha, merkle_root, 64);
  5068. memcpy(merkle_sha, merkle_root, 32);
  5069. }
  5070. data32 = (uint32_t *)merkle_sha;
  5071. swap32 = (uint32_t *)merkle_root;
  5072. for (i = 0; i < 32 / 4; i++)
  5073. swap32[i] = swab32(data32[i]);
  5074. merkle_hash = (unsigned char *)bin2hex((const unsigned char *)merkle_root, 32);
  5075. sprintf(header, "%s", pool->swork.bbversion);
  5076. strcat(header, pool->swork.prev_hash);
  5077. strcat(header, (char *)merkle_hash);
  5078. strcat(header, pool->swork.ntime);
  5079. strcat(header, pool->swork.nbit);
  5080. strcat(header, "00000000"); /* nonce */
  5081. strcat(header, "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000");
  5082. /* Store the stratum work diff to check it still matches the pool's
  5083. * stratum diff when submitting shares */
  5084. work->sdiff = pool->swork.diff;
  5085. /* Copy parameters required for share submission */
  5086. sprintf(work->job_id, "%s", pool->swork.job_id);
  5087. sprintf(work->nonce2, "%s", nonce2);
  5088. sprintf(work->ntime, "%s", pool->swork.ntime);
  5089. free(nonce2);
  5090. mutex_unlock(&pool->pool_lock);
  5091. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  5092. applog(LOG_DEBUG, "Generated stratum header %s", header);
  5093. applog(LOG_DEBUG, "Work job_id %s nonce2 %s ntime %s", work->job_id, work->nonce2, work->ntime);
  5094. free(merkle_hash);
  5095. /* Convert hex data to binary data for work */
  5096. if (unlikely(!hex2bin(work->data, header, 128)))
  5097. quit(1, "Failed to convert header to data in gen_stratum_work");
  5098. calc_midstate(work);
  5099. sprintf(hash1, "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000");
  5100. if (unlikely(!hex2bin(work->hash1, hash1, 64)))
  5101. quit(1, "Failed to convert hash1 in gen_stratum_work");
  5102. set_work_target(work, work->sdiff);
  5103. local_work++;
  5104. work->pool = pool;
  5105. work->stratum = true;
  5106. work->blk.nonce = 0;
  5107. work->id = total_work++;
  5108. work->longpoll = false;
  5109. work->getwork_mode = GETWORK_MODE_STRATUM;
  5110. work->work_restart_id = work->pool->work_restart_id;
  5111. calc_diff(work, work->sdiff);
  5112. gettimeofday(&work->tv_staged, NULL);
  5113. }
  5114. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  5115. {
  5116. struct timespec abstime = {0, 0};
  5117. struct work *work_heap;
  5118. struct timeval now;
  5119. struct pool *pool;
  5120. /* Tell the watchdog thread this thread is waiting on getwork and
  5121. * should not be restarted */
  5122. thread_reportout(thr);
  5123. if (opt_benchmark) {
  5124. get_benchmark_work(work);
  5125. goto out;
  5126. }
  5127. retry:
  5128. pool = current_pool();
  5129. if (reuse_work(work, pool))
  5130. goto out;
  5131. /* If we were unable to reuse work from a stratum pool, it implies the
  5132. * pool is inactive and unless we have another pool to grab work from
  5133. * we can only wait till it comes alive or another pool comes online */
  5134. if (pool->has_stratum) {
  5135. sleep(5);
  5136. goto retry;
  5137. }
  5138. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  5139. struct cgpu_info *cgpu = thr->cgpu;
  5140. bool stalled = true;
  5141. int i;
  5142. /* Check to see if all the threads on the device that called
  5143. * get_work are waiting on work and only consider the pool
  5144. * lagging if true */
  5145. for (i = 0; i < cgpu->threads; i++) {
  5146. if (!cgpu->thr[i]->getwork) {
  5147. stalled = false;
  5148. break;
  5149. }
  5150. }
  5151. if (stalled && !pool_tset(pool, &pool->lagging)) {
  5152. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  5153. pool->getfail_occasions++;
  5154. total_go++;
  5155. }
  5156. }
  5157. gettimeofday(&now, NULL);
  5158. abstime.tv_sec = now.tv_sec + 60;
  5159. applog(LOG_DEBUG, "Popping work from get queue to get work");
  5160. keepwaiting:
  5161. /* wait for 1st response, or get cached response */
  5162. work_heap = hash_pop(&abstime);
  5163. if (unlikely(!work_heap)) {
  5164. /* Attempt to switch pools if this one times out */
  5165. pool_died(pool);
  5166. if (pool == current_pool())
  5167. goto keepwaiting;
  5168. goto retry;
  5169. }
  5170. if (stale_work(work_heap, false)) {
  5171. discard_work(work_heap);
  5172. goto retry;
  5173. }
  5174. pool = work_heap->pool;
  5175. /* If we make it here we have succeeded in getting fresh work */
  5176. if (!work_heap->mined) {
  5177. /* Only clear the lagging flag if we are staging them at a
  5178. * rate faster then we're using them */
  5179. if (pool->lagging && total_staged())
  5180. pool_tclear(pool, &pool->lagging);
  5181. if (pool_tclear(pool, &pool->idle))
  5182. pool_resus(pool);
  5183. }
  5184. memcpy(work, work_heap, sizeof(struct work));
  5185. free(work_heap);
  5186. out:
  5187. work->thr_id = thr_id;
  5188. thread_reportin(thr);
  5189. work->mined = true;
  5190. }
  5191. bool submit_work_sync(struct thr_info *thr, const struct work *work_in, struct timeval *tv_work_found)
  5192. {
  5193. struct workio_cmd *wc;
  5194. /* fill out work request message */
  5195. wc = calloc(1, sizeof(*wc));
  5196. if (unlikely(!wc)) {
  5197. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  5198. return false;
  5199. }
  5200. wc->work = make_work();
  5201. wc->cmd = WC_SUBMIT_WORK;
  5202. wc->thr = thr;
  5203. workcpy(wc->work, work_in);
  5204. if (tv_work_found)
  5205. memcpy(&(wc->work->tv_work_found), tv_work_found, sizeof(struct timeval));
  5206. applog(LOG_DEBUG, "Pushing submit work to work thread");
  5207. /* send solution to workio thread */
  5208. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  5209. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  5210. goto err_out;
  5211. }
  5212. return true;
  5213. err_out:
  5214. workio_cmd_free(wc);
  5215. return false;
  5216. }
  5217. enum test_nonce2_result hashtest2(struct work *work, bool checktarget)
  5218. {
  5219. uint32_t *data32 = (uint32_t *)(work->data);
  5220. unsigned char swap[128];
  5221. uint32_t *swap32 = (uint32_t *)swap;
  5222. unsigned char hash1[32];
  5223. unsigned char hash2[32];
  5224. uint32_t *hash2_32 = (uint32_t *)hash2;
  5225. struct pool *pool = work->pool;
  5226. int diff;
  5227. swap32yes(swap32, data32, 80 / 4);
  5228. sha2(swap, 80, hash1, false);
  5229. sha2(hash1, 32, hash2, false);
  5230. if (hash2_32[7] != 0)
  5231. return TNR_BAD;
  5232. if (!checktarget)
  5233. return TNR_GOOD;
  5234. swap32yes(hash2_32, hash2_32, 32 / 4);
  5235. memcpy((void*)work->hash, hash2, 32);
  5236. if (work->stratum) {
  5237. mutex_lock(&pool->pool_lock);
  5238. diff = pool->swork.diff;
  5239. mutex_unlock(&pool->pool_lock);
  5240. if (unlikely(work->sdiff != diff)) {
  5241. applog(LOG_DEBUG, "Share needs retargetting to match pool");
  5242. set_work_target(work, diff);
  5243. }
  5244. }
  5245. if (!fulltest(work->hash, work->target))
  5246. return TNR_HIGH;
  5247. return TNR_GOOD;
  5248. }
  5249. enum test_nonce2_result _test_nonce2(struct work *work, uint32_t nonce, bool checktarget)
  5250. {
  5251. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  5252. *work_nonce = nonce;
  5253. #ifdef USE_SCRYPT
  5254. if (opt_scrypt) {
  5255. if (!scrypt_test(work->data, work->target, nonce))
  5256. return TNR_BAD;
  5257. return TNR_GOOD;
  5258. }
  5259. #endif
  5260. return hashtest2(work, checktarget);
  5261. }
  5262. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  5263. {
  5264. struct timeval tv_work_found;
  5265. gettimeofday(&tv_work_found, NULL);
  5266. total_diff1++;
  5267. thr->cgpu->diff1++;
  5268. work->pool->diff1++;
  5269. /* Do one last check before attempting to submit the work */
  5270. /* Side effect: sets work->data for us */
  5271. switch (test_nonce2(work, nonce)) {
  5272. case TNR_BAD:
  5273. {
  5274. struct cgpu_info *cgpu = thr->cgpu;
  5275. struct device_api *dapi = cgpu->api;
  5276. ++hw_errors;
  5277. ++thr->cgpu->hw_errors;
  5278. if (!(dapi->hw_error && dapi->hw_error(thr)))
  5279. applog(LOG_WARNING, "%s %u: invalid nonce - HW error",
  5280. dapi->name, cgpu->device_id);
  5281. return false;
  5282. }
  5283. case TNR_HIGH:
  5284. // Share above target, normal
  5285. return true;
  5286. case TNR_GOOD:
  5287. break;
  5288. }
  5289. return submit_work_sync(thr, work, &tv_work_found);
  5290. }
  5291. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  5292. {
  5293. if (wdiff->tv_sec > opt_scantime ||
  5294. work->blk.nonce >= MAXTHREADS - hashes ||
  5295. hashes >= 0xfffffffe ||
  5296. stale_work(work, false))
  5297. return true;
  5298. return false;
  5299. }
  5300. static void mt_disable(struct thr_info *mythr, const int thr_id,
  5301. const struct device_api *api)
  5302. {
  5303. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  5304. mythr->rolling = mythr->cgpu->rolling = 0;
  5305. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  5306. thread_reportout(mythr);
  5307. do {
  5308. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  5309. } while (mythr->pause);
  5310. thread_reportin(mythr);
  5311. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  5312. if (api->thread_enable)
  5313. api->thread_enable(mythr);
  5314. }
  5315. void *miner_thread(void *userdata)
  5316. {
  5317. struct thr_info *mythr = userdata;
  5318. const int thr_id = mythr->id;
  5319. struct cgpu_info *cgpu = mythr->cgpu;
  5320. const struct device_api *api = cgpu->api;
  5321. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  5322. struct cgminer_stats *pool_stats;
  5323. struct timeval getwork_start;
  5324. {
  5325. char thrname[16];
  5326. sprintf(thrname, "bfg-miner-%s%d", api->name, cgpu->device_id);
  5327. rename_thr(thrname);
  5328. }
  5329. /* Try to cycle approximately 5 times before each log update */
  5330. const long cycle = opt_log_interval / 5 ? : 1;
  5331. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  5332. struct timeval diff, sdiff, wdiff = {0, 0};
  5333. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  5334. int64_t hashes_done = 0;
  5335. int64_t hashes;
  5336. bool scanhash_working = true;
  5337. struct work *work = make_work();
  5338. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  5339. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5340. gettimeofday(&getwork_start, NULL);
  5341. if (api->thread_init && !api->thread_init(mythr)) {
  5342. cgpu->device_last_not_well = time(NULL);
  5343. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  5344. cgpu->thread_fail_init_count++;
  5345. goto out;
  5346. }
  5347. thread_reportout(mythr);
  5348. applog(LOG_DEBUG, "Popping ping in miner thread");
  5349. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  5350. sdiff.tv_sec = sdiff.tv_usec = 0;
  5351. gettimeofday(&tv_lastupdate, NULL);
  5352. while (1) {
  5353. mythr->work_restart = false;
  5354. if (api->free_work && likely(work->pool))
  5355. api->free_work(mythr, work);
  5356. get_work(work, mythr, thr_id);
  5357. cgpu->new_work = true;
  5358. gettimeofday(&tv_workstart, NULL);
  5359. work->blk.nonce = 0;
  5360. cgpu->max_hashes = 0;
  5361. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  5362. applog(LOG_ERR, "work prepare failed, exiting "
  5363. "mining thread %d", thr_id);
  5364. break;
  5365. }
  5366. do {
  5367. gettimeofday(&tv_start, NULL);
  5368. timersub(&tv_start, &getwork_start, &getwork_start);
  5369. timeradd(&getwork_start,
  5370. &(dev_stats->getwork_wait),
  5371. &(dev_stats->getwork_wait));
  5372. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  5373. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  5374. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  5375. }
  5376. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  5377. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  5378. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  5379. }
  5380. dev_stats->getwork_calls++;
  5381. pool_stats = &(work->pool->cgminer_stats);
  5382. timeradd(&getwork_start,
  5383. &(pool_stats->getwork_wait),
  5384. &(pool_stats->getwork_wait));
  5385. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  5386. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  5387. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  5388. }
  5389. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  5390. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  5391. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  5392. }
  5393. pool_stats->getwork_calls++;
  5394. gettimeofday(&(work->tv_work_start), NULL);
  5395. thread_reportin(mythr);
  5396. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  5397. thread_reportin(mythr);
  5398. gettimeofday(&getwork_start, NULL);
  5399. if (unlikely(hashes == -1)) {
  5400. time_t now = time(NULL);
  5401. if (difftime(now, cgpu->device_last_not_well) > 1.) {
  5402. cgpu->device_last_not_well = time(NULL);
  5403. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  5404. cgpu->thread_zero_hash_count++;
  5405. }
  5406. if (scanhash_working && opt_restart) {
  5407. applog(LOG_ERR, "%s %u failure, attempting to reinitialize", api->name, cgpu->device_id);
  5408. scanhash_working = false;
  5409. cgpu->reinit_backoff = 5.2734375;
  5410. hashes = 0;
  5411. } else {
  5412. applog(LOG_ERR, "%s %u failure, disabling!", api->name, cgpu->device_id);
  5413. cgpu->deven = DEV_RECOVER_ERR;
  5414. goto disabled;
  5415. }
  5416. }
  5417. else
  5418. scanhash_working = true;
  5419. hashes_done += hashes;
  5420. if (hashes > cgpu->max_hashes)
  5421. cgpu->max_hashes = hashes;
  5422. gettimeofday(&tv_end, NULL);
  5423. timersub(&tv_end, &tv_start, &diff);
  5424. sdiff.tv_sec += diff.tv_sec;
  5425. sdiff.tv_usec += diff.tv_usec;
  5426. if (sdiff.tv_usec > 1000000) {
  5427. ++sdiff.tv_sec;
  5428. sdiff.tv_usec -= 1000000;
  5429. }
  5430. timersub(&tv_end, &tv_workstart, &wdiff);
  5431. if (unlikely((long)sdiff.tv_sec < cycle)) {
  5432. int mult;
  5433. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  5434. continue;
  5435. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  5436. mult *= cycle;
  5437. if (max_nonce > (0xffffffff * 0x400) / mult)
  5438. max_nonce = 0xffffffff;
  5439. else
  5440. max_nonce = (max_nonce * mult) / 0x400;
  5441. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  5442. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  5443. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  5444. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  5445. timersub(&tv_end, &tv_lastupdate, &diff);
  5446. if (diff.tv_sec >= opt_log_interval) {
  5447. hashmeter(thr_id, &diff, hashes_done);
  5448. hashes_done = 0;
  5449. tv_lastupdate = tv_end;
  5450. }
  5451. if (unlikely(mythr->work_restart)) {
  5452. /* Apart from device_thread 0, we stagger the
  5453. * starting of every next thread to try and get
  5454. * all devices busy before worrying about
  5455. * getting work for their extra threads */
  5456. if (!primary) {
  5457. struct timespec rgtp;
  5458. rgtp.tv_sec = 0;
  5459. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  5460. nanosleep(&rgtp, NULL);
  5461. }
  5462. break;
  5463. }
  5464. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  5465. disabled:
  5466. mt_disable(mythr, thr_id, api);
  5467. sdiff.tv_sec = sdiff.tv_usec = 0;
  5468. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  5469. }
  5470. out:
  5471. if (api->thread_shutdown)
  5472. api->thread_shutdown(mythr);
  5473. thread_reportin(mythr);
  5474. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  5475. tq_freeze(mythr->q);
  5476. return NULL;
  5477. }
  5478. enum {
  5479. STAT_SLEEP_INTERVAL = 1,
  5480. STAT_CTR_INTERVAL = 10000000,
  5481. FAILURE_INTERVAL = 30,
  5482. };
  5483. /* Stage another work item from the work returned in a longpoll */
  5484. 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)
  5485. {
  5486. bool rc;
  5487. rc = work_decode(json_object_get(val, "result"), work);
  5488. if (unlikely(!rc)) {
  5489. applog(LOG_ERR, "Could not convert longpoll data to work");
  5490. free_work(work);
  5491. return;
  5492. }
  5493. work->pool = pool;
  5494. work->rolltime = rolltime;
  5495. work->longpoll = true;
  5496. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  5497. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  5498. work->getwork_mode = GETWORK_MODE_LP;
  5499. calc_diff(work, 0);
  5500. if (pool->enabled == POOL_REJECTING)
  5501. work->mandatory = true;
  5502. /* We'll be checking this work item twice, but we already know it's
  5503. * from a new block so explicitly force the new block detection now
  5504. * rather than waiting for it to hit the stage thread. This also
  5505. * allows testwork to know whether LP discovered the block or not. */
  5506. test_work_current(work);
  5507. /* Don't use backup LPs as work if we have failover-only enabled. Use
  5508. * the longpoll work from a pool that has been rejecting shares as a
  5509. * way to detect when the pool has recovered.
  5510. */
  5511. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  5512. free_work(work);
  5513. return;
  5514. }
  5515. work = clone_work(work);
  5516. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  5517. if (unlikely(!stage_work(work)))
  5518. free_work(work);
  5519. else
  5520. applog(LOG_DEBUG, "Converted longpoll data to work");
  5521. }
  5522. /* If we want longpoll, enable it for the chosen default pool, or, if
  5523. * the pool does not support longpoll, find the first one that does
  5524. * and use its longpoll support */
  5525. static struct pool *select_longpoll_pool(struct pool *cp)
  5526. {
  5527. int i;
  5528. if (cp->lp_url)
  5529. return cp;
  5530. for (i = 0; i < total_pools; i++) {
  5531. struct pool *pool = pools[i];
  5532. if (pool->lp_url)
  5533. return pool;
  5534. }
  5535. return NULL;
  5536. }
  5537. /* This will make the longpoll thread wait till it's the current pool, or it
  5538. * has been flagged as rejecting, before attempting to open any connections.
  5539. */
  5540. static void wait_lpcurrent(struct pool *pool)
  5541. {
  5542. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  5543. return;
  5544. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  5545. mutex_lock(&lp_lock);
  5546. pthread_cond_wait(&lp_cond, &lp_lock);
  5547. mutex_unlock(&lp_lock);
  5548. }
  5549. }
  5550. static curl_socket_t save_curl_socket(void *vpool, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr) {
  5551. struct pool *pool = vpool;
  5552. curl_socket_t sock = socket(addr->family, addr->socktype, addr->protocol);
  5553. pool->lp_socket = sock;
  5554. return sock;
  5555. }
  5556. static void *longpoll_thread(void *userdata)
  5557. {
  5558. struct pool *cp = (struct pool *)userdata;
  5559. /* This *pool is the source of the actual longpoll, not the pool we've
  5560. * tied it to */
  5561. struct pool *pool = NULL;
  5562. struct timeval start, reply, end;
  5563. CURL *curl = NULL;
  5564. int failures = 0;
  5565. int rolltime;
  5566. rename_thr("bfg-longpoll");
  5567. curl = curl_easy_init();
  5568. if (unlikely(!curl)) {
  5569. applog(LOG_ERR, "CURL initialisation failed");
  5570. goto out;
  5571. }
  5572. retry_pool:
  5573. pool = select_longpoll_pool(cp);
  5574. if (!pool) {
  5575. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  5576. while (!pool) {
  5577. sleep(60);
  5578. pool = select_longpoll_pool(cp);
  5579. }
  5580. }
  5581. /* Any longpoll from any pool is enough for this to be true */
  5582. have_longpoll = true;
  5583. wait_lpcurrent(cp);
  5584. if (cp == pool)
  5585. applog(LOG_WARNING, "Long-polling activated via %s (%s)", pool->lp_url, pool_protocol_name(pool->lp_proto));
  5586. else
  5587. applog(LOG_WARNING, "Long-polling activated for pool %s via %s (%s)", cp->rpc_url, pool->lp_url, pool_protocol_name(pool->lp_proto));
  5588. while (42) {
  5589. json_t *val, *soval;
  5590. struct work *work = make_work();
  5591. work->pool = pool;
  5592. char *rpc_req;
  5593. rpc_req = prepare_rpc_req(work, pool->lp_proto, pool->lp_id);
  5594. if (!rpc_req)
  5595. goto lpfail;
  5596. wait_lpcurrent(cp);
  5597. gettimeofday(&start, NULL);
  5598. /* Longpoll connections can be persistent for a very long time
  5599. * and any number of issues could have come up in the meantime
  5600. * so always establish a fresh connection instead of relying on
  5601. * a persistent one. */
  5602. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  5603. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, save_curl_socket);
  5604. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  5605. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  5606. false, true, &rolltime, pool, false);
  5607. pool->lp_socket = CURL_SOCKET_BAD;
  5608. gettimeofday(&reply, NULL);
  5609. free(rpc_req);
  5610. if (likely(val)) {
  5611. soval = json_object_get(json_object_get(val, "result"), "submitold");
  5612. if (soval)
  5613. pool->submit_old = json_is_true(soval);
  5614. else
  5615. pool->submit_old = false;
  5616. convert_to_work(val, rolltime, pool, work, &start, &reply);
  5617. failures = 0;
  5618. json_decref(val);
  5619. } else {
  5620. /* Some pools regularly drop the longpoll request so
  5621. * only see this as longpoll failure if it happens
  5622. * immediately and just restart it the rest of the
  5623. * time. */
  5624. gettimeofday(&end, NULL);
  5625. free_work(work);
  5626. if (end.tv_sec - start.tv_sec > 30)
  5627. continue;
  5628. if (failures == 1)
  5629. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  5630. lpfail:
  5631. sleep(30);
  5632. }
  5633. if (pool != cp) {
  5634. pool = select_longpoll_pool(cp);
  5635. if (unlikely(!pool))
  5636. goto retry_pool;
  5637. }
  5638. if (unlikely(pool->removed))
  5639. break;
  5640. }
  5641. out:
  5642. if (curl)
  5643. curl_easy_cleanup(curl);
  5644. return NULL;
  5645. }
  5646. static void stop_longpoll(void)
  5647. {
  5648. int i;
  5649. want_longpoll = false;
  5650. for (i = 0; i < total_pools; ++i)
  5651. {
  5652. struct pool *pool = pools[i];
  5653. if (unlikely(!pool->lp_started))
  5654. continue;
  5655. pool->lp_started = false;
  5656. pthread_cancel(pool->longpoll_thread);
  5657. }
  5658. have_longpoll = false;
  5659. }
  5660. static void start_longpoll(void)
  5661. {
  5662. int i;
  5663. want_longpoll = true;
  5664. for (i = 0; i < total_pools; ++i)
  5665. {
  5666. struct pool *pool = pools[i];
  5667. if (unlikely(pool->removed || pool->lp_started || !pool->lp_url))
  5668. continue;
  5669. pool->lp_started = true;
  5670. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5671. quit(1, "Failed to create pool longpoll thread");
  5672. }
  5673. }
  5674. void reinit_device(struct cgpu_info *cgpu)
  5675. {
  5676. if (cgpu->api->reinit_device)
  5677. cgpu->api->reinit_device(cgpu);
  5678. }
  5679. static struct timeval rotate_tv;
  5680. /* We reap curls if they are unused for over a minute */
  5681. static void reap_curl(struct pool *pool)
  5682. {
  5683. struct curl_ent *ent, *iter;
  5684. struct timeval now;
  5685. int reaped = 0;
  5686. gettimeofday(&now, NULL);
  5687. mutex_lock(&pool->pool_lock);
  5688. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  5689. if (pool->curls < 2)
  5690. break;
  5691. if (now.tv_sec - ent->tv.tv_sec > 300) {
  5692. reaped++;
  5693. pool->curls--;
  5694. list_del(&ent->node);
  5695. curl_easy_cleanup(ent->curl);
  5696. free(ent);
  5697. }
  5698. }
  5699. mutex_unlock(&pool->pool_lock);
  5700. if (reaped)
  5701. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  5702. }
  5703. static void *watchpool_thread(void __maybe_unused *userdata)
  5704. {
  5705. int intervals = 0;
  5706. rename_thr("bfg-watchpool");
  5707. while (42) {
  5708. struct timeval now;
  5709. int i;
  5710. if (++intervals > 20)
  5711. intervals = 0;
  5712. gettimeofday(&now, NULL);
  5713. for (i = 0; i < total_pools; i++) {
  5714. struct pool *pool = pools[i];
  5715. if (!opt_benchmark)
  5716. reap_curl(pool);
  5717. if (pool->enabled == POOL_DISABLED || pool->has_stratum)
  5718. continue;
  5719. /* Test pool is idle once every minute */
  5720. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  5721. gettimeofday(&pool->tv_idle, NULL);
  5722. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  5723. pool_resus(pool);
  5724. }
  5725. /* Get a rolling utility per pool over 10 mins */
  5726. if (intervals > 19) {
  5727. int shares = pool->diff1 - pool->last_shares;
  5728. pool->last_shares = pool->diff1;
  5729. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  5730. pool->shares = pool->utility;
  5731. }
  5732. }
  5733. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  5734. gettimeofday(&rotate_tv, NULL);
  5735. switch_pools(NULL);
  5736. }
  5737. sleep(30);
  5738. }
  5739. return NULL;
  5740. }
  5741. void device_recovered(struct cgpu_info *cgpu)
  5742. {
  5743. struct thr_info *thr;
  5744. int j;
  5745. cgpu->deven = DEV_ENABLED;
  5746. for (j = 0; j < cgpu->threads; ++j) {
  5747. thr = cgpu->thr[j];
  5748. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5749. tq_push(thr->q, &ping);
  5750. }
  5751. }
  5752. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  5753. * the screen at regular intervals, and restarts threads if they appear to have
  5754. * died. */
  5755. #define WATCHDOG_INTERVAL 3
  5756. #define WATCHDOG_SICK_TIME 60
  5757. #define WATCHDOG_DEAD_TIME 600
  5758. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  5759. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  5760. static void *watchdog_thread(void __maybe_unused *userdata)
  5761. {
  5762. const unsigned int interval = WATCHDOG_INTERVAL;
  5763. struct timeval zero_tv;
  5764. rename_thr("bfg-watchdog");
  5765. memset(&zero_tv, 0, sizeof(struct timeval));
  5766. gettimeofday(&rotate_tv, NULL);
  5767. while (1) {
  5768. int i;
  5769. struct timeval now;
  5770. sleep(interval);
  5771. discard_stale();
  5772. hashmeter(-1, &zero_tv, 0);
  5773. #ifdef HAVE_CURSES
  5774. if (curses_active_locked()) {
  5775. change_logwinsize();
  5776. curses_print_status();
  5777. for (i = 0; i < mining_threads; i++)
  5778. curses_print_devstatus(i);
  5779. touchwin(statuswin);
  5780. wrefresh(statuswin);
  5781. touchwin(logwin);
  5782. wrefresh(logwin);
  5783. unlock_curses();
  5784. }
  5785. #endif
  5786. gettimeofday(&now, NULL);
  5787. if (!sched_paused && !should_run()) {
  5788. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  5789. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5790. if (!schedstart.enable) {
  5791. quit(0, "Terminating execution as planned");
  5792. break;
  5793. }
  5794. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  5795. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5796. sched_paused = true;
  5797. for (i = 0; i < mining_threads; i++) {
  5798. struct thr_info *thr;
  5799. thr = &thr_info[i];
  5800. thr->pause = true;
  5801. }
  5802. } else if (sched_paused && should_run()) {
  5803. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  5804. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  5805. if (schedstop.enable)
  5806. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  5807. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  5808. sched_paused = false;
  5809. for (i = 0; i < mining_threads; i++) {
  5810. struct thr_info *thr;
  5811. thr = &thr_info[i];
  5812. /* Don't touch disabled devices */
  5813. if (thr->cgpu->deven == DEV_DISABLED)
  5814. continue;
  5815. thr->pause = false;
  5816. tq_push(thr->q, &ping);
  5817. }
  5818. }
  5819. for (i = 0; i < total_devices; ++i) {
  5820. struct cgpu_info *cgpu = devices[i];
  5821. struct thr_info *thr = cgpu->thr[0];
  5822. enum dev_enable *denable;
  5823. char dev_str[8];
  5824. int gpu;
  5825. if (cgpu->api->get_stats)
  5826. cgpu->api->get_stats(cgpu);
  5827. gpu = cgpu->device_id;
  5828. denable = &cgpu->deven;
  5829. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  5830. #ifdef HAVE_ADL
  5831. if (adl_active && cgpu->has_adl)
  5832. gpu_autotune(gpu, denable);
  5833. if (opt_debug && cgpu->has_adl) {
  5834. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  5835. float temp = 0, vddc = 0;
  5836. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  5837. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  5838. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  5839. }
  5840. #endif
  5841. /* Thread is disabled */
  5842. if (*denable == DEV_DISABLED)
  5843. continue;
  5844. else
  5845. if (*denable == DEV_RECOVER_ERR) {
  5846. if (opt_restart && difftime(time(NULL), cgpu->device_last_not_well) > cgpu->reinit_backoff) {
  5847. applog(LOG_NOTICE, "Attempting to reinitialize %s %u",
  5848. cgpu->api->name, cgpu->device_id);
  5849. if (cgpu->reinit_backoff < 300)
  5850. cgpu->reinit_backoff *= 2;
  5851. device_recovered(cgpu);
  5852. }
  5853. continue;
  5854. }
  5855. else
  5856. if (*denable == DEV_RECOVER) {
  5857. if (opt_restart && cgpu->temp < cgpu->targettemp) {
  5858. applog(LOG_NOTICE, "%s %u recovered to temperature below target, re-enabling",
  5859. cgpu->api->name, cgpu->device_id);
  5860. device_recovered(cgpu);
  5861. }
  5862. cgpu->device_last_not_well = time(NULL);
  5863. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5864. continue;
  5865. }
  5866. else
  5867. if (cgpu->temp > cgpu->cutofftemp)
  5868. {
  5869. applog(LOG_WARNING, "%s %u hit thermal cutoff limit, disabling!",
  5870. cgpu->api->name, cgpu->device_id);
  5871. *denable = DEV_RECOVER;
  5872. cgpu->device_last_not_well = time(NULL);
  5873. cgpu->device_not_well_reason = REASON_DEV_THERMAL_CUTOFF;
  5874. ++cgpu->dev_thermal_cutoff_count;
  5875. }
  5876. if (thr->getwork) {
  5877. if (cgpu->status == LIFE_WELL && thr->getwork < now.tv_sec - opt_log_interval) {
  5878. int thrid;
  5879. bool cgpu_idle = true;
  5880. thr->rolling = 0;
  5881. for (thrid = 0; thrid < cgpu->threads; ++thrid)
  5882. if (!cgpu->thr[thrid]->getwork)
  5883. cgpu_idle = false;
  5884. if (cgpu_idle) {
  5885. cgpu->rolling = 0;
  5886. cgpu->status = LIFE_WAIT;
  5887. }
  5888. }
  5889. continue;
  5890. }
  5891. else if (cgpu->status == LIFE_WAIT)
  5892. cgpu->status = LIFE_WELL;
  5893. #ifdef WANT_CPUMINE
  5894. if (!strcmp(cgpu->api->dname, "cpu"))
  5895. continue;
  5896. #endif
  5897. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  5898. if (cgpu->status != LIFE_INIT)
  5899. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  5900. cgpu->status = LIFE_WELL;
  5901. cgpu->device_last_well = time(NULL);
  5902. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  5903. thr->rolling = cgpu->rolling = 0;
  5904. cgpu->status = LIFE_SICK;
  5905. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  5906. gettimeofday(&thr->sick, NULL);
  5907. cgpu->device_last_not_well = time(NULL);
  5908. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  5909. cgpu->dev_sick_idle_60_count++;
  5910. #ifdef HAVE_ADL
  5911. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5912. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  5913. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  5914. } else
  5915. #endif
  5916. if (opt_restart) {
  5917. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  5918. reinit_device(cgpu);
  5919. }
  5920. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  5921. cgpu->status = LIFE_DEAD;
  5922. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  5923. gettimeofday(&thr->sick, NULL);
  5924. cgpu->device_last_not_well = time(NULL);
  5925. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  5926. cgpu->dev_dead_idle_600_count++;
  5927. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  5928. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  5929. /* Attempt to restart a GPU that's sick or dead once every minute */
  5930. gettimeofday(&thr->sick, NULL);
  5931. #ifdef HAVE_ADL
  5932. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  5933. /* Again do not attempt to restart a device that may have hard hung */
  5934. } else
  5935. #endif
  5936. if (opt_restart)
  5937. reinit_device(cgpu);
  5938. }
  5939. }
  5940. }
  5941. return NULL;
  5942. }
  5943. static void log_print_status(struct cgpu_info *cgpu)
  5944. {
  5945. char logline[255];
  5946. get_statline(logline, cgpu);
  5947. applog(LOG_WARNING, "%s", logline);
  5948. }
  5949. static void print_summary(void)
  5950. {
  5951. struct timeval diff;
  5952. int hours, mins, secs, i;
  5953. double utility, efficiency = 0.0, work_util;
  5954. timersub(&total_tv_end, &total_tv_start, &diff);
  5955. hours = diff.tv_sec / 3600;
  5956. mins = (diff.tv_sec % 3600) / 60;
  5957. secs = diff.tv_sec % 60;
  5958. utility = total_accepted / total_secs * 60;
  5959. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  5960. work_util = total_diff1 / total_secs * 60;
  5961. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  5962. applog(LOG_WARNING, "Started at %s", datestamp);
  5963. if (total_pools == 1)
  5964. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  5965. #ifdef WANT_CPUMINE
  5966. if (opt_n_threads)
  5967. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  5968. #endif
  5969. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  5970. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  5971. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  5972. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  5973. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  5974. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  5975. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  5976. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  5977. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  5978. if (total_accepted || total_rejected)
  5979. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  5980. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  5981. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  5982. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  5983. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  5984. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  5985. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  5986. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  5987. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  5988. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  5989. if (total_pools > 1) {
  5990. for (i = 0; i < total_pools; i++) {
  5991. struct pool *pool = pools[i];
  5992. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  5993. if (pool->solved)
  5994. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  5995. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  5996. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  5997. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  5998. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  5999. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  6000. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  6001. if (pool->accepted || pool->rejected)
  6002. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  6003. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  6004. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  6005. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  6006. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  6007. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  6008. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  6009. }
  6010. }
  6011. applog(LOG_WARNING, "Summary of per device statistics:\n");
  6012. for (i = 0; i < total_devices; ++i)
  6013. log_print_status(devices[i]);
  6014. if (opt_shares)
  6015. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  6016. fflush(stdout);
  6017. fflush(stderr);
  6018. if (opt_shares > total_accepted)
  6019. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  6020. }
  6021. static void clean_up(void)
  6022. {
  6023. #ifdef HAVE_OPENCL
  6024. clear_adl(nDevs);
  6025. #endif
  6026. #ifdef HAVE_LIBUSB
  6027. libusb_exit(NULL);
  6028. #endif
  6029. gettimeofday(&total_tv_end, NULL);
  6030. #ifdef HAVE_CURSES
  6031. disable_curses();
  6032. #endif
  6033. if (!opt_realquiet && successful_connect)
  6034. print_summary();
  6035. if (opt_n_threads)
  6036. free(cpus);
  6037. curl_global_cleanup();
  6038. }
  6039. void quit(int status, const char *format, ...)
  6040. {
  6041. va_list ap;
  6042. clean_up();
  6043. if (format) {
  6044. va_start(ap, format);
  6045. vfprintf(stderr, format, ap);
  6046. va_end(ap);
  6047. }
  6048. fprintf(stderr, "\n");
  6049. fflush(stderr);
  6050. if (status) {
  6051. const char *ev = getenv("__BFGMINER_SEGFAULT_ERRQUIT");
  6052. if (unlikely(ev && ev[0] && ev[0] != '0')) {
  6053. const char **p = NULL;
  6054. // NOTE debugger can bypass with: p = &p
  6055. *p = format; // Segfault, hopefully dumping core
  6056. }
  6057. }
  6058. #if defined(unix)
  6059. if (forkpid > 0) {
  6060. kill(forkpid, SIGTERM);
  6061. forkpid = 0;
  6062. }
  6063. #endif
  6064. exit(status);
  6065. }
  6066. #ifdef HAVE_CURSES
  6067. char *curses_input(const char *query)
  6068. {
  6069. char *input;
  6070. echo();
  6071. input = malloc(255);
  6072. if (!input)
  6073. quit(1, "Failed to malloc input");
  6074. leaveok(logwin, false);
  6075. wlogprint("%s:\n", query);
  6076. wgetnstr(logwin, input, 255);
  6077. if (!strlen(input))
  6078. strcpy(input, "-1");
  6079. leaveok(logwin, true);
  6080. noecho();
  6081. return input;
  6082. }
  6083. #endif
  6084. void add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  6085. {
  6086. pool->rpc_url = url;
  6087. pool->rpc_user = user;
  6088. pool->rpc_pass = pass;
  6089. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6090. if (!pool->rpc_userpass)
  6091. quit(1, "Failed to malloc userpass");
  6092. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6093. enable_pool(pool);
  6094. /* Prevent noise on startup */
  6095. pool->lagging = true;
  6096. /* Test the pool is not idle if we're live running, otherwise
  6097. * it will be tested separately */
  6098. if (live && !pool_active(pool, false))
  6099. pool->idle = true;
  6100. }
  6101. #ifdef HAVE_CURSES
  6102. static bool input_pool(bool live)
  6103. {
  6104. char *url = NULL, *user = NULL, *pass = NULL;
  6105. struct pool *pool;
  6106. bool ret = false;
  6107. immedok(logwin, true);
  6108. wlogprint("Input server details.\n");
  6109. url = curses_input("URL");
  6110. if (!url)
  6111. goto out;
  6112. user = curses_input("Username");
  6113. if (!user)
  6114. goto out;
  6115. pass = curses_input("Password");
  6116. if (!pass)
  6117. goto out;
  6118. pool = add_pool();
  6119. if (detect_stratum(pool, url))
  6120. url = strdup(pool->stratum_url);
  6121. else if (strncmp(url, "http://", 7) && strncmp(url, "https://", 8)) {
  6122. char *httpinput;
  6123. httpinput = malloc(255);
  6124. if (!httpinput)
  6125. quit(1, "Failed to malloc httpinput");
  6126. strcpy(httpinput, "http://");
  6127. strncat(httpinput, url, 248);
  6128. free(url);
  6129. url = httpinput;
  6130. }
  6131. add_pool_details(pool, live, url, user, pass);
  6132. ret = true;
  6133. out:
  6134. immedok(logwin, false);
  6135. if (!ret) {
  6136. if (url)
  6137. free(url);
  6138. if (user)
  6139. free(user);
  6140. if (pass)
  6141. free(pass);
  6142. }
  6143. return ret;
  6144. }
  6145. #endif
  6146. #if defined(unix)
  6147. static void fork_monitor()
  6148. {
  6149. // Make a pipe: [readFD, writeFD]
  6150. int pfd[2];
  6151. int r = pipe(pfd);
  6152. if (r < 0) {
  6153. perror("pipe - failed to create pipe for --monitor");
  6154. exit(1);
  6155. }
  6156. // Make stderr write end of pipe
  6157. fflush(stderr);
  6158. r = dup2(pfd[1], 2);
  6159. if (r < 0) {
  6160. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  6161. exit(1);
  6162. }
  6163. r = close(pfd[1]);
  6164. if (r < 0) {
  6165. perror("close - failed to close write end of pipe for --monitor");
  6166. exit(1);
  6167. }
  6168. // Don't allow a dying monitor to kill the main process
  6169. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  6170. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  6171. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  6172. perror("signal - failed to edit signal mask for --monitor");
  6173. exit(1);
  6174. }
  6175. // Fork a child process
  6176. forkpid = fork();
  6177. if (forkpid < 0) {
  6178. perror("fork - failed to fork child process for --monitor");
  6179. exit(1);
  6180. }
  6181. // Child: launch monitor command
  6182. if (0 == forkpid) {
  6183. // Make stdin read end of pipe
  6184. r = dup2(pfd[0], 0);
  6185. if (r < 0) {
  6186. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  6187. exit(1);
  6188. }
  6189. close(pfd[0]);
  6190. if (r < 0) {
  6191. perror("close - in child, failed to close read end of pipe for --monitor");
  6192. exit(1);
  6193. }
  6194. // Launch user specified command
  6195. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  6196. perror("execl - in child failed to exec user specified command for --monitor");
  6197. exit(1);
  6198. }
  6199. // Parent: clean up unused fds and bail
  6200. r = close(pfd[0]);
  6201. if (r < 0) {
  6202. perror("close - failed to close read end of pipe for --monitor");
  6203. exit(1);
  6204. }
  6205. }
  6206. #endif // defined(unix)
  6207. #ifdef HAVE_CURSES
  6208. void enable_curses(void) {
  6209. int x,y;
  6210. lock_curses();
  6211. if (curses_active) {
  6212. unlock_curses();
  6213. return;
  6214. }
  6215. mainwin = initscr();
  6216. keypad(mainwin, true);
  6217. getmaxyx(mainwin, y, x);
  6218. statuswin = newwin(logstart, x, 0, 0);
  6219. leaveok(statuswin, true);
  6220. // For whatever reason, PDCurses crashes if the logwin is initialized to height y-logcursor
  6221. // We resize the window later anyway, so just start it off at 1 :)
  6222. logwin = newwin(1, 0, logcursor, 0);
  6223. idlok(logwin, true);
  6224. scrollok(logwin, true);
  6225. leaveok(logwin, true);
  6226. cbreak();
  6227. noecho();
  6228. curses_active = true;
  6229. statusy = logstart;
  6230. unlock_curses();
  6231. }
  6232. #endif
  6233. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  6234. #ifndef WANT_CPUMINE
  6235. struct device_api cpu_api;
  6236. struct device_api cpu_api = {
  6237. .name = "CPU",
  6238. };
  6239. #endif
  6240. #ifdef USE_BITFORCE
  6241. extern struct device_api bitforce_api;
  6242. #endif
  6243. #ifdef USE_ICARUS
  6244. extern struct device_api cairnsmore_api;
  6245. extern struct device_api icarus_api;
  6246. #endif
  6247. #ifdef USE_MODMINER
  6248. extern struct device_api modminer_api;
  6249. #endif
  6250. #ifdef USE_X6500
  6251. extern struct device_api x6500_api;
  6252. #endif
  6253. #ifdef USE_ZTEX
  6254. extern struct device_api ztex_api;
  6255. #endif
  6256. static int cgminer_id_count = 0;
  6257. void register_device(struct cgpu_info *cgpu)
  6258. {
  6259. cgpu->deven = DEV_ENABLED;
  6260. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  6261. mining_threads += cgpu->threads;
  6262. #ifdef HAVE_CURSES
  6263. adj_width(mining_threads, &dev_width);
  6264. #endif
  6265. #ifdef HAVE_OPENCL
  6266. if (cgpu->api == &opencl_api) {
  6267. gpu_threads += cgpu->threads;
  6268. }
  6269. #endif
  6270. }
  6271. struct _cgpu_devid_counter {
  6272. char name[4];
  6273. int lastid;
  6274. UT_hash_handle hh;
  6275. };
  6276. void renumber_cgpu(struct cgpu_info *cgpu)
  6277. {
  6278. static struct _cgpu_devid_counter *devids = NULL;
  6279. struct _cgpu_devid_counter *d;
  6280. HASH_FIND_STR(devids, cgpu->api->name, d);
  6281. if (d)
  6282. cgpu->device_id = ++d->lastid;
  6283. else {
  6284. d = malloc(sizeof(*d));
  6285. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  6286. cgpu->device_id = d->lastid = 0;
  6287. HASH_ADD_STR(devids, name, d);
  6288. }
  6289. }
  6290. bool add_cgpu(struct cgpu_info*cgpu)
  6291. {
  6292. renumber_cgpu(cgpu);
  6293. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  6294. devices[total_devices++] = cgpu;
  6295. return true;
  6296. }
  6297. static bool my_blkmaker_sha256_callback(void *digest, const void *buffer, size_t length)
  6298. {
  6299. sha2(buffer, length, digest, false);
  6300. return true;
  6301. }
  6302. int main(int argc, char *argv[])
  6303. {
  6304. struct block *block, *tmpblock;
  6305. struct work *work, *tmpwork;
  6306. bool pools_active = false;
  6307. struct sigaction handler;
  6308. struct thr_info *thr;
  6309. char *s;
  6310. unsigned int k;
  6311. int i, j;
  6312. blkmk_sha256_impl = my_blkmaker_sha256_callback;
  6313. /* This dangerous functions tramples random dynamically allocated
  6314. * variables so do it before anything at all */
  6315. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  6316. quit(1, "Failed to curl_global_init");
  6317. initial_args = malloc(sizeof(char *) * (argc + 1));
  6318. for (i = 0; i < argc; i++)
  6319. initial_args[i] = strdup(argv[i]);
  6320. initial_args[argc] = NULL;
  6321. #ifdef HAVE_LIBUSB
  6322. libusb_init(NULL);
  6323. #endif
  6324. #ifdef USE_X6500
  6325. ft232r_scan();
  6326. #endif
  6327. mutex_init(&hash_lock);
  6328. mutex_init(&qd_lock);
  6329. mutex_init(&console_lock);
  6330. mutex_init(&control_lock);
  6331. mutex_init(&sharelog_lock);
  6332. mutex_init(&ch_lock);
  6333. mutex_init(&sshare_lock);
  6334. rwlock_init(&blk_lock);
  6335. rwlock_init(&netacc_lock);
  6336. mutex_init(&lp_lock);
  6337. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  6338. quit(1, "Failed to pthread_cond_init lp_cond");
  6339. mutex_init(&restart_lock);
  6340. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  6341. quit(1, "Failed to pthread_cond_init restart_cond");
  6342. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  6343. #ifdef WANT_CPUMINE
  6344. init_max_name_len();
  6345. #endif
  6346. handler.sa_handler = &sighandler;
  6347. handler.sa_flags = 0;
  6348. sigemptyset(&handler.sa_mask);
  6349. sigaction(SIGTERM, &handler, &termhandler);
  6350. sigaction(SIGINT, &handler, &inthandler);
  6351. #ifndef WIN32
  6352. signal(SIGPIPE, SIG_IGN);
  6353. #endif
  6354. opt_kernel_path = alloca(PATH_MAX);
  6355. strcpy(opt_kernel_path, CGMINER_PREFIX);
  6356. cgminer_path = alloca(PATH_MAX);
  6357. s = strdup(argv[0]);
  6358. strcpy(cgminer_path, dirname(s));
  6359. free(s);
  6360. strcat(cgminer_path, "/");
  6361. #ifdef WANT_CPUMINE
  6362. // Hack to make cgminer silent when called recursively on WIN32
  6363. int skip_to_bench = 0;
  6364. #if defined(WIN32)
  6365. char buf[32];
  6366. if (GetEnvironmentVariable("BFGMINER_BENCH_ALGO", buf, 16))
  6367. skip_to_bench = 1;
  6368. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  6369. skip_to_bench = 1;
  6370. #endif // defined(WIN32)
  6371. #endif
  6372. devcursor = 8;
  6373. logstart = devcursor + 1;
  6374. logcursor = logstart + 1;
  6375. block = calloc(sizeof(struct block), 1);
  6376. if (unlikely(!block))
  6377. quit (1, "main OOM");
  6378. for (i = 0; i < 36; i++)
  6379. strcat(block->hash, "0");
  6380. HASH_ADD_STR(blocks, hash, block);
  6381. strcpy(current_block, block->hash);
  6382. INIT_LIST_HEAD(&scan_devices);
  6383. mutex_init(&submitting_lock);
  6384. INIT_LIST_HEAD(&submit_waiting);
  6385. #ifdef HAVE_OPENCL
  6386. memset(gpus, 0, sizeof(gpus));
  6387. for (i = 0; i < MAX_GPUDEVICES; i++)
  6388. gpus[i].dynamic = true;
  6389. #endif
  6390. schedstart.tm.tm_sec = 1;
  6391. schedstop .tm.tm_sec = 1;
  6392. /* parse command line */
  6393. opt_register_table(opt_config_table,
  6394. "Options for both config file and command line");
  6395. opt_register_table(opt_cmdline_table,
  6396. "Options for command line only");
  6397. opt_parse(&argc, argv, applog_and_exit);
  6398. if (argc != 1)
  6399. quit(1, "Unexpected extra commandline arguments");
  6400. if (!config_loaded)
  6401. load_default_config();
  6402. if (opt_restart) {
  6403. struct sigaction shandler;
  6404. shandler.sa_handler = &seghandler;
  6405. shandler.sa_flags = 0;
  6406. sigemptyset(&shandler.sa_mask);
  6407. sigaction(SIGSEGV, &shandler, &segvhandler);
  6408. sigaction(SIGILL, &shandler, &illhandler);
  6409. #ifndef WIN32
  6410. sigaction(SIGBUS, &shandler, &bushandler);
  6411. #endif
  6412. }
  6413. if (opt_benchmark) {
  6414. struct pool *pool;
  6415. want_longpoll = false;
  6416. pool = add_pool();
  6417. pool->rpc_url = malloc(255);
  6418. strcpy(pool->rpc_url, "Benchmark");
  6419. pool->rpc_user = pool->rpc_url;
  6420. pool->rpc_pass = pool->rpc_url;
  6421. enable_pool(pool);
  6422. pool->idle = false;
  6423. successful_connect = true;
  6424. }
  6425. #ifdef HAVE_CURSES
  6426. if (opt_realquiet || devices_enabled == -1)
  6427. use_curses = false;
  6428. if (use_curses)
  6429. enable_curses();
  6430. #endif
  6431. applog(LOG_WARNING, "Started %s", packagename);
  6432. if (cnfbuf) {
  6433. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  6434. switch (fileconf_load) {
  6435. case 0:
  6436. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  6437. applog(LOG_WARNING, "Configuration file could not be used.");
  6438. break;
  6439. case -1:
  6440. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  6441. if (use_curses)
  6442. applog(LOG_WARNING, "Start BFGMiner with -T to see what failed to load.");
  6443. break;
  6444. default:
  6445. break;
  6446. }
  6447. free(cnfbuf);
  6448. cnfbuf = NULL;
  6449. }
  6450. strcat(opt_kernel_path, "/");
  6451. if (want_per_device_stats)
  6452. opt_log_output = true;
  6453. #ifdef WANT_CPUMINE
  6454. #ifdef USE_SCRYPT
  6455. if (opt_scrypt)
  6456. set_scrypt_algo(&opt_algo);
  6457. else
  6458. #endif
  6459. if (0 <= opt_bench_algo) {
  6460. double rate = bench_algo_stage3(opt_bench_algo);
  6461. if (!skip_to_bench)
  6462. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  6463. else {
  6464. // Write result to shared memory for parent
  6465. #if defined(WIN32)
  6466. char unique_name[64];
  6467. if (GetEnvironmentVariable("BFGMINER_SHARED_MEM", unique_name, 32) || GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  6468. HANDLE map_handle = CreateFileMapping(
  6469. INVALID_HANDLE_VALUE, // use paging file
  6470. NULL, // default security attributes
  6471. PAGE_READWRITE, // read/write access
  6472. 0, // size: high 32-bits
  6473. 4096, // size: low 32-bits
  6474. unique_name // name of map object
  6475. );
  6476. if (NULL != map_handle) {
  6477. void *shared_mem = MapViewOfFile(
  6478. map_handle, // object to map view of
  6479. FILE_MAP_WRITE, // read/write access
  6480. 0, // high offset: map from
  6481. 0, // low offset: beginning
  6482. 0 // default: map entire file
  6483. );
  6484. if (NULL != shared_mem)
  6485. CopyMemory(shared_mem, &rate, sizeof(rate));
  6486. (void)UnmapViewOfFile(shared_mem);
  6487. }
  6488. (void)CloseHandle(map_handle);
  6489. }
  6490. #endif
  6491. }
  6492. exit(0);
  6493. }
  6494. #endif
  6495. #ifdef HAVE_OPENCL
  6496. if (!opt_nogpu)
  6497. opencl_api.api_detect();
  6498. gpu_threads = 0;
  6499. #endif
  6500. #ifdef USE_ICARUS
  6501. if (!opt_scrypt)
  6502. {
  6503. cairnsmore_api.api_detect();
  6504. icarus_api.api_detect();
  6505. }
  6506. #endif
  6507. #ifdef USE_BITFORCE
  6508. if (!opt_scrypt)
  6509. bitforce_api.api_detect();
  6510. #endif
  6511. #ifdef USE_MODMINER
  6512. if (!opt_scrypt)
  6513. modminer_api.api_detect();
  6514. #endif
  6515. #ifdef USE_X6500
  6516. if (!opt_scrypt)
  6517. x6500_api.api_detect();
  6518. #endif
  6519. #ifdef USE_ZTEX
  6520. if (!opt_scrypt)
  6521. ztex_api.api_detect();
  6522. #endif
  6523. #ifdef WANT_CPUMINE
  6524. cpu_api.api_detect();
  6525. #endif
  6526. #ifdef USE_X6500
  6527. ft232r_scan_free();
  6528. #endif
  6529. for (i = 0; i < total_devices; ++i)
  6530. if (!devices[i]->devtype)
  6531. devices[i]->devtype = "PGA";
  6532. if (devices_enabled == -1) {
  6533. applog(LOG_ERR, "Devices detected:");
  6534. for (i = 0; i < total_devices; ++i) {
  6535. struct cgpu_info *cgpu = devices[i];
  6536. if (cgpu->name)
  6537. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  6538. else
  6539. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  6540. }
  6541. quit(0, "%d devices listed", total_devices);
  6542. }
  6543. mining_threads = 0;
  6544. if (devices_enabled) {
  6545. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  6546. if (devices_enabled & (1 << i)) {
  6547. if (i >= total_devices)
  6548. quit (1, "Command line options set a device that doesn't exist");
  6549. register_device(devices[i]);
  6550. } else if (i < total_devices) {
  6551. if (opt_removedisabled) {
  6552. if (devices[i]->api == &cpu_api)
  6553. --opt_n_threads;
  6554. } else {
  6555. register_device(devices[i]);
  6556. }
  6557. devices[i]->deven = DEV_DISABLED;
  6558. }
  6559. }
  6560. total_devices = cgminer_id_count;
  6561. } else {
  6562. for (i = 0; i < total_devices; ++i)
  6563. register_device(devices[i]);
  6564. }
  6565. if (!total_devices)
  6566. quit(1, "All devices disabled, cannot mine!");
  6567. load_temp_config();
  6568. for (i = 0; i < total_devices; ++i)
  6569. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6570. if (!opt_compact) {
  6571. logstart += total_devices;
  6572. logcursor = logstart + 1;
  6573. #ifdef HAVE_CURSES
  6574. check_winsizes();
  6575. #endif
  6576. }
  6577. if (!total_pools) {
  6578. applog(LOG_WARNING, "Need to specify at least one pool server.");
  6579. #ifdef HAVE_CURSES
  6580. if (!use_curses || !input_pool(false))
  6581. #endif
  6582. quit(1, "Pool setup failed");
  6583. }
  6584. for (i = 0; i < total_pools; i++) {
  6585. struct pool *pool = pools[i];
  6586. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6587. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  6588. if (!pool->rpc_userpass) {
  6589. if (!pool->rpc_user || !pool->rpc_pass)
  6590. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  6591. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  6592. if (!pool->rpc_userpass)
  6593. quit(1, "Failed to malloc userpass");
  6594. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  6595. }
  6596. }
  6597. /* Set the currentpool to pool wiht priority 0 */
  6598. validate_pool_priorities();
  6599. for (i = 0; i < total_pools; i++) {
  6600. struct pool *pool = pools[i];
  6601. if (!pool->prio)
  6602. currentpool = pool;
  6603. }
  6604. #ifdef HAVE_SYSLOG_H
  6605. if (use_syslog)
  6606. openlog(PACKAGE, LOG_PID, LOG_USER);
  6607. #endif
  6608. #if defined(unix)
  6609. if (opt_stderr_cmd)
  6610. fork_monitor();
  6611. #endif // defined(unix)
  6612. total_threads = mining_threads + 7;
  6613. thr_info = calloc(total_threads, sizeof(*thr));
  6614. if (!thr_info)
  6615. quit(1, "Failed to calloc thr_info");
  6616. /* init workio thread info */
  6617. work_thr_id = mining_threads;
  6618. thr = &thr_info[work_thr_id];
  6619. thr->id = work_thr_id;
  6620. thr->q = tq_new();
  6621. if (!thr->q)
  6622. quit(1, "Failed to tq_new");
  6623. /* start work I/O thread */
  6624. if (thr_info_create(thr, NULL, workio_thread, thr))
  6625. quit(1, "workio thread create failed");
  6626. stage_thr_id = mining_threads + 1;
  6627. thr = &thr_info[stage_thr_id];
  6628. thr->q = tq_new();
  6629. if (!thr->q)
  6630. quit(1, "Failed to tq_new");
  6631. /* start stage thread */
  6632. if (thr_info_create(thr, NULL, stage_thread, thr))
  6633. quit(1, "stage thread create failed");
  6634. pthread_detach(thr->pth);
  6635. /* Create a unique get work queue */
  6636. getq = tq_new();
  6637. if (!getq)
  6638. quit(1, "Failed to create getq");
  6639. /* We use the getq mutex as the staged lock */
  6640. stgd_lock = &getq->mutex;
  6641. if (opt_benchmark)
  6642. goto begin_bench;
  6643. for (i = 0; i < total_pools; i++) {
  6644. struct pool *pool = pools[i];
  6645. enable_pool(pool);
  6646. pool->idle = true;
  6647. }
  6648. applog(LOG_NOTICE, "Probing for an alive pool");
  6649. do {
  6650. /* Look for at least one active pool before starting */
  6651. for (j = 0; j < total_pools; j++) {
  6652. for (i = 0; i < total_pools; i++) {
  6653. struct pool *pool = pools[i];
  6654. if (pool->prio != j)
  6655. continue;
  6656. if (pool_active(pool, false)) {
  6657. if (!currentpool)
  6658. currentpool = pool;
  6659. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  6660. pools_active = true;
  6661. break;
  6662. } else {
  6663. if (pool == currentpool)
  6664. currentpool = NULL;
  6665. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  6666. }
  6667. }
  6668. }
  6669. if (!pools_active) {
  6670. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  6671. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  6672. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  6673. for (i = 0; i < total_pools; i++) {
  6674. struct pool *pool;
  6675. pool = pools[i];
  6676. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  6677. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  6678. }
  6679. #ifdef HAVE_CURSES
  6680. if (use_curses) {
  6681. halfdelay(150);
  6682. applog(LOG_ERR, "Press any key to exit, or BFGMiner will try again in 15s.");
  6683. if (getch() != ERR)
  6684. quit(0, "No servers could be used! Exiting.");
  6685. nocbreak();
  6686. } else
  6687. #endif
  6688. quit(0, "No servers could be used! Exiting.");
  6689. }
  6690. } while (!pools_active);
  6691. #ifdef USE_SCRYPT
  6692. if (detect_algo == 1 && !opt_scrypt) {
  6693. applog(LOG_NOTICE, "Detected scrypt algorithm");
  6694. opt_scrypt = true;
  6695. }
  6696. #endif
  6697. detect_algo = 0;
  6698. begin_bench:
  6699. total_mhashes_done = 0;
  6700. for (i = 0; i < total_devices; i++) {
  6701. struct cgpu_info *cgpu = devices[i];
  6702. cgpu->rolling = cgpu->total_mhashes = 0;
  6703. }
  6704. gettimeofday(&total_tv_start, NULL);
  6705. gettimeofday(&total_tv_end, NULL);
  6706. miner_started = total_tv_start;
  6707. if (schedstart.tm.tm_sec)
  6708. schedstart.tm = *localtime(&miner_started.tv_sec);
  6709. if (schedstop.tm.tm_sec)
  6710. schedstop .tm = *localtime(&miner_started.tv_sec);
  6711. get_datestamp(datestamp, &total_tv_start);
  6712. // Start threads
  6713. k = 0;
  6714. for (i = 0; i < total_devices; ++i) {
  6715. struct cgpu_info *cgpu = devices[i];
  6716. cgpu->thr = calloc(cgpu->threads+1, sizeof(*cgpu->thr));
  6717. cgpu->thr[cgpu->threads] = NULL;
  6718. cgpu->status = LIFE_INIT;
  6719. // Setup thread structs before starting any of the threads, in case they try to interact
  6720. for (j = 0; j < cgpu->threads; ++j, ++k) {
  6721. thr = &thr_info[k];
  6722. thr->id = k;
  6723. thr->cgpu = cgpu;
  6724. thr->device_thread = j;
  6725. thr->work_restart_fd = thr->_work_restart_fd_w = -1;
  6726. thr->q = tq_new();
  6727. if (!thr->q)
  6728. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  6729. /* Enable threads for devices set not to mine but disable
  6730. * their queue in case we wish to enable them later */
  6731. if (cgpu->deven != DEV_DISABLED) {
  6732. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  6733. tq_push(thr->q, &ping);
  6734. }
  6735. cgpu->thr[j] = thr;
  6736. }
  6737. for (j = 0; j < cgpu->threads; ++j) {
  6738. thr = cgpu->thr[j];
  6739. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  6740. continue;
  6741. if (!thr->work_restart_fd)
  6742. {
  6743. #if defined(unix)
  6744. int pipefd[2];
  6745. if (!pipe(pipefd))
  6746. {
  6747. thr->work_restart_fd = pipefd[0];
  6748. thr->_work_restart_fd_w = pipefd[1];
  6749. }
  6750. else
  6751. #endif
  6752. thr->work_restart_fd = -1;
  6753. }
  6754. thread_reportout(thr);
  6755. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  6756. quit(1, "thread %d create failed", thr->id);
  6757. }
  6758. }
  6759. #ifdef HAVE_OPENCL
  6760. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  6761. for (i = 0; i < nDevs; i++)
  6762. pause_dynamic_threads(i);
  6763. #endif
  6764. #ifdef WANT_CPUMINE
  6765. applog(LOG_INFO, "%d cpu miner threads started, "
  6766. "using SHA256 '%s' algorithm.",
  6767. opt_n_threads,
  6768. algo_names[opt_algo]);
  6769. #endif
  6770. gettimeofday(&total_tv_start, NULL);
  6771. gettimeofday(&total_tv_end, NULL);
  6772. watchpool_thr_id = mining_threads + 2;
  6773. thr = &thr_info[watchpool_thr_id];
  6774. /* start watchpool thread */
  6775. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  6776. quit(1, "watchpool thread create failed");
  6777. pthread_detach(thr->pth);
  6778. watchdog_thr_id = mining_threads + 3;
  6779. thr = &thr_info[watchdog_thr_id];
  6780. /* start watchdog thread */
  6781. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  6782. quit(1, "watchdog thread create failed");
  6783. pthread_detach(thr->pth);
  6784. #ifdef HAVE_OPENCL
  6785. /* Create reinit gpu thread */
  6786. gpur_thr_id = mining_threads + 4;
  6787. thr = &thr_info[gpur_thr_id];
  6788. thr->q = tq_new();
  6789. if (!thr->q)
  6790. quit(1, "tq_new failed for gpur_thr_id");
  6791. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  6792. quit(1, "reinit_gpu thread create failed");
  6793. #endif
  6794. /* Create API socket thread */
  6795. api_thr_id = mining_threads + 5;
  6796. thr = &thr_info[api_thr_id];
  6797. if (thr_info_create(thr, NULL, api_thread, thr))
  6798. quit(1, "API thread create failed");
  6799. #ifdef HAVE_CURSES
  6800. /* Create curses input thread for keyboard input. Create this last so
  6801. * that we know all threads are created since this can call kill_work
  6802. * to try and shut down ll previous threads. */
  6803. input_thr_id = mining_threads + 6;
  6804. thr = &thr_info[input_thr_id];
  6805. if (thr_info_create(thr, NULL, input_thread, thr))
  6806. quit(1, "input thread create failed");
  6807. pthread_detach(thr->pth);
  6808. #endif
  6809. for (i = 0; i < mining_threads + opt_queue; i++)
  6810. queue_request();
  6811. /* main loop - simply wait for workio thread to exit. This is not the
  6812. * normal exit path and only occurs should the workio_thread die
  6813. * unexpectedly */
  6814. pthread_join(thr_info[work_thr_id].pth, NULL);
  6815. applog(LOG_INFO, "workio thread dead, exiting.");
  6816. clean_up();
  6817. /* Not really necessary, but let's clean this up too anyway */
  6818. HASH_ITER(hh, staged_work, work, tmpwork) {
  6819. HASH_DEL(staged_work, work);
  6820. free_work(work);
  6821. }
  6822. HASH_ITER(hh, blocks, block, tmpblock) {
  6823. HASH_DEL(blocks, block);
  6824. free(block);
  6825. }
  6826. #if defined(unix)
  6827. if (forkpid > 0) {
  6828. kill(forkpid, SIGTERM);
  6829. forkpid = 0;
  6830. }
  6831. #endif
  6832. return 0;
  6833. }