cgminer.c 202 KB

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