cgminer.c 213 KB

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