miner.c 187 KB

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