miner.c 227 KB

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