cgminer.c 213 KB

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