miner.c 182 KB

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