miner.c 209 KB

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