cgminer.c 202 KB

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