miner.c 207 KB

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