miner.c 166 KB

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