miner.c 202 KB

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