cgminer.c 202 KB

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