miner.c 182 KB

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