cgminer.c 202 KB

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