miner.c 181 KB

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