cgminer.c 265 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067
  1. /*
  2. * Copyright 2011-2014 Con Kolivas
  3. * Copyright 2011-2012 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #ifdef HAVE_CURSES
  13. #include <curses.h>
  14. #endif
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <math.h>
  24. #include <stdarg.h>
  25. #include <assert.h>
  26. #include <signal.h>
  27. #include <limits.h>
  28. #ifdef USE_USBUTILS
  29. #include <semaphore.h>
  30. #endif
  31. #include <sys/stat.h>
  32. #include <sys/types.h>
  33. #ifndef WIN32
  34. #include <sys/resource.h>
  35. #else
  36. #include <windows.h>
  37. #endif
  38. #include <ccan/opt/opt.h>
  39. #include <jansson.h>
  40. #ifdef HAVE_LIBCURL
  41. #include <curl/curl.h>
  42. #else
  43. char *curly = ":D";
  44. #endif
  45. #include <libgen.h>
  46. #include <sha2.h>
  47. #include "compat.h"
  48. #include "miner.h"
  49. #include "bench_block.h"
  50. #include "scrypt.h"
  51. #ifdef USE_USBUTILS
  52. #include "usbutils.h"
  53. #endif
  54. #if defined(unix) || defined(__APPLE__)
  55. #include <errno.h>
  56. #include <fcntl.h>
  57. #include <sys/wait.h>
  58. #endif
  59. #ifdef USE_AVALON
  60. #include "driver-avalon.h"
  61. #endif
  62. #ifdef USE_AVALON2
  63. #include "driver-avalon2.h"
  64. #endif
  65. #ifdef USE_BFLSC
  66. #include "driver-bflsc.h"
  67. #endif
  68. #ifdef USE_SP10
  69. #include "driver-spondoolies-sp10.h"
  70. #endif
  71. #ifdef USE_SP30
  72. #include "driver-spondoolies-sp30.h"
  73. #endif
  74. #ifdef USE_BLOCK_ERUPTER
  75. #include "driver-blockerupter.h"
  76. #endif
  77. #ifdef USE_BITFURY
  78. #include "driver-bitfury.h"
  79. #endif
  80. #ifdef USE_COINTERRA
  81. #include "driver-cointerra.h"
  82. #endif
  83. #ifdef USE_HASHFAST
  84. #include "driver-hashfast.h"
  85. #endif
  86. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  87. #include "driver-bitmain.h"
  88. #endif
  89. #ifdef USE_GRIDSEED
  90. #include "driver-gridseed.h"
  91. #endif
  92. #ifdef USE_ZEUS
  93. #include "driver-zeus.h"
  94. #endif
  95. #ifdef USE_LKETC
  96. #include "driver-lketc.h"
  97. #endif
  98. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_AVALON) || defined(USE_AVALON2) || defined(USE_MODMINER)
  99. # define USE_FPGA
  100. #endif
  101. struct strategies strategies[] = {
  102. { "Failover" },
  103. { "Round Robin" },
  104. { "Rotate" },
  105. { "Load Balance" },
  106. { "Balance" },
  107. };
  108. static char packagename[256];
  109. bool opt_work_update;
  110. bool opt_protocol;
  111. static struct benchfile_layout {
  112. int length;
  113. char *name;
  114. } benchfile_data[] = {
  115. { 1, "Version" },
  116. { 64, "MerkleRoot" },
  117. { 64, "PrevHash" },
  118. { 8, "DifficultyBits" },
  119. { 10, "NonceTime" } // 10 digits
  120. };
  121. enum benchwork {
  122. BENCHWORK_VERSION = 0,
  123. BENCHWORK_MERKLEROOT,
  124. BENCHWORK_PREVHASH,
  125. BENCHWORK_DIFFBITS,
  126. BENCHWORK_NONCETIME,
  127. BENCHWORK_COUNT
  128. };
  129. #ifdef HAVE_LIBCURL
  130. static char *opt_btc_address;
  131. static char *opt_btc_sig;
  132. #endif
  133. static char *opt_benchfile;
  134. static bool opt_benchfile_display;
  135. static FILE *benchfile_in;
  136. static int benchfile_line;
  137. static int benchfile_work;
  138. static bool opt_benchmark;
  139. bool have_longpoll;
  140. bool want_per_device_stats;
  141. bool use_syslog;
  142. bool opt_quiet;
  143. bool opt_realquiet;
  144. bool opt_loginput;
  145. bool opt_compact;
  146. const int opt_cutofftemp = 95;
  147. int opt_log_interval = 5;
  148. int opt_queue = 1;
  149. static int max_queue = 1;
  150. int opt_scantime = -1;
  151. int opt_expiry = 120;
  152. static const bool opt_time = true;
  153. unsigned long long global_hashrate;
  154. unsigned long global_quota_gcd = 1;
  155. time_t last_getwork;
  156. #if defined(USE_USBUTILS)
  157. int nDevs;
  158. #endif
  159. bool opt_sha256;
  160. #ifdef USE_SCRYPT
  161. bool opt_scrypt;
  162. #endif
  163. bool opt_restart = true;
  164. bool opt_nogpu;
  165. struct list_head scan_devices;
  166. static bool opt_display_devs;
  167. int total_devices;
  168. int zombie_devs;
  169. static int most_devices;
  170. struct cgpu_info **devices;
  171. int mining_threads;
  172. int num_processors;
  173. #ifdef HAVE_CURSES
  174. bool use_curses = true;
  175. #else
  176. bool use_curses;
  177. #endif
  178. static bool opt_widescreen;
  179. static bool alt_status;
  180. static bool switch_status;
  181. static bool opt_submit_stale = true;
  182. static int opt_shares;
  183. bool opt_fail_only;
  184. static bool opt_fix_protocol;
  185. bool opt_lowmem;
  186. bool opt_autofan;
  187. bool opt_autoengine;
  188. bool opt_noadl;
  189. char *opt_api_allow = NULL;
  190. char *opt_api_groups;
  191. char *opt_api_description = PACKAGE_STRING;
  192. int opt_api_port = 4028;
  193. char *opt_api_host = API_LISTEN_ADDR;
  194. bool opt_api_listen;
  195. bool opt_api_mcast;
  196. char *opt_api_mcast_addr = API_MCAST_ADDR;
  197. char *opt_api_mcast_code = API_MCAST_CODE;
  198. char *opt_api_mcast_des = "";
  199. int opt_api_mcast_port = 4028;
  200. bool opt_api_network;
  201. bool opt_delaynet;
  202. bool opt_disable_pool;
  203. static bool no_work;
  204. #ifdef USE_ICARUS
  205. char *opt_icarus_options = NULL;
  206. char *opt_icarus_timing = NULL;
  207. float opt_anu_freq = 200;
  208. float opt_rock_freq = 270;
  209. #endif
  210. bool opt_worktime;
  211. #ifdef USE_AVALON
  212. char *opt_avalon_options;
  213. char *opt_bitburner_fury_options;
  214. static char *opt_set_avalon_fan;
  215. static char *opt_set_avalon_freq;
  216. #endif
  217. #ifdef USE_AVALON2
  218. static char *opt_set_avalon2_freq;
  219. static char *opt_set_avalon2_fan;
  220. static char *opt_set_avalon2_voltage;
  221. #endif
  222. #ifdef USE_BLOCKERUPTER
  223. int opt_bet_clk = 0;
  224. #endif
  225. #ifdef USE_HASHRATIO
  226. #include "driver-hashratio.h"
  227. #endif
  228. #ifdef USE_KLONDIKE
  229. char *opt_klondike_options = NULL;
  230. #endif
  231. #ifdef USE_DRILLBIT
  232. char *opt_drillbit_options = NULL;
  233. char *opt_drillbit_auto = NULL;
  234. #endif
  235. char *opt_bab_options = NULL;
  236. #ifdef USE_BITMINE_A1
  237. char *opt_bitmine_a1_options = NULL;
  238. #endif
  239. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  240. char *opt_bitmain_options;
  241. static char *opt_set_bitmain_fan;
  242. static char *opt_set_bitmain_freq;
  243. #endif
  244. #ifdef USE_ANT_S2
  245. char *opt_bitmain_dev;
  246. #endif
  247. #ifdef USE_HASHFAST
  248. static char *opt_set_hfa_fan;
  249. #endif
  250. #ifdef USE_GRIDSEED
  251. char *opt_gridseed_options = NULL;
  252. char *opt_gridseed_freq = NULL;
  253. char *opt_gridseed_override = NULL;
  254. #endif
  255. #ifdef USE_LKETC
  256. bool opt_lketc_debug;
  257. int opt_lketc_chips_count;
  258. int opt_lketc_chip_clk;
  259. bool opt_lketc_nocheck_golden;
  260. char *opt_lketc_options;
  261. #endif
  262. #ifdef USE_ZEUS
  263. bool opt_zeus_debug;
  264. int opt_zeus_chips_count;
  265. int opt_zeus_chip_clk;
  266. bool opt_zeus_nocheck_golden;
  267. char *opt_zeus_options;
  268. #endif
  269. static char *opt_set_null;
  270. #ifdef USE_MINION
  271. int opt_minion_chipreport;
  272. char *opt_minion_cores;
  273. bool opt_minion_extra;
  274. char *opt_minion_freq;
  275. int opt_minion_freqchange = 1000;
  276. int opt_minion_freqpercent = 70;
  277. bool opt_minion_idlecount;
  278. int opt_minion_ledcount;
  279. int opt_minion_ledlimit = 98;
  280. bool opt_minion_noautofreq;
  281. bool opt_minion_overheat;
  282. int opt_minion_spidelay;
  283. char *opt_minion_spireset;
  284. int opt_minion_spisleep = 200;
  285. int opt_minion_spiusec;
  286. char *opt_minion_temp;
  287. #endif
  288. #ifdef USE_USBUTILS
  289. char *opt_usb_select = NULL;
  290. int opt_usbdump = -1;
  291. bool opt_usb_list_all;
  292. cgsem_t usb_resource_sem;
  293. static pthread_t usb_poll_thread;
  294. static bool usb_polling;
  295. #endif
  296. char *opt_kernel_path;
  297. char *cgminer_path;
  298. #if defined(USE_BITFORCE)
  299. bool opt_bfl_noncerange;
  300. #endif
  301. #define QUIET (opt_quiet || opt_realquiet)
  302. struct thr_info *control_thr;
  303. struct thr_info **mining_thr;
  304. static int gwsched_thr_id;
  305. static int watchpool_thr_id;
  306. static int watchdog_thr_id;
  307. #ifdef HAVE_CURSES
  308. static int input_thr_id;
  309. #endif
  310. int gpur_thr_id;
  311. static int api_thr_id;
  312. #ifdef USE_USBUTILS
  313. static int usbres_thr_id;
  314. static int hotplug_thr_id;
  315. #endif
  316. static int total_control_threads;
  317. bool hotplug_mode;
  318. static int new_devices;
  319. static int new_threads;
  320. int hotplug_time = 5;
  321. #if LOCK_TRACKING
  322. pthread_mutex_t lockstat_lock;
  323. #endif
  324. pthread_mutex_t hash_lock;
  325. static pthread_mutex_t *stgd_lock;
  326. pthread_mutex_t console_lock;
  327. cglock_t ch_lock;
  328. static pthread_rwlock_t blk_lock;
  329. static pthread_mutex_t sshare_lock;
  330. pthread_rwlock_t netacc_lock;
  331. pthread_rwlock_t mining_thr_lock;
  332. pthread_rwlock_t devices_lock;
  333. static pthread_mutex_t lp_lock;
  334. static pthread_cond_t lp_cond;
  335. pthread_mutex_t restart_lock;
  336. pthread_cond_t restart_cond;
  337. pthread_cond_t gws_cond;
  338. double rolling1, rolling5, rolling15;
  339. double total_rolling;
  340. double total_mhashes_done;
  341. static struct timeval total_tv_start, total_tv_end;
  342. static struct timeval restart_tv_start, update_tv_start;
  343. cglock_t control_lock;
  344. pthread_mutex_t stats_lock;
  345. int hw_errors;
  346. int64_t total_accepted, total_rejected, total_diff1;
  347. int64_t total_getworks, total_stale, total_discarded;
  348. double total_diff_accepted, total_diff_rejected, total_diff_stale;
  349. static int staged_rollable;
  350. unsigned int new_blocks;
  351. static unsigned int work_block;
  352. unsigned int found_blocks;
  353. unsigned int local_work;
  354. unsigned int total_go, total_ro;
  355. struct pool **pools;
  356. static struct pool *currentpool = NULL;
  357. int total_pools, enabled_pools;
  358. enum pool_strategy pool_strategy = POOL_FAILOVER;
  359. int opt_rotate_period;
  360. static int total_urls, total_users, total_passes, total_userpasses;
  361. static
  362. #ifndef HAVE_CURSES
  363. const
  364. #endif
  365. bool curses_active;
  366. /* Protected by ch_lock */
  367. char current_hash[68];
  368. static char prev_block[12];
  369. static char current_block[32];
  370. static char datestamp[40];
  371. static char blocktime[32];
  372. struct timeval block_timeval;
  373. static char best_share[8] = "0";
  374. double current_diff = 0xFFFFFFFFFFFFFFFFULL;
  375. static char block_diff[8];
  376. uint64_t best_diff = 0;
  377. struct block {
  378. char hash[68];
  379. UT_hash_handle hh;
  380. int block_no;
  381. };
  382. static struct block *blocks = NULL;
  383. int swork_id;
  384. /* For creating a hash database of stratum shares submitted that have not had
  385. * a response yet */
  386. struct stratum_share {
  387. UT_hash_handle hh;
  388. bool block;
  389. struct work *work;
  390. int id;
  391. time_t sshare_time;
  392. time_t sshare_sent;
  393. };
  394. static struct stratum_share *stratum_shares = NULL;
  395. char *opt_socks_proxy = NULL;
  396. int opt_suggest_diff;
  397. static const char def_conf[] = "cgminer.conf";
  398. static char *default_config;
  399. static bool config_loaded;
  400. static int include_count;
  401. #define JSON_INCLUDE_CONF "include"
  402. #define JSON_LOAD_ERROR "JSON decode of file '%s' failed\n %s"
  403. #define JSON_LOAD_ERROR_LEN strlen(JSON_LOAD_ERROR)
  404. #define JSON_MAX_DEPTH 10
  405. #define JSON_MAX_DEPTH_ERR "Too many levels of JSON includes (limit 10) or a loop"
  406. #define JSON_WEB_ERROR "WEB config err"
  407. #if defined(unix) || defined(__APPLE__)
  408. static char *opt_stderr_cmd = NULL;
  409. static int forkpid;
  410. #endif // defined(unix)
  411. struct sigaction termhandler, inthandler;
  412. struct thread_q *getq;
  413. static uint32_t total_work;
  414. struct work *staged_work = NULL;
  415. struct schedtime {
  416. bool enable;
  417. struct tm tm;
  418. };
  419. struct schedtime schedstart;
  420. struct schedtime schedstop;
  421. bool sched_paused;
  422. static bool time_before(struct tm *tm1, struct tm *tm2)
  423. {
  424. if (tm1->tm_hour < tm2->tm_hour)
  425. return true;
  426. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  427. return true;
  428. return false;
  429. }
  430. static bool should_run(void)
  431. {
  432. struct timeval tv;
  433. struct tm *tm;
  434. if (!schedstart.enable && !schedstop.enable)
  435. return true;
  436. cgtime(&tv);
  437. const time_t tmp_time = tv.tv_sec;
  438. tm = localtime(&tmp_time);
  439. if (schedstart.enable) {
  440. if (!schedstop.enable) {
  441. if (time_before(tm, &schedstart.tm))
  442. return false;
  443. /* This is a once off event with no stop time set */
  444. schedstart.enable = false;
  445. return true;
  446. }
  447. if (time_before(&schedstart.tm, &schedstop.tm)) {
  448. if (time_before(tm, &schedstop.tm) && !time_before(tm, &schedstart.tm))
  449. return true;
  450. return false;
  451. } /* Times are reversed */
  452. if (time_before(tm, &schedstart.tm)) {
  453. if (time_before(tm, &schedstop.tm))
  454. return true;
  455. return false;
  456. }
  457. return true;
  458. }
  459. /* only schedstop.enable == true */
  460. if (!time_before(tm, &schedstop.tm))
  461. return false;
  462. return true;
  463. }
  464. void get_datestamp(char *f, size_t fsiz, struct timeval *tv)
  465. {
  466. struct tm *tm;
  467. const time_t tmp_time = tv->tv_sec;
  468. tm = localtime(&tmp_time);
  469. snprintf(f, fsiz, "[%d-%02d-%02d %02d:%02d:%02d]",
  470. tm->tm_year + 1900,
  471. tm->tm_mon + 1,
  472. tm->tm_mday,
  473. tm->tm_hour,
  474. tm->tm_min,
  475. tm->tm_sec);
  476. }
  477. static void get_timestamp(char *f, size_t fsiz, struct timeval *tv)
  478. {
  479. struct tm *tm;
  480. const time_t tmp_time = tv->tv_sec;
  481. tm = localtime(&tmp_time);
  482. snprintf(f, fsiz, "[%02d:%02d:%02d]",
  483. tm->tm_hour,
  484. tm->tm_min,
  485. tm->tm_sec);
  486. }
  487. static char exit_buf[512];
  488. static void applog_and_exit(const char *fmt, ...)
  489. {
  490. va_list ap;
  491. va_start(ap, fmt);
  492. vsnprintf(exit_buf, sizeof(exit_buf), fmt, ap);
  493. va_end(ap);
  494. _applog(LOG_ERR, exit_buf, true);
  495. exit(1);
  496. }
  497. static pthread_mutex_t sharelog_lock;
  498. static FILE *sharelog_file = NULL;
  499. static struct thr_info *__get_thread(int thr_id)
  500. {
  501. return mining_thr[thr_id];
  502. }
  503. struct thr_info *get_thread(int thr_id)
  504. {
  505. struct thr_info *thr;
  506. rd_lock(&mining_thr_lock);
  507. thr = __get_thread(thr_id);
  508. rd_unlock(&mining_thr_lock);
  509. return thr;
  510. }
  511. static struct cgpu_info *get_thr_cgpu(int thr_id)
  512. {
  513. struct thr_info *thr = get_thread(thr_id);
  514. return thr->cgpu;
  515. }
  516. struct cgpu_info *get_devices(int id)
  517. {
  518. struct cgpu_info *cgpu;
  519. rd_lock(&devices_lock);
  520. cgpu = devices[id];
  521. rd_unlock(&devices_lock);
  522. return cgpu;
  523. }
  524. static void sharelog(const char*disposition, const struct work*work)
  525. {
  526. char *target, *hash, *data;
  527. struct cgpu_info *cgpu;
  528. unsigned long int t;
  529. struct pool *pool;
  530. int thr_id, rv;
  531. char s[1024];
  532. size_t ret;
  533. if (!sharelog_file)
  534. return;
  535. thr_id = work->thr_id;
  536. cgpu = get_thr_cgpu(thr_id);
  537. pool = work->pool;
  538. t = (unsigned long int)(work->tv_work_found.tv_sec);
  539. target = bin2hex(work->target, sizeof(work->target));
  540. hash = bin2hex(work->hash, sizeof(work->hash));
  541. data = bin2hex(work->data, sizeof(work->data));
  542. // timestamp,disposition,target,pool,dev,thr,sharehash,sharedata
  543. 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);
  544. free(target);
  545. free(hash);
  546. free(data);
  547. if (rv >= (int)(sizeof(s)))
  548. s[sizeof(s) - 1] = '\0';
  549. else if (rv < 0) {
  550. applog(LOG_ERR, "sharelog printf error");
  551. return;
  552. }
  553. mutex_lock(&sharelog_lock);
  554. ret = fwrite(s, rv, 1, sharelog_file);
  555. fflush(sharelog_file);
  556. mutex_unlock(&sharelog_lock);
  557. if (ret != 1)
  558. applog(LOG_ERR, "sharelog fwrite error");
  559. }
  560. static char *getwork_req = "{\"method\": \"getwork\", \"params\": [], \"id\":0}\n";
  561. static char *gbt_req = "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"]}]}\n";
  562. static char *gbt_solo_req = "{\"id\": 0, \"method\": \"getblocktemplate\"}\n";
  563. /* Adjust all the pools' quota to the greatest common denominator after a pool
  564. * has been added or the quotas changed. */
  565. void adjust_quota_gcd(void)
  566. {
  567. unsigned long gcd, lowest_quota = ~0UL, quota;
  568. struct pool *pool;
  569. int i;
  570. for (i = 0; i < total_pools; i++) {
  571. pool = pools[i];
  572. quota = pool->quota;
  573. if (!quota)
  574. continue;
  575. if (quota < lowest_quota)
  576. lowest_quota = quota;
  577. }
  578. if (likely(lowest_quota < ~0UL)) {
  579. gcd = lowest_quota;
  580. for (i = 0; i < total_pools; i++) {
  581. pool = pools[i];
  582. quota = pool->quota;
  583. if (!quota)
  584. continue;
  585. while (quota % gcd)
  586. gcd--;
  587. }
  588. } else
  589. gcd = 1;
  590. for (i = 0; i < total_pools; i++) {
  591. pool = pools[i];
  592. pool->quota_used *= global_quota_gcd;
  593. pool->quota_used /= gcd;
  594. pool->quota_gcd = pool->quota / gcd;
  595. }
  596. global_quota_gcd = gcd;
  597. applog(LOG_DEBUG, "Global quota greatest common denominator set to %lu", gcd);
  598. }
  599. /* Return value is ignored if not called from add_pool_details */
  600. struct pool *add_pool(void)
  601. {
  602. struct pool *pool;
  603. pool = calloc(sizeof(struct pool), 1);
  604. if (!pool)
  605. quit(1, "Failed to malloc pool in add_pool");
  606. pool->pool_no = pool->prio = total_pools;
  607. pools = realloc(pools, sizeof(struct pool *) * (total_pools + 2));
  608. pools[total_pools++] = pool;
  609. mutex_init(&pool->pool_lock);
  610. if (unlikely(pthread_cond_init(&pool->cr_cond, NULL)))
  611. quit(1, "Failed to pthread_cond_init in add_pool");
  612. cglock_init(&pool->data_lock);
  613. mutex_init(&pool->stratum_lock);
  614. cglock_init(&pool->gbt_lock);
  615. INIT_LIST_HEAD(&pool->curlring);
  616. /* Make sure the pool doesn't think we've been idle since time 0 */
  617. pool->tv_idle.tv_sec = ~0UL;
  618. pool->rpc_req = getwork_req;
  619. pool->rpc_proxy = NULL;
  620. pool->quota = 1;
  621. adjust_quota_gcd();
  622. return pool;
  623. }
  624. /* Pool variant of test and set */
  625. static bool pool_tset(struct pool *pool, bool *var)
  626. {
  627. bool ret;
  628. mutex_lock(&pool->pool_lock);
  629. ret = *var;
  630. *var = true;
  631. mutex_unlock(&pool->pool_lock);
  632. return ret;
  633. }
  634. bool pool_tclear(struct pool *pool, bool *var)
  635. {
  636. bool ret;
  637. mutex_lock(&pool->pool_lock);
  638. ret = *var;
  639. *var = false;
  640. mutex_unlock(&pool->pool_lock);
  641. return ret;
  642. }
  643. struct pool *current_pool(void)
  644. {
  645. struct pool *pool;
  646. cg_rlock(&control_lock);
  647. pool = currentpool;
  648. cg_runlock(&control_lock);
  649. return pool;
  650. }
  651. char *set_int_range(const char *arg, int *i, int min, int max)
  652. {
  653. char *err = opt_set_intval(arg, i);
  654. if (err)
  655. return err;
  656. if (*i < min || *i > max)
  657. return "Value out of range";
  658. return NULL;
  659. }
  660. static char *set_int_0_to_9999(const char *arg, int *i)
  661. {
  662. return set_int_range(arg, i, 0, 9999);
  663. }
  664. static char *set_int_1_to_65535(const char *arg, int *i)
  665. {
  666. return set_int_range(arg, i, 1, 65535);
  667. }
  668. static char *set_int_0_to_10(const char *arg, int *i)
  669. {
  670. return set_int_range(arg, i, 0, 10);
  671. }
  672. static char *set_int_0_to_100(const char *arg, int *i)
  673. {
  674. return set_int_range(arg, i, 0, 100);
  675. }
  676. static char *set_int_0_to_255(const char *arg, int *i)
  677. {
  678. return set_int_range(arg, i, 0, 255);
  679. }
  680. static char *set_int_0_to_200(const char *arg, int *i)
  681. {
  682. return set_int_range(arg, i, 0, 200);
  683. }
  684. static char *set_int_32_to_63(const char *arg, int *i)
  685. {
  686. return set_int_range(arg, i, 32, 63);
  687. }
  688. static char *set_int_1_to_10(const char *arg, int *i)
  689. {
  690. return set_int_range(arg, i, 1, 10);
  691. }
  692. static char __maybe_unused *set_int_0_to_4(const char *arg, int *i)
  693. {
  694. return set_int_range(arg, i, 0, 4);
  695. }
  696. static char *set_int_1_to_1024(const char *arg, int *i)
  697. {
  698. return set_int_range(arg, i, 1, 1024);
  699. }
  700. #ifdef USE_FPGA_SERIAL
  701. static char *opt_add_serial;
  702. static char *add_serial(char *arg)
  703. {
  704. string_elist_add(arg, &scan_devices);
  705. return NULL;
  706. }
  707. #endif
  708. void get_intrange(char *arg, int *val1, int *val2)
  709. {
  710. if (sscanf(arg, "%d-%d", val1, val2) == 1)
  711. *val2 = *val1;
  712. }
  713. static char *set_balance(enum pool_strategy *strategy)
  714. {
  715. *strategy = POOL_BALANCE;
  716. return NULL;
  717. }
  718. static char *set_loadbalance(enum pool_strategy *strategy)
  719. {
  720. *strategy = POOL_LOADBALANCE;
  721. return NULL;
  722. }
  723. static char *set_rotate(const char *arg, char __maybe_unused *i)
  724. {
  725. pool_strategy = POOL_ROTATE;
  726. return set_int_range(arg, &opt_rotate_period, 0, 9999);
  727. }
  728. static char *set_rr(enum pool_strategy *strategy)
  729. {
  730. *strategy = POOL_ROUNDROBIN;
  731. return NULL;
  732. }
  733. /* Detect that url is for a stratum protocol either via the presence of
  734. * stratum+tcp or by detecting a stratum server response */
  735. bool detect_stratum(struct pool *pool, char *url)
  736. {
  737. check_extranonce_option(pool, url);
  738. if (!extract_sockaddr(url, &pool->sockaddr_url, &pool->stratum_port))
  739. return false;
  740. if (!strncasecmp(url, "stratum+tcp://", 14)) {
  741. pool->rpc_url = strdup(url);
  742. pool->has_stratum = true;
  743. pool->stratum_url = pool->sockaddr_url;
  744. return true;
  745. }
  746. return false;
  747. }
  748. static struct pool *add_url(void)
  749. {
  750. total_urls++;
  751. if (total_urls > total_pools)
  752. add_pool();
  753. return pools[total_urls - 1];
  754. }
  755. static void setup_url(struct pool *pool, char *arg)
  756. {
  757. arg = get_proxy(arg, pool);
  758. if (detect_stratum(pool, arg))
  759. return;
  760. opt_set_charp(arg, &pool->rpc_url);
  761. if (strncmp(arg, "http://", 7) &&
  762. strncmp(arg, "https://", 8)) {
  763. char *httpinput;
  764. httpinput = malloc(256);
  765. if (!httpinput)
  766. quit(1, "Failed to malloc httpinput");
  767. strcpy(httpinput, "stratum+tcp://");
  768. strncat(httpinput, arg, 242);
  769. detect_stratum(pool, httpinput);
  770. }
  771. }
  772. static char *set_url(char *arg)
  773. {
  774. struct pool *pool = add_url();
  775. setup_url(pool, arg);
  776. return NULL;
  777. }
  778. static char *set_quota(char *arg)
  779. {
  780. char *semicolon = strchr(arg, ';'), *url;
  781. int len, qlen, quota;
  782. struct pool *pool;
  783. if (!semicolon)
  784. return "No semicolon separated quota;URL pair found";
  785. len = strlen(arg);
  786. *semicolon = '\0';
  787. qlen = strlen(arg);
  788. if (!qlen)
  789. return "No parameter for quota found";
  790. len -= qlen + 1;
  791. if (len < 1)
  792. return "No parameter for URL found";
  793. quota = atoi(arg);
  794. if (quota < 0)
  795. return "Invalid negative parameter for quota set";
  796. url = arg + qlen + 1;
  797. pool = add_url();
  798. setup_url(pool, url);
  799. pool->quota = quota;
  800. applog(LOG_INFO, "Setting pool %d to quota %d", pool->pool_no, pool->quota);
  801. adjust_quota_gcd();
  802. return NULL;
  803. }
  804. static char *set_user(const char *arg)
  805. {
  806. struct pool *pool;
  807. if (total_userpasses)
  808. return "Use only user + pass or userpass, but not both";
  809. total_users++;
  810. if (total_users > total_pools)
  811. add_pool();
  812. pool = pools[total_users - 1];
  813. opt_set_charp(arg, &pool->rpc_user);
  814. return NULL;
  815. }
  816. static char *set_pass(const char *arg)
  817. {
  818. struct pool *pool;
  819. if (total_userpasses)
  820. return "Use only user + pass or userpass, but not both";
  821. total_passes++;
  822. if (total_passes > total_pools)
  823. add_pool();
  824. pool = pools[total_passes - 1];
  825. opt_set_charp(arg, &pool->rpc_pass);
  826. return NULL;
  827. }
  828. static char *set_userpass(const char *arg)
  829. {
  830. struct pool *pool;
  831. char *updup;
  832. if (total_users || total_passes)
  833. return "Use only user + pass or userpass, but not both";
  834. total_userpasses++;
  835. if (total_userpasses > total_pools)
  836. add_pool();
  837. pool = pools[total_userpasses - 1];
  838. updup = strdup(arg);
  839. opt_set_charp(arg, &pool->rpc_userpass);
  840. pool->rpc_user = strtok(updup, ":");
  841. if (!pool->rpc_user)
  842. return "Failed to find : delimited user info";
  843. pool->rpc_pass = strtok(NULL, ":");
  844. if (!pool->rpc_pass)
  845. pool->rpc_pass = strdup("");
  846. return NULL;
  847. }
  848. static char *enable_debug(bool *flag)
  849. {
  850. *flag = true;
  851. /* Turn on verbose output, too. */
  852. opt_log_output = true;
  853. return NULL;
  854. }
  855. static char *opt_set_sched_start;
  856. static char *opt_set_sched_stop;
  857. static char *set_schedtime(const char *arg, struct schedtime *st)
  858. {
  859. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  860. return "Invalid time set, should be HH:MM";
  861. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  862. return "Invalid time set.";
  863. st->enable = true;
  864. return NULL;
  865. }
  866. static char *set_sched_start(const char *arg)
  867. {
  868. return set_schedtime(arg, &schedstart);
  869. }
  870. static char *set_sched_stop(const char *arg)
  871. {
  872. return set_schedtime(arg, &schedstop);
  873. }
  874. static char *opt_set_sharelog;
  875. static char* set_sharelog(char *arg)
  876. {
  877. char *r = "";
  878. long int i = strtol(arg, &r, 10);
  879. if ((!*r) && i >= 0 && i <= INT_MAX) {
  880. sharelog_file = fdopen((int)i, "a");
  881. if (!sharelog_file)
  882. applog(LOG_ERR, "Failed to open fd %u for share log", (unsigned int)i);
  883. } else if (!strcmp(arg, "-")) {
  884. sharelog_file = stdout;
  885. if (!sharelog_file)
  886. applog(LOG_ERR, "Standard output missing for share log");
  887. } else {
  888. sharelog_file = fopen(arg, "a");
  889. if (!sharelog_file)
  890. applog(LOG_ERR, "Failed to open %s for share log", arg);
  891. }
  892. return NULL;
  893. }
  894. static char *temp_cutoff_str = NULL;
  895. static char __maybe_unused *opt_set_temp_cutoff;
  896. char *set_temp_cutoff(char *arg)
  897. {
  898. int val;
  899. if (!(arg && arg[0]))
  900. return "Invalid parameters for set temp cutoff";
  901. val = atoi(arg);
  902. if (val < 0 || val > 200)
  903. return "Invalid value passed to set temp cutoff";
  904. temp_cutoff_str = arg;
  905. return NULL;
  906. }
  907. static void load_temp_cutoffs()
  908. {
  909. int i, val = 0, device = 0;
  910. char *nextptr;
  911. if (temp_cutoff_str) {
  912. for (device = 0, nextptr = strtok(temp_cutoff_str, ","); nextptr; ++device, nextptr = strtok(NULL, ",")) {
  913. if (device >= total_devices)
  914. quit(1, "Too many values passed to set temp cutoff");
  915. val = atoi(nextptr);
  916. if (val < 0 || val > 200)
  917. quit(1, "Invalid value passed to set temp cutoff");
  918. rd_lock(&devices_lock);
  919. devices[device]->cutofftemp = val;
  920. rd_unlock(&devices_lock);
  921. }
  922. } else {
  923. rd_lock(&devices_lock);
  924. for (i = device; i < total_devices; ++i) {
  925. if (!devices[i]->cutofftemp)
  926. devices[i]->cutofftemp = opt_cutofftemp;
  927. }
  928. rd_unlock(&devices_lock);
  929. return;
  930. }
  931. if (device <= 1) {
  932. rd_lock(&devices_lock);
  933. for (i = device; i < total_devices; ++i)
  934. devices[i]->cutofftemp = val;
  935. rd_unlock(&devices_lock);
  936. }
  937. }
  938. static char *set_float_125_to_500(const char *arg, float *i)
  939. {
  940. char *err = opt_set_floatval(arg, i);
  941. if (err)
  942. return err;
  943. if (*i < 125 || *i > 500)
  944. return "Value out of range";
  945. return NULL;
  946. }
  947. static char *set_null(const char __maybe_unused *arg)
  948. {
  949. return NULL;
  950. }
  951. /* These options are available from config file or commandline */
  952. static struct opt_table opt_config_table[] = {
  953. #ifdef USE_ICARUS
  954. OPT_WITH_ARG("--anu-freq",
  955. set_float_125_to_500, &opt_show_floatval, &opt_anu_freq,
  956. "Set AntminerU1 frequency in MHz, range 125-500"),
  957. #endif
  958. OPT_WITH_ARG("--api-allow",
  959. opt_set_charp, NULL, &opt_api_allow,
  960. "Allow API access only to the given list of [G:]IP[/Prefix] addresses[/subnets]"),
  961. OPT_WITH_ARG("--api-description",
  962. opt_set_charp, NULL, &opt_api_description,
  963. "Description placed in the API status header, default: cgminer version"),
  964. OPT_WITH_ARG("--api-groups",
  965. opt_set_charp, NULL, &opt_api_groups,
  966. "API one letter groups G:cmd:cmd[,P:cmd:*...] defining the cmds a groups can use"),
  967. OPT_WITHOUT_ARG("--api-listen",
  968. opt_set_bool, &opt_api_listen,
  969. "Enable API, default: disabled"),
  970. OPT_WITHOUT_ARG("--api-mcast",
  971. opt_set_bool, &opt_api_mcast,
  972. "Enable API Multicast listener, default: disabled"),
  973. OPT_WITH_ARG("--api-mcast-addr",
  974. opt_set_charp, NULL, &opt_api_mcast_addr,
  975. "API Multicast listen address"),
  976. OPT_WITH_ARG("--api-mcast-code",
  977. opt_set_charp, NULL, &opt_api_mcast_code,
  978. "Code expected in the API Multicast message, don't use '-'"),
  979. OPT_WITH_ARG("--api-mcast-des",
  980. opt_set_charp, NULL, &opt_api_mcast_des,
  981. "Description appended to the API Multicast reply, default: ''"),
  982. OPT_WITH_ARG("--api-mcast-port",
  983. set_int_1_to_65535, opt_show_intval, &opt_api_mcast_port,
  984. "API Multicast listen port"),
  985. OPT_WITHOUT_ARG("--api-network",
  986. opt_set_bool, &opt_api_network,
  987. "Allow API (if enabled) to listen on/for any address, default: only 127.0.0.1"),
  988. OPT_WITH_ARG("--api-port",
  989. set_int_1_to_65535, opt_show_intval, &opt_api_port,
  990. "Port number of miner API"),
  991. OPT_WITH_ARG("--api-host",
  992. opt_set_charp, NULL, &opt_api_host,
  993. "Specify API listen address, default: 0.0.0.0"),
  994. #ifdef USE_AVALON
  995. OPT_WITHOUT_ARG("--avalon-auto",
  996. opt_set_bool, &opt_avalon_auto,
  997. "Adjust avalon overclock frequency dynamically for best hashrate"),
  998. OPT_WITH_ARG("--avalon-cutoff",
  999. set_int_0_to_100, opt_show_intval, &opt_avalon_overheat,
  1000. "Set avalon overheat cut off temperature"),
  1001. OPT_WITH_CBARG("--avalon-fan",
  1002. set_avalon_fan, NULL, &opt_set_avalon_fan,
  1003. "Set fanspeed percentage for avalon, single value or range (default: 20-100)"),
  1004. OPT_WITH_CBARG("--avalon-freq",
  1005. set_avalon_freq, NULL, &opt_set_avalon_freq,
  1006. "Set frequency range for avalon-auto, single value or range"),
  1007. OPT_WITH_ARG("--avalon-options",
  1008. opt_set_charp, NULL, &opt_avalon_options,
  1009. "Set avalon options baud:miners:asic:timeout:freq:tech"),
  1010. OPT_WITH_ARG("--avalon-temp",
  1011. set_int_0_to_100, opt_show_intval, &opt_avalon_temp,
  1012. "Set avalon target temperature"),
  1013. #endif
  1014. #ifdef USE_AVALON2
  1015. OPT_WITH_CBARG("--avalon2-freq",
  1016. set_avalon2_freq, NULL, &opt_set_avalon2_freq,
  1017. "Set frequency range for Avalon2, single value or range, step: 25"),
  1018. OPT_WITH_CBARG("--avalon2-voltage",
  1019. set_avalon2_voltage, NULL, &opt_set_avalon2_voltage,
  1020. "Set Avalon2 core voltage, in millivolts, step: 125"),
  1021. OPT_WITH_CBARG("--avalon2-fan",
  1022. set_avalon2_fan, NULL, &opt_set_avalon2_fan,
  1023. "Set Avalon2 target fan speed"),
  1024. OPT_WITH_ARG("--avalon2-cutoff",
  1025. set_int_0_to_100, opt_show_intval, &opt_avalon2_overheat,
  1026. "Set Avalon2 overheat cut off temperature"),
  1027. OPT_WITHOUT_ARG("--avalon2-fixed-speed",
  1028. set_avalon2_fixed_speed, &opt_avalon2_fan_fixed,
  1029. "Set Avalon2 fan to fixed speed"),
  1030. OPT_WITH_ARG("--avalon2-polling-delay",
  1031. set_int_1_to_65535, opt_show_intval, &opt_avalon2_polling_delay,
  1032. "Set Avalon2 polling delay value (ms)"),
  1033. #endif
  1034. #ifdef USE_BAB
  1035. OPT_WITH_ARG("--bab-options",
  1036. opt_set_charp, NULL, &opt_bab_options,
  1037. "Set bab options max:def:min:up:down:hz:delay:trf"),
  1038. #endif
  1039. OPT_WITHOUT_ARG("--balance",
  1040. set_balance, &pool_strategy,
  1041. "Change multipool strategy from failover to even share balance"),
  1042. OPT_WITH_ARG("--benchfile",
  1043. opt_set_charp, NULL, &opt_benchfile,
  1044. "Run cgminer in benchmark mode using a work file - produces no shares"),
  1045. OPT_WITHOUT_ARG("--benchfile-display",
  1046. opt_set_bool, &opt_benchfile_display,
  1047. "Display each benchfile nonce found"),
  1048. OPT_WITHOUT_ARG("--benchmark",
  1049. opt_set_bool, &opt_benchmark,
  1050. "Run cgminer in benchmark mode - produces no shares"),
  1051. #if defined(USE_BITFORCE)
  1052. OPT_WITHOUT_ARG("--bfl-range",
  1053. opt_set_bool, &opt_bfl_noncerange,
  1054. "Use nonce range on bitforce devices if supported"),
  1055. #endif
  1056. #ifdef USE_BFLSC
  1057. OPT_WITH_ARG("--bflsc-overheat",
  1058. set_int_0_to_200, opt_show_intval, &opt_bflsc_overheat,
  1059. "Set overheat temperature where BFLSC devices throttle, 0 to disable"),
  1060. #endif
  1061. #ifdef USE_AVALON
  1062. OPT_WITH_ARG("--bitburner-voltage",
  1063. opt_set_intval, NULL, &opt_bitburner_core_voltage,
  1064. "Set BitBurner (Avalon) core voltage, in millivolts"),
  1065. OPT_WITH_ARG("--bitburner-fury-voltage",
  1066. opt_set_intval, NULL, &opt_bitburner_fury_core_voltage,
  1067. "Set BitBurner Fury core voltage, in millivolts"),
  1068. OPT_WITH_ARG("--bitburner-fury-options",
  1069. opt_set_charp, NULL, &opt_bitburner_fury_options,
  1070. "Override avalon-options for BitBurner Fury boards baud:miners:asic:timeout:freq"),
  1071. #endif
  1072. #if defined(USE_ANT_S1) || defined(USE_ANT_S2)
  1073. OPT_WITHOUT_ARG("--bitmain-auto",
  1074. opt_set_bool, &opt_bitmain_auto,
  1075. "Adjust bitmain overclock frequency dynamically for best hashrate"),
  1076. OPT_WITH_ARG("--bitmain-cutoff",
  1077. set_int_0_to_100, opt_show_intval, &opt_bitmain_overheat,
  1078. "Set bitmain overheat cut off temperature"),
  1079. OPT_WITH_CBARG("--bitmain-fan",
  1080. set_bitmain_fan, NULL, &opt_set_bitmain_fan,
  1081. "Set fanspeed percentage for bitmain, single value or range (default: 20-100)"),
  1082. OPT_WITH_CBARG("--bitmain-freq",
  1083. set_bitmain_freq, NULL, &opt_set_bitmain_freq,
  1084. "Set frequency range for bitmain-auto, single value or range"),
  1085. OPT_WITHOUT_ARG("--bitmain-hwerror",
  1086. opt_set_bool, &opt_bitmain_hwerror,
  1087. "Set bitmain device detect hardware error"),
  1088. OPT_WITH_ARG("--bitmain-options",
  1089. opt_set_charp, NULL, &opt_bitmain_options,
  1090. "Set bitmain options baud:miners:asic:timeout:freq"),
  1091. OPT_WITH_ARG("--bitmain-temp",
  1092. set_int_0_to_100, opt_show_intval, &opt_bitmain_temp,
  1093. "Set bitmain target temperature"),
  1094. #endif
  1095. #ifdef USE_ANT_S2
  1096. OPT_WITH_ARG("--bitmain-dev",
  1097. opt_set_charp, NULL, &opt_bitmain_dev,
  1098. "Set bitmain device"),
  1099. OPT_WITHOUT_ARG("--bitmainbeeper",
  1100. opt_set_bool, &opt_bitmain_beeper,
  1101. "Set bitmain beeper ringing"),
  1102. OPT_WITHOUT_ARG("--bitmain-checkall",
  1103. opt_set_bool, &opt_bitmain_checkall,
  1104. opt_hidden),
  1105. OPT_WITHOUT_ARG("--bitmain-checkn2diff",
  1106. opt_set_bool, &opt_bitmain_checkn2diff,
  1107. opt_hidden),
  1108. OPT_WITHOUT_ARG("--bitmaintempoverctrl",
  1109. opt_set_bool, &opt_bitmain_tempoverctrl,
  1110. "Set bitmain stop runing when temprerature is over 80 degree Celsius"),
  1111. #endif
  1112. #ifdef USE_BITMINE_A1
  1113. OPT_WITH_ARG("--bitmine-a1-options",
  1114. opt_set_charp, NULL, &opt_bitmine_a1_options,
  1115. "Bitmine A1 options ref_clk_khz:sys_clk_khz:spi_clk_khz:override_chip_num"),
  1116. #endif
  1117. #ifdef USE_BITFURY
  1118. OPT_WITH_ARG("--bxf-bits",
  1119. set_int_32_to_63, opt_show_intval, &opt_bxf_bits,
  1120. "Set max BXF/HXF bits for overclocking"),
  1121. OPT_WITH_ARG("--bxf-debug",
  1122. set_int_0_to_4, opt_show_intval, &opt_bxf_debug,
  1123. "BXF: Debug all USB I/O, > is to the board(s), < is from the board(s)"),
  1124. OPT_WITH_ARG("--bxf-temp-target",
  1125. set_int_0_to_200, opt_show_intval, &opt_bxf_temp_target,
  1126. "Set target temperature for BXF/HXF devices"),
  1127. OPT_WITH_ARG("--bxm-bits",
  1128. set_int_0_to_100, opt_show_intval, &opt_bxm_bits,
  1129. "Set BXM bits for overclocking"),
  1130. #endif
  1131. #ifdef USE_BLOCKERUPTER
  1132. OPT_WITH_ARG("--bet-clk",
  1133. opt_set_intval, opt_show_intval, &opt_bet_clk,
  1134. "Set Block Erupter clock"),
  1135. #endif
  1136. #ifdef HAVE_LIBCURL
  1137. OPT_WITH_ARG("--btc-address",
  1138. opt_set_charp, NULL, &opt_btc_address,
  1139. "Set bitcoin target address when solo mining to bitcoind (mandatory)"),
  1140. OPT_WITH_ARG("--btc-sig",
  1141. opt_set_charp, NULL, &opt_btc_sig,
  1142. "Set signature to add to coinbase when solo mining (optional)"),
  1143. #endif
  1144. #ifdef HAVE_CURSES
  1145. OPT_WITHOUT_ARG("--compact",
  1146. opt_set_bool, &opt_compact,
  1147. "Use compact display without per device statistics"),
  1148. #endif
  1149. #ifdef USE_COINTERRA
  1150. OPT_WITH_ARG("--cta-load",
  1151. set_int_0_to_255, opt_show_intval, &opt_cta_load,
  1152. "Set load for CTA devices, 0-255 range"),
  1153. OPT_WITH_ARG("--ps-load",
  1154. set_int_0_to_100, opt_show_intval, &opt_ps_load,
  1155. "Set power supply load for CTA devices, 0-100 range"),
  1156. #endif
  1157. OPT_WITHOUT_ARG("--debug|-D",
  1158. enable_debug, &opt_debug,
  1159. "Enable debug output"),
  1160. OPT_WITHOUT_ARG("--disable-rejecting",
  1161. opt_set_bool, &opt_disable_pool,
  1162. "Automatically disable pools that continually reject shares"),
  1163. #ifdef USE_DRILLBIT
  1164. OPT_WITH_ARG("--drillbit-options",
  1165. opt_set_charp, NULL, &opt_drillbit_options,
  1166. "Set drillbit options <int|ext>:clock[:clock_divider][:voltage]"),
  1167. OPT_WITH_ARG("--drillbit-auto",
  1168. opt_set_charp, NULL, &opt_drillbit_auto,
  1169. "Enable drillbit automatic tuning <every>:[<gooderr>:<baderr>:<maxerr>]"),
  1170. #endif
  1171. OPT_WITH_ARG("--expiry|-E",
  1172. set_int_0_to_9999, opt_show_intval, &opt_expiry,
  1173. "Upper bound on how many seconds after getting work we consider a share from it stale"),
  1174. OPT_WITHOUT_ARG("--failover-only",
  1175. opt_set_bool, &opt_fail_only,
  1176. "Don't leak work to backup pools when primary pool is lagging"),
  1177. OPT_WITHOUT_ARG("--fix-protocol",
  1178. opt_set_bool, &opt_fix_protocol,
  1179. "Do not redirect to a different getwork protocol (eg. stratum)"),
  1180. #ifdef USE_GRIDSEED
  1181. OPT_WITH_ARG("--gridseed-options",
  1182. opt_set_charp, NULL, &opt_gridseed_options,
  1183. "Set gridseed options: freq=N[,voltage=1][,led_off=1]"),
  1184. OPT_WITH_ARG("--gridseed-freq",
  1185. opt_set_charp, NULL, &opt_gridseed_freq,
  1186. "Set gridseed frequency per-device: serial=freq[,...]"),
  1187. OPT_WITH_ARG("--gridseed-override",
  1188. opt_set_charp, NULL, &opt_gridseed_override,
  1189. "Set any gridseed option per-device: serial:opt1=val1[,...][;serial=...]"),
  1190. #endif
  1191. #ifdef USE_HASHFAST
  1192. OPT_WITHOUT_ARG("--hfa-dfu-boot",
  1193. opt_set_bool, &opt_hfa_dfu_boot,
  1194. opt_hidden),
  1195. OPT_WITH_ARG("--hfa-hash-clock",
  1196. set_int_0_to_9999, opt_show_intval, &opt_hfa_hash_clock,
  1197. "Set hashfast clock speed"),
  1198. OPT_WITH_ARG("--hfa-fail-drop",
  1199. set_int_0_to_100, opt_show_intval, &opt_hfa_fail_drop,
  1200. "Set how many MHz to drop clockspeed each failure on an overlocked hashfast device"),
  1201. OPT_WITH_CBARG("--hfa-fan",
  1202. set_hfa_fan, NULL, &opt_set_hfa_fan,
  1203. "Set fanspeed percentage for hashfast, single value or range (default: 10-85)"),
  1204. OPT_WITH_ARG("--hfa-name",
  1205. opt_set_charp, NULL, &opt_hfa_name,
  1206. "Set a unique name for a single hashfast device specified with --usb or the first device found"),
  1207. OPT_WITHOUT_ARG("--hfa-noshed",
  1208. opt_set_bool, &opt_hfa_noshed,
  1209. "Disable hashfast dynamic core disabling feature"),
  1210. OPT_WITH_ARG("--hfa-ntime-roll",
  1211. opt_set_intval, NULL, &opt_hfa_ntime_roll,
  1212. opt_hidden),
  1213. OPT_WITH_ARG("--hfa-options",
  1214. opt_set_charp, NULL, &opt_hfa_options,
  1215. "Set hashfast options name:clock (comma separated)"),
  1216. OPT_WITHOUT_ARG("--hfa-pll-bypass",
  1217. opt_set_bool, &opt_hfa_pll_bypass,
  1218. opt_hidden),
  1219. OPT_WITH_ARG("--hfa-temp-overheat",
  1220. set_int_0_to_200, opt_show_intval, &opt_hfa_overheat,
  1221. "Set the hashfast overheat throttling temperature"),
  1222. OPT_WITH_ARG("--hfa-temp-target",
  1223. set_int_0_to_200, opt_show_intval, &opt_hfa_target,
  1224. "Set the hashfast target temperature (0 to disable)"),
  1225. #endif
  1226. #ifdef USE_HASHRATIO
  1227. OPT_WITH_CBARG("--hro-freq",
  1228. set_hashratio_freq, NULL, &opt_hashratio_freq,
  1229. "Set the hashratio clock frequency"),
  1230. #endif
  1231. OPT_WITH_ARG("--hotplug",
  1232. set_int_0_to_9999, NULL, &hotplug_time,
  1233. #ifdef USE_USBUTILS
  1234. "Seconds between hotplug checks (0 means never check)"
  1235. #else
  1236. opt_hidden
  1237. #endif
  1238. ),
  1239. #ifdef USE_ICARUS
  1240. OPT_WITH_ARG("--icarus-options",
  1241. opt_set_charp, NULL, &opt_icarus_options,
  1242. opt_hidden),
  1243. OPT_WITH_ARG("--icarus-timing",
  1244. opt_set_charp, NULL, &opt_icarus_timing,
  1245. opt_hidden),
  1246. #endif
  1247. #if defined(HAVE_MODMINER)
  1248. OPT_WITH_ARG("--kernel-path|-K",
  1249. opt_set_charp, opt_show_charp, &opt_kernel_path,
  1250. "Specify a path to where bitstream files are"),
  1251. #endif
  1252. #ifdef USE_KLONDIKE
  1253. OPT_WITH_ARG("--klondike-options",
  1254. opt_set_charp, NULL, &opt_klondike_options,
  1255. "Set klondike options clock:temptarget"),
  1256. #endif
  1257. OPT_WITHOUT_ARG("--load-balance",
  1258. set_loadbalance, &pool_strategy,
  1259. "Change multipool strategy from failover to quota based balance"),
  1260. OPT_WITH_ARG("--log|-l",
  1261. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1262. "Interval in seconds between log output"),
  1263. OPT_WITHOUT_ARG("--lowmem",
  1264. opt_set_bool, &opt_lowmem,
  1265. "Minimise caching of shares for low memory applications"),
  1266. #ifdef USE_MINION
  1267. OPT_WITH_ARG("--minion-chipreport",
  1268. set_int_0_to_100, opt_show_intval, &opt_minion_chipreport,
  1269. "Seconds to report chip 5min hashrate, range 0-100 (default: 0=disabled)"),
  1270. OPT_WITH_ARG("--minion-cores",
  1271. opt_set_charp, NULL, &opt_minion_cores,
  1272. opt_hidden),
  1273. OPT_WITHOUT_ARG("--minion-extra",
  1274. opt_set_bool, &opt_minion_extra,
  1275. opt_hidden),
  1276. OPT_WITH_ARG("--minion-freq",
  1277. opt_set_charp, NULL, &opt_minion_freq,
  1278. "Set minion chip frequencies in MHz, single value or comma list, range 100-1400 (default: 1200)"),
  1279. OPT_WITH_ARG("--minion-freqchange",
  1280. set_int_0_to_9999, opt_show_intval, &opt_minion_freqchange,
  1281. "Millisecond total time to do frequency changes (default: 1000)"),
  1282. OPT_WITH_ARG("--minion-freqpercent",
  1283. set_int_0_to_100, opt_show_intval, &opt_minion_freqpercent,
  1284. "Percentage to use when starting up a chip (default: 70%)"),
  1285. OPT_WITHOUT_ARG("--minion-idlecount",
  1286. opt_set_bool, &opt_minion_idlecount,
  1287. "Report when IdleCount is >0 or changes"),
  1288. OPT_WITH_ARG("--minion-ledcount",
  1289. set_int_0_to_100, opt_show_intval, &opt_minion_ledcount,
  1290. "Turn off led when more than this many chips below the ledlimit (default: 0)"),
  1291. OPT_WITH_ARG("--minion-ledlimit",
  1292. set_int_0_to_200, opt_show_intval, &opt_minion_ledlimit,
  1293. "Turn off led when chips GHs are below this (default: 90)"),
  1294. OPT_WITHOUT_ARG("--minion-noautofreq",
  1295. opt_set_bool, &opt_minion_noautofreq,
  1296. "Disable automatic frequency adjustment"),
  1297. OPT_WITHOUT_ARG("--minion-overheat",
  1298. opt_set_bool, &opt_minion_overheat,
  1299. "Enable directly halting any chip when the status exceeds 100C"),
  1300. OPT_WITH_ARG("--minion-spidelay",
  1301. set_int_0_to_9999, opt_show_intval, &opt_minion_spidelay,
  1302. "Add a delay in microseconds after each SPI I/O"),
  1303. OPT_WITH_ARG("--minion-spireset",
  1304. opt_set_charp, NULL, &opt_minion_spireset,
  1305. "SPI regular reset: iNNN for I/O count or sNNN for seconds - 0 means none"),
  1306. OPT_WITH_ARG("--minion-spisleep",
  1307. set_int_0_to_9999, opt_show_intval, &opt_minion_spisleep,
  1308. "Sleep time in milliseconds when doing an SPI reset"),
  1309. OPT_WITH_ARG("--minion-spiusec",
  1310. set_int_0_to_9999, NULL, &opt_minion_spiusec,
  1311. opt_hidden),
  1312. OPT_WITH_ARG("--minion-temp",
  1313. opt_set_charp, NULL, &opt_minion_temp,
  1314. "Set minion chip temperature threshold, single value or comma list, range 120-160 (default: 135C)"),
  1315. #endif
  1316. #if defined(unix) || defined(__APPLE__)
  1317. OPT_WITH_ARG("--monitor|-m",
  1318. opt_set_charp, NULL, &opt_stderr_cmd,
  1319. "Use custom pipe cmd for output messages"),
  1320. #endif // defined(unix)
  1321. #ifdef USE_BITFURY
  1322. OPT_WITH_ARG("--nfu-bits",
  1323. set_int_32_to_63, opt_show_intval, &opt_nfu_bits,
  1324. "Set nanofury bits for overclocking, range 32-63"),
  1325. #endif
  1326. OPT_WITHOUT_ARG("--net-delay",
  1327. opt_set_bool, &opt_delaynet,
  1328. "Impose small delays in networking to not overload slow routers"),
  1329. OPT_WITHOUT_ARG("--no-pool-disable",
  1330. opt_set_invbool, &opt_disable_pool,
  1331. opt_hidden),
  1332. OPT_WITHOUT_ARG("--no-submit-stale",
  1333. opt_set_invbool, &opt_submit_stale,
  1334. "Don't submit shares if they are detected as stale"),
  1335. #ifdef USE_BITFURY
  1336. OPT_WITH_ARG("--osm-led-mode",
  1337. set_int_0_to_4, opt_show_intval, &opt_osm_led_mode,
  1338. "Set LED mode for OneStringMiner devices"),
  1339. #endif
  1340. OPT_WITH_ARG("--pass|-p",
  1341. set_pass, NULL, &opt_set_null,
  1342. "Password for bitcoin JSON-RPC server"),
  1343. OPT_WITHOUT_ARG("--per-device-stats",
  1344. opt_set_bool, &want_per_device_stats,
  1345. "Force verbose mode and output per-device statistics"),
  1346. OPT_WITH_ARG("--pools",
  1347. opt_set_bool, NULL, &opt_set_null, opt_hidden),
  1348. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1349. opt_set_bool, &opt_protocol,
  1350. "Verbose dump of protocol-level activities"),
  1351. OPT_WITH_ARG("--queue|-Q",
  1352. set_int_0_to_9999, opt_show_intval, &opt_queue,
  1353. "Maximum number of work items to have queued"),
  1354. OPT_WITHOUT_ARG("--quiet|-q",
  1355. opt_set_bool, &opt_quiet,
  1356. "Disable logging output, display status and errors"),
  1357. OPT_WITH_ARG("--quota|-U",
  1358. set_quota, NULL, &opt_set_null,
  1359. "quota;URL combination for server with load-balance strategy quotas"),
  1360. OPT_WITHOUT_ARG("--real-quiet",
  1361. opt_set_bool, &opt_realquiet,
  1362. "Disable all output"),
  1363. OPT_WITH_ARG("--retries",
  1364. set_null, NULL, &opt_set_null,
  1365. opt_hidden),
  1366. OPT_WITH_ARG("--retry-pause",
  1367. set_null, NULL, &opt_set_null,
  1368. opt_hidden),
  1369. #ifdef USE_ICARUS
  1370. OPT_WITH_ARG("--rock-freq",
  1371. set_float_125_to_500, &opt_show_floatval, &opt_rock_freq,
  1372. "Set RockMiner frequency in MHz, range 125-500"),
  1373. #endif
  1374. OPT_WITH_ARG("--rotate",
  1375. set_rotate, NULL, &opt_set_null,
  1376. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1377. OPT_WITHOUT_ARG("--round-robin",
  1378. set_rr, &pool_strategy,
  1379. "Change multipool strategy from failover to round robin on failure"),
  1380. #ifdef USE_FPGA_SERIAL
  1381. OPT_WITH_CBARG("--scan-serial|-S",
  1382. add_serial, NULL, &opt_add_serial,
  1383. "Serial port to probe for Serial FPGA Mining device"),
  1384. #endif
  1385. OPT_WITH_ARG("--scan-time|-s",
  1386. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1387. "Upper bound on time spent scanning current work, in seconds"),
  1388. OPT_WITH_CBARG("--sched-start",
  1389. set_sched_start, NULL, &opt_set_sched_start,
  1390. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1391. OPT_WITH_CBARG("--sched-stop",
  1392. set_sched_stop, NULL, &opt_set_sched_stop,
  1393. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1394. OPT_WITHOUT_ARG("--sha256",
  1395. opt_set_bool, &opt_sha256,
  1396. "Use the SHA-256 algorithm for mining"),
  1397. #ifdef USE_SCRYPT
  1398. OPT_WITHOUT_ARG("--scrypt",
  1399. opt_set_bool, &opt_scrypt,
  1400. "Use the scrypt algorithm for mining"),
  1401. #endif
  1402. OPT_WITH_CBARG("--sharelog",
  1403. set_sharelog, NULL, &opt_set_sharelog,
  1404. "Append share log to file"),
  1405. OPT_WITH_ARG("--shares",
  1406. opt_set_intval, NULL, &opt_shares,
  1407. "Quit after mining N shares (default: unlimited)"),
  1408. OPT_WITH_ARG("--socks-proxy",
  1409. opt_set_charp, NULL, &opt_socks_proxy,
  1410. "Set socks4 proxy (host:port)"),
  1411. OPT_WITH_ARG("--suggest-diff",
  1412. opt_set_intval, NULL, &opt_suggest_diff,
  1413. "Suggest miner difficulty for pool to user (default: none)"),
  1414. #ifdef HAVE_SYSLOG_H
  1415. OPT_WITHOUT_ARG("--syslog",
  1416. opt_set_bool, &use_syslog,
  1417. "Use system log for output messages (default: standard error)"),
  1418. #endif
  1419. #if defined(USE_BITFORCE) || defined(USE_MODMINER) || defined(USE_BFLSC)
  1420. OPT_WITH_CBARG("--temp-cutoff",
  1421. set_temp_cutoff, opt_show_intval, &opt_set_temp_cutoff,
  1422. "Temperature where a device will be automatically disabled, one value or comma separated list"),
  1423. #endif
  1424. OPT_WITHOUT_ARG("--text-only|-T",
  1425. opt_set_invbool, &use_curses,
  1426. #ifdef HAVE_CURSES
  1427. "Disable ncurses formatted screen output"
  1428. #else
  1429. opt_hidden
  1430. #endif
  1431. ),
  1432. OPT_WITH_ARG("--url|-o",
  1433. set_url, NULL, &opt_set_null,
  1434. "URL for bitcoin JSON-RPC server"),
  1435. #ifdef USE_USBUTILS
  1436. OPT_WITH_ARG("--usb",
  1437. opt_set_charp, NULL, &opt_usb_select,
  1438. "USB device selection"),
  1439. OPT_WITH_ARG("--usb-dump",
  1440. set_int_0_to_10, opt_show_intval, &opt_usbdump,
  1441. opt_hidden),
  1442. OPT_WITHOUT_ARG("--usb-list-all",
  1443. opt_set_bool, &opt_usb_list_all,
  1444. opt_hidden),
  1445. #endif
  1446. OPT_WITH_ARG("--user|-u",
  1447. set_user, NULL, &opt_set_null,
  1448. "Username for bitcoin JSON-RPC server"),
  1449. OPT_WITH_ARG("--userpass|-O",
  1450. set_userpass, NULL, &opt_set_null,
  1451. "Username:Password pair for bitcoin JSON-RPC server"),
  1452. OPT_WITHOUT_ARG("--verbose",
  1453. opt_set_bool, &opt_log_output,
  1454. "Log verbose output to stderr as well as status output"),
  1455. OPT_WITHOUT_ARG("--widescreen",
  1456. opt_set_bool, &opt_widescreen,
  1457. "Use extra wide display without toggling"),
  1458. OPT_WITHOUT_ARG("--worktime",
  1459. opt_set_bool, &opt_worktime,
  1460. "Display extra work time debug information"),
  1461. #ifdef USE_ZEUS
  1462. OPT_WITH_ARG("--zeus-chips",
  1463. set_int_1_to_1024, NULL, &opt_zeus_chips_count,
  1464. "Number of Zeus chips per device"),
  1465. OPT_WITH_ARG("--zeus-clock",
  1466. opt_set_intval, NULL, &opt_zeus_chip_clk,
  1467. "Zeus chip clock speed (MHz)"),
  1468. OPT_WITHOUT_ARG("--zeus-debug",
  1469. opt_set_bool, &opt_zeus_debug,
  1470. "Enable extra Zeus driver debugging output in verbose mode"),
  1471. OPT_WITHOUT_ARG("--zeus-nocheck-golden",
  1472. opt_set_bool, &opt_zeus_nocheck_golden,
  1473. "Skip golden nonce verification during initialization"),
  1474. OPT_WITH_ARG("--zeus-options",
  1475. opt_set_charp, NULL, &opt_zeus_options,
  1476. "Set individual Zeus device options: ID,chips,clock[;ID,chips,clock...]"),
  1477. #endif
  1478. #ifdef USE_LKETC
  1479. OPT_WITH_ARG("--lketc-chips",
  1480. set_int_1_to_1024, NULL, &opt_lketc_chips_count,
  1481. "Number of LKETC chips per device"),
  1482. OPT_WITH_ARG("--lketc-clock",
  1483. opt_set_intval, NULL, &opt_lketc_chip_clk,
  1484. "LKETC chip clock speed (MHz)"),
  1485. OPT_WITHOUT_ARG("--lketc-debug",
  1486. opt_set_bool, &opt_lketc_debug,
  1487. "Enable extra LKETC driver debugging output in verbose mode"),
  1488. OPT_WITHOUT_ARG("--lketc-nocheck-golden",
  1489. opt_set_bool, &opt_lketc_nocheck_golden,
  1490. "Skip golden nonce verification during initialization"),
  1491. OPT_WITH_ARG("--lketc-options",
  1492. opt_set_charp, NULL, &opt_lketc_options,
  1493. "Set individual LKETC device options: ID,chips,clock[;ID,chips,clock...]"),
  1494. #endif
  1495. OPT_ENDTABLE
  1496. };
  1497. static char *load_config(const char *arg, void __maybe_unused *unused);
  1498. static int fileconf_load;
  1499. static char *parse_config(json_t *config, bool fileconf)
  1500. {
  1501. static char err_buf[200];
  1502. struct opt_table *opt;
  1503. const char *str;
  1504. json_t *val;
  1505. if (fileconf && !fileconf_load)
  1506. fileconf_load = 1;
  1507. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1508. char *p, *name;
  1509. /* We don't handle subtables. */
  1510. assert(!(opt->type & OPT_SUBTABLE));
  1511. if (!opt->names)
  1512. continue;
  1513. /* Pull apart the option name(s). */
  1514. name = strdup(opt->names);
  1515. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1516. char *err = NULL;
  1517. /* Ignore short options. */
  1518. if (p[1] != '-')
  1519. continue;
  1520. val = json_object_get(config, p+2);
  1521. if (!val)
  1522. continue;
  1523. if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_string(val)) {
  1524. str = json_string_value(val);
  1525. err = opt->cb_arg(str, opt->u.arg);
  1526. if (opt->type == OPT_PROCESSARG)
  1527. opt_set_charp(str, opt->u.arg);
  1528. } else if ((opt->type & (OPT_HASARG | OPT_PROCESSARG)) && json_is_array(val)) {
  1529. json_t *arr_val;
  1530. size_t index;
  1531. json_array_foreach(val, index, arr_val) {
  1532. if (json_is_string(arr_val)) {
  1533. str = json_string_value(arr_val);
  1534. err = opt->cb_arg(str, opt->u.arg);
  1535. if (opt->type == OPT_PROCESSARG)
  1536. opt_set_charp(str, opt->u.arg);
  1537. } else if (json_is_object(arr_val))
  1538. err = parse_config(arr_val, false);
  1539. if (err)
  1540. break;
  1541. }
  1542. } else if ((opt->type & OPT_NOARG) && json_is_true(val))
  1543. err = opt->cb(opt->u.arg);
  1544. else
  1545. err = "Invalid value";
  1546. if (err) {
  1547. /* Allow invalid values to be in configuration
  1548. * file, just skipping over them provided the
  1549. * JSON is still valid after that. */
  1550. if (fileconf) {
  1551. applog(LOG_ERR, "Invalid config option %s: %s", p, err);
  1552. fileconf_load = -1;
  1553. } else {
  1554. snprintf(err_buf, sizeof(err_buf), "Parsing JSON option %s: %s",
  1555. p, err);
  1556. return err_buf;
  1557. }
  1558. }
  1559. }
  1560. free(name);
  1561. }
  1562. val = json_object_get(config, JSON_INCLUDE_CONF);
  1563. if (val && json_is_string(val))
  1564. return load_config(json_string_value(val), NULL);
  1565. return NULL;
  1566. }
  1567. char *cnfbuf = NULL;
  1568. #ifdef HAVE_LIBCURL
  1569. char conf_web1[] = "http://";
  1570. char conf_web2[] = "https://";
  1571. static char *load_web_config(const char *arg)
  1572. {
  1573. json_t *val = json_web_config(arg);
  1574. if (!val || !json_is_object(val))
  1575. return JSON_WEB_ERROR;
  1576. if (!cnfbuf)
  1577. cnfbuf = strdup(arg);
  1578. config_loaded = true;
  1579. return parse_config(val, true);
  1580. }
  1581. #endif
  1582. static char *load_config(const char *arg, void __maybe_unused *unused)
  1583. {
  1584. json_error_t err;
  1585. json_t *config;
  1586. char *json_error;
  1587. size_t siz;
  1588. #ifdef HAVE_LIBCURL
  1589. if (strncasecmp(arg, conf_web1, sizeof(conf_web1)-1) == 0 ||
  1590. strncasecmp(arg, conf_web2, sizeof(conf_web2)-1) == 0)
  1591. return load_web_config(arg);
  1592. #endif
  1593. if (!cnfbuf)
  1594. cnfbuf = strdup(arg);
  1595. if (++include_count > JSON_MAX_DEPTH)
  1596. return JSON_MAX_DEPTH_ERR;
  1597. config = json_load_file(arg, 0, &err);
  1598. if (!json_is_object(config)) {
  1599. siz = JSON_LOAD_ERROR_LEN + strlen(arg) + strlen(err.text);
  1600. json_error = malloc(siz);
  1601. if (!json_error)
  1602. quit(1, "Malloc failure in json error");
  1603. snprintf(json_error, siz, JSON_LOAD_ERROR, arg, err.text);
  1604. return json_error;
  1605. }
  1606. config_loaded = true;
  1607. /* Parse the config now, so we can override it. That can keep pointers
  1608. * so don't free config object. */
  1609. return parse_config(config, true);
  1610. }
  1611. static char *set_default_config(const char *arg)
  1612. {
  1613. opt_set_charp(arg, &default_config);
  1614. return NULL;
  1615. }
  1616. void default_save_file(char *filename);
  1617. static void load_default_config(void)
  1618. {
  1619. cnfbuf = malloc(PATH_MAX);
  1620. default_save_file(cnfbuf);
  1621. if (!access(cnfbuf, R_OK))
  1622. load_config(cnfbuf, NULL);
  1623. else {
  1624. free(cnfbuf);
  1625. cnfbuf = NULL;
  1626. }
  1627. }
  1628. extern const char *opt_argv0;
  1629. static char *opt_verusage_and_exit(const char *extra)
  1630. {
  1631. printf("%s\nBuilt with "
  1632. #ifdef USE_ANT_S1
  1633. "ant.S1 "
  1634. #endif
  1635. #ifdef USE_ANT_S2
  1636. "ant.S2 "
  1637. #endif
  1638. #ifdef USE_AVALON
  1639. "avalon "
  1640. #endif
  1641. #ifdef USE_AVALON2
  1642. "avalon2 "
  1643. #endif
  1644. #ifdef USE_BFLSC
  1645. "bflsc "
  1646. #endif
  1647. #ifdef USE_BITFORCE
  1648. "bitforce "
  1649. #endif
  1650. #ifdef USE_BITFURY
  1651. "bitfury "
  1652. #endif
  1653. #ifdef USE_COINTERRA
  1654. "cointerra "
  1655. #endif
  1656. #ifdef USE_DRILLBIT
  1657. "drillbit "
  1658. #endif
  1659. #ifdef USE_HASHFAST
  1660. "hashfast "
  1661. #endif
  1662. #ifdef USE_ICARUS
  1663. "icarus "
  1664. #endif
  1665. #ifdef USE_KLONDIKE
  1666. "klondike "
  1667. #endif
  1668. #ifdef USE_KNC
  1669. "KnC "
  1670. #endif
  1671. #ifdef USE_BAB
  1672. "BaB "
  1673. #endif
  1674. #ifdef USE_MINION
  1675. "minion "
  1676. #endif
  1677. #ifdef USE_MODMINER
  1678. "modminer "
  1679. #endif
  1680. #ifdef USE_BITMINE_A1
  1681. "Bitmine.A1 "
  1682. #endif
  1683. #ifdef USE_SP10
  1684. "spondoolies "
  1685. #endif
  1686. #ifdef USE_SP30
  1687. "sp30 "
  1688. #endif
  1689. #ifdef USE_GRIDSEED
  1690. "GridSeed "
  1691. #endif
  1692. #ifdef USE_ZEUS
  1693. "Zeus "
  1694. #endif
  1695. #ifdef USE_LKETC
  1696. "Lketc "
  1697. #endif
  1698. #ifdef USE_SCRYPT
  1699. "scrypt "
  1700. #endif
  1701. "mining support.\n"
  1702. , packagename);
  1703. printf("%s", opt_usage(opt_argv0, extra));
  1704. fflush(stdout);
  1705. exit(0);
  1706. }
  1707. #if defined(USE_USBUTILS)
  1708. char *display_devs(int *ndevs)
  1709. {
  1710. *ndevs = 0;
  1711. usb_all(0);
  1712. exit(*ndevs);
  1713. }
  1714. #endif
  1715. /* These options are available from commandline only */
  1716. static struct opt_table opt_cmdline_table[] = {
  1717. OPT_WITH_ARG("--config|-c",
  1718. load_config, NULL, &opt_set_null,
  1719. "Load a JSON-format configuration file\n"
  1720. "See example.conf for an example configuration."),
  1721. OPT_WITH_ARG("--default-config",
  1722. set_default_config, NULL, &opt_set_null,
  1723. "Specify the filename of the default config file\n"
  1724. "Loaded at start and used when saving without a name."),
  1725. OPT_WITHOUT_ARG("--help|-h",
  1726. opt_verusage_and_exit, NULL,
  1727. "Print this message"),
  1728. #if defined(USE_USBUTILS)
  1729. OPT_WITHOUT_ARG("--ndevs|-n",
  1730. display_devs, &nDevs,
  1731. "Display all USB devices and exit"),
  1732. #endif
  1733. OPT_WITHOUT_ARG("--version|-V",
  1734. opt_version_and_exit, packagename,
  1735. "Display version and exit"),
  1736. OPT_ENDTABLE
  1737. };
  1738. #ifdef HAVE_LIBCURL
  1739. static bool jobj_binary(const json_t *obj, const char *key,
  1740. void *buf, size_t buflen, bool required)
  1741. {
  1742. const char *hexstr;
  1743. json_t *tmp;
  1744. tmp = json_object_get(obj, key);
  1745. if (unlikely(!tmp)) {
  1746. if (unlikely(required))
  1747. applog(LOG_ERR, "JSON key '%s' not found", key);
  1748. return false;
  1749. }
  1750. hexstr = json_string_value(tmp);
  1751. if (unlikely(!hexstr)) {
  1752. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1753. return false;
  1754. }
  1755. if (!hex2bin(buf, hexstr, buflen))
  1756. return false;
  1757. return true;
  1758. }
  1759. #endif
  1760. static void calc_midstate(struct work *work)
  1761. {
  1762. unsigned char data[64];
  1763. uint32_t *data32 = (uint32_t *)data;
  1764. sha256_ctx ctx;
  1765. flip64(data32, work->data);
  1766. sha256_init(&ctx);
  1767. sha256_update(&ctx, data, 64);
  1768. memcpy(work->midstate, ctx.h, 32);
  1769. endian_flip32(work->midstate, work->midstate);
  1770. }
  1771. /* Returns the current value of total_work and increments it */
  1772. static int total_work_inc(void)
  1773. {
  1774. int ret;
  1775. cg_wlock(&control_lock);
  1776. ret = total_work++;
  1777. cg_wunlock(&control_lock);
  1778. return ret;
  1779. }
  1780. static struct work *make_work(void)
  1781. {
  1782. struct work *work = calloc(1, sizeof(struct work));
  1783. if (unlikely(!work))
  1784. quit(1, "Failed to calloc work in make_work");
  1785. work->id = total_work_inc();
  1786. return work;
  1787. }
  1788. /* This is the central place all work that is about to be retired should be
  1789. * cleaned to remove any dynamically allocated arrays within the struct */
  1790. void clean_work(struct work *work)
  1791. {
  1792. free(work->job_id);
  1793. free(work->ntime);
  1794. free(work->coinbase);
  1795. free(work->nonce1);
  1796. memset(work, 0, sizeof(struct work));
  1797. }
  1798. /* All dynamically allocated work structs should be freed here to not leak any
  1799. * ram from arrays allocated within the work struct */
  1800. void _free_work(struct work *work)
  1801. {
  1802. clean_work(work);
  1803. free(work);
  1804. }
  1805. static void gen_hash(unsigned char *data, unsigned char *hash, int len);
  1806. static void calc_diff(struct work *work, double known);
  1807. char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
  1808. #ifdef HAVE_LIBCURL
  1809. /* Process transactions with GBT by storing the binary value of the first
  1810. * transaction, and the hashes of the remaining transactions since these
  1811. * remain constant with an altered coinbase when generating work. Must be
  1812. * entered under gbt_lock */
  1813. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr);
  1814. static void __build_gbt_txns(struct pool *pool, json_t *res_val)
  1815. {
  1816. json_t *txn_array;
  1817. txn_array = json_object_get(res_val, "transactions");
  1818. gbt_merkle_bins(pool, txn_array);
  1819. }
  1820. static void __gbt_merkleroot(struct pool *pool, unsigned char *merkle_root)
  1821. {
  1822. unsigned char merkle_sha[64];
  1823. int i;
  1824. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  1825. memcpy(merkle_sha, merkle_root, 32);
  1826. for (i = 0; i < pool->merkles; i++) {
  1827. memcpy(merkle_sha + 32, pool->merklebin + i * 32, 32);
  1828. gen_hash(merkle_sha, merkle_root, 64);
  1829. memcpy(merkle_sha, merkle_root, 32);
  1830. }
  1831. }
  1832. static bool work_decode(struct pool *pool, struct work *work, json_t *val);
  1833. static void update_gbt(struct pool *pool)
  1834. {
  1835. int rolltime;
  1836. json_t *val;
  1837. CURL *curl;
  1838. curl = curl_easy_init();
  1839. if (unlikely(!curl))
  1840. quit (1, "CURL initialisation failed in update_gbt");
  1841. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  1842. pool->rpc_req, true, false, &rolltime, pool, false);
  1843. if (val) {
  1844. struct work *work = make_work();
  1845. bool rc = work_decode(pool, work, val);
  1846. total_getworks++;
  1847. pool->getwork_requested++;
  1848. if (rc) {
  1849. applog(LOG_DEBUG, "Successfully retrieved and updated GBT from pool %u %s",
  1850. pool->pool_no, pool->rpc_url);
  1851. if (pool == current_pool())
  1852. opt_work_update = true;
  1853. } else {
  1854. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher GBT from pool %u %s",
  1855. pool->pool_no, pool->rpc_url);
  1856. }
  1857. json_decref(val);
  1858. free_work(work);
  1859. } else {
  1860. applog(LOG_DEBUG, "FAILED to update GBT from pool %u %s",
  1861. pool->pool_no, pool->rpc_url);
  1862. }
  1863. curl_easy_cleanup(curl);
  1864. }
  1865. static void gen_gbt_work(struct pool *pool, struct work *work)
  1866. {
  1867. unsigned char merkleroot[32];
  1868. struct timeval now;
  1869. uint64_t nonce2le;
  1870. cgtime(&now);
  1871. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  1872. update_gbt(pool);
  1873. cg_wlock(&pool->gbt_lock);
  1874. nonce2le = htole64(pool->nonce2);
  1875. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  1876. pool->nonce2++;
  1877. cg_dwlock(&pool->gbt_lock);
  1878. __gbt_merkleroot(pool, merkleroot);
  1879. memcpy(work->data, &pool->gbt_version, 4);
  1880. memcpy(work->data + 4, pool->previousblockhash, 32);
  1881. memcpy(work->data + 4 + 32 + 32, &pool->curtime, 4);
  1882. memcpy(work->data + 4 + 32 + 32 + 4, &pool->gbt_bits, 4);
  1883. memcpy(work->target, pool->gbt_target, 32);
  1884. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  1885. /* For encoding the block data on submission */
  1886. work->gbt_txns = pool->gbt_txns + 1;
  1887. if (pool->gbt_workid)
  1888. work->job_id = strdup(pool->gbt_workid);
  1889. cg_runlock(&pool->gbt_lock);
  1890. flip32(work->data + 4 + 32, merkleroot);
  1891. memset(work->data + 4 + 32 + 32 + 4 + 4, 0, 4); /* nonce */
  1892. hex2bin(work->data + 4 + 32 + 32 + 4 + 4 + 4, workpadding, 48);
  1893. if (opt_debug) {
  1894. char *header = bin2hex(work->data, 128);
  1895. applog(LOG_DEBUG, "Generated GBT header %s", header);
  1896. applog(LOG_DEBUG, "Work coinbase %s", work->coinbase);
  1897. free(header);
  1898. }
  1899. calc_midstate(work);
  1900. local_work++;
  1901. work->pool = pool;
  1902. work->gbt = true;
  1903. work->longpoll = false;
  1904. work->getwork_mode = GETWORK_MODE_GBT;
  1905. work->work_block = work_block;
  1906. /* Nominally allow a driver to ntime roll 60 seconds */
  1907. work->drv_rolllimit = 60;
  1908. calc_diff(work, 0);
  1909. cgtime(&work->tv_staged);
  1910. }
  1911. static bool gbt_decode(struct pool *pool, json_t *res_val)
  1912. {
  1913. const char *previousblockhash;
  1914. const char *target;
  1915. const char *coinbasetxn;
  1916. const char *longpollid;
  1917. unsigned char hash_swap[32];
  1918. int expires;
  1919. int version;
  1920. int curtime;
  1921. bool submitold;
  1922. const char *bits;
  1923. const char *workid;
  1924. int cbt_len, orig_len;
  1925. uint8_t *extra_len;
  1926. size_t cal_len;
  1927. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  1928. target = json_string_value(json_object_get(res_val, "target"));
  1929. coinbasetxn = json_string_value(json_object_get(json_object_get(res_val, "coinbasetxn"), "data"));
  1930. longpollid = json_string_value(json_object_get(res_val, "longpollid"));
  1931. expires = json_integer_value(json_object_get(res_val, "expires"));
  1932. version = json_integer_value(json_object_get(res_val, "version"));
  1933. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  1934. submitold = json_is_true(json_object_get(res_val, "submitold"));
  1935. bits = json_string_value(json_object_get(res_val, "bits"));
  1936. workid = json_string_value(json_object_get(res_val, "workid"));
  1937. if (!previousblockhash || !target || !coinbasetxn || !longpollid ||
  1938. !expires || !version || !curtime || !bits) {
  1939. applog(LOG_ERR, "JSON failed to decode GBT");
  1940. return false;
  1941. }
  1942. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  1943. applog(LOG_DEBUG, "target: %s", target);
  1944. applog(LOG_DEBUG, "coinbasetxn: %s", coinbasetxn);
  1945. applog(LOG_DEBUG, "longpollid: %s", longpollid);
  1946. applog(LOG_DEBUG, "expires: %d", expires);
  1947. applog(LOG_DEBUG, "version: %d", version);
  1948. applog(LOG_DEBUG, "curtime: %d", curtime);
  1949. applog(LOG_DEBUG, "submitold: %s", submitold ? "true" : "false");
  1950. applog(LOG_DEBUG, "bits: %s", bits);
  1951. if (workid)
  1952. applog(LOG_DEBUG, "workid: %s", workid);
  1953. cg_wlock(&pool->gbt_lock);
  1954. free(pool->coinbasetxn);
  1955. pool->coinbasetxn = strdup(coinbasetxn);
  1956. cbt_len = strlen(pool->coinbasetxn) / 2;
  1957. /* We add 8 bytes of extra data corresponding to nonce2 */
  1958. pool->n2size = 8;
  1959. pool->coinbase_len = cbt_len + pool->n2size;
  1960. cal_len = pool->coinbase_len + 1;
  1961. align_len(&cal_len);
  1962. free(pool->coinbase);
  1963. pool->coinbase = calloc(cal_len, 1);
  1964. if (unlikely(!pool->coinbase))
  1965. quit(1, "Failed to calloc pool coinbase in gbt_decode");
  1966. hex2bin(pool->coinbase, pool->coinbasetxn, 42);
  1967. extra_len = (uint8_t *)(pool->coinbase + 41);
  1968. orig_len = *extra_len;
  1969. hex2bin(pool->coinbase + 42, pool->coinbasetxn + 84, orig_len);
  1970. *extra_len += pool->n2size;
  1971. hex2bin(pool->coinbase + 42 + *extra_len, pool->coinbasetxn + 84 + (orig_len * 2),
  1972. cbt_len - orig_len - 42);
  1973. pool->nonce2_offset = orig_len + 42;
  1974. free(pool->longpollid);
  1975. pool->longpollid = strdup(longpollid);
  1976. free(pool->gbt_workid);
  1977. if (workid)
  1978. pool->gbt_workid = strdup(workid);
  1979. else
  1980. pool->gbt_workid = NULL;
  1981. hex2bin(hash_swap, previousblockhash, 32);
  1982. swap256(pool->previousblockhash, hash_swap);
  1983. hex2bin(hash_swap, target, 32);
  1984. swab256(pool->gbt_target, hash_swap);
  1985. pool->gbt_expires = expires;
  1986. pool->gbt_version = htobe32(version);
  1987. pool->curtime = htobe32(curtime);
  1988. pool->submit_old = submitold;
  1989. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  1990. __build_gbt_txns(pool, res_val);
  1991. cg_wunlock(&pool->gbt_lock);
  1992. return true;
  1993. }
  1994. static bool getwork_decode(json_t *res_val, struct work *work)
  1995. {
  1996. if (unlikely(!jobj_binary(res_val, "data", work->data, sizeof(work->data), true))) {
  1997. applog(LOG_ERR, "JSON inval data");
  1998. return false;
  1999. }
  2000. if (!jobj_binary(res_val, "midstate", work->midstate, sizeof(work->midstate), false)) {
  2001. // Calculate it ourselves
  2002. applog(LOG_DEBUG, "Calculating midstate locally");
  2003. calc_midstate(work);
  2004. }
  2005. if (unlikely(!jobj_binary(res_val, "target", work->target, sizeof(work->target), true))) {
  2006. applog(LOG_ERR, "JSON inval target");
  2007. return false;
  2008. }
  2009. return true;
  2010. }
  2011. /* Returns whether the pool supports local work generation or not. */
  2012. static bool pool_localgen(struct pool *pool)
  2013. {
  2014. return (pool->has_stratum || pool->has_gbt || pool->gbt_solo);
  2015. }
  2016. static void gbt_merkle_bins(struct pool *pool, json_t *transaction_arr)
  2017. {
  2018. unsigned char *hashbin;
  2019. json_t *arr_val;
  2020. int i, j, binleft, binlen;
  2021. free(pool->txn_data);
  2022. pool->txn_data = NULL;
  2023. pool->transactions = 0;
  2024. pool->merkles = 0;
  2025. pool->transactions = json_array_size(transaction_arr);
  2026. binlen = pool->transactions * 32 + 32;
  2027. hashbin = alloca(binlen + 32);
  2028. memset(hashbin, 0, 32);
  2029. binleft = binlen / 32;
  2030. if (pool->transactions) {
  2031. int len = 0, ofs = 0;
  2032. const char *txn;
  2033. for (i = 0; i < pool->transactions; i++) {
  2034. arr_val = json_array_get(transaction_arr, i);
  2035. txn = json_string_value(json_object_get(arr_val, "data"));
  2036. if (!txn) {
  2037. applog(LOG_ERR, "Pool %d json_string_value fail - cannot find transaction data",
  2038. pool->pool_no);
  2039. return;
  2040. }
  2041. len += strlen(txn);
  2042. }
  2043. pool->txn_data = malloc(len + 1);
  2044. if (unlikely(!pool->txn_data))
  2045. quit(1, "Failed to calloc txn_data in gbt_merkle_bins");
  2046. pool->txn_data[len] = '\0';
  2047. for (i = 0; i < pool->transactions; i++) {
  2048. unsigned char binswap[32];
  2049. const char *hash;
  2050. arr_val = json_array_get(transaction_arr, i);
  2051. hash = json_string_value(json_object_get(arr_val, "hash"));
  2052. txn = json_string_value(json_object_get(arr_val, "data"));
  2053. len = strlen(txn);
  2054. memcpy(pool->txn_data + ofs, txn, len);
  2055. ofs += len;
  2056. if (!hash) {
  2057. unsigned char *txn_bin;
  2058. int txn_len;
  2059. txn_len = len / 2;
  2060. txn_bin = malloc(txn_len);
  2061. if (!txn_bin)
  2062. quit(1, "Failed to malloc txn_bin in gbt_merkle_bins");
  2063. hex2bin(txn_bin, txn, txn_len);
  2064. /* This is needed for pooled mining since only
  2065. * transaction data and not hashes are sent */
  2066. gen_hash(txn_bin, hashbin + 32 + 32 * i, txn_len);
  2067. continue;
  2068. }
  2069. if (!hex2bin(binswap, hash, 32)) {
  2070. applog(LOG_ERR, "Failed to hex2bin hash in gbt_merkle_bins");
  2071. return;
  2072. }
  2073. swab256(hashbin + 32 + 32 * i, binswap);
  2074. }
  2075. }
  2076. if (binleft > 1) {
  2077. while (42) {
  2078. if (binleft == 1)
  2079. break;
  2080. memcpy(pool->merklebin + (pool->merkles * 32), hashbin + 32, 32);
  2081. pool->merkles++;
  2082. if (binleft % 2) {
  2083. memcpy(hashbin + binlen, hashbin + binlen - 32, 32);
  2084. binlen += 32;
  2085. binleft++;
  2086. }
  2087. for (i = 32, j = 64; j < binlen; i += 32, j += 64) {
  2088. gen_hash(hashbin + j, hashbin + i, 64);
  2089. }
  2090. binleft /= 2;
  2091. binlen = binleft * 32;
  2092. }
  2093. }
  2094. if (opt_debug) {
  2095. char hashhex[68];
  2096. for (i = 0; i < pool->merkles; i++) {
  2097. __bin2hex(hashhex, pool->merklebin + i * 32, 32);
  2098. applog(LOG_DEBUG, "MH%d %s",i, hashhex);
  2099. }
  2100. }
  2101. applog(LOG_INFO, "Stored %d transactions from pool %d", pool->transactions,
  2102. pool->pool_no);
  2103. }
  2104. static double diff_from_target(void *target);
  2105. static const char scriptsig_header[] = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff";
  2106. static unsigned char scriptsig_header_bin[41];
  2107. static bool gbt_solo_decode(struct pool *pool, json_t *res_val)
  2108. {
  2109. json_t *transaction_arr, *coinbase_aux;
  2110. const char *previousblockhash;
  2111. unsigned char hash_swap[32];
  2112. struct timeval now;
  2113. const char *target;
  2114. uint64_t coinbasevalue;
  2115. const char *flags;
  2116. const char *bits;
  2117. char header[228];
  2118. int ofs = 0, len;
  2119. uint64_t *u64;
  2120. uint32_t *u32;
  2121. int version;
  2122. int curtime;
  2123. int height;
  2124. previousblockhash = json_string_value(json_object_get(res_val, "previousblockhash"));
  2125. target = json_string_value(json_object_get(res_val, "target"));
  2126. transaction_arr = json_object_get(res_val, "transactions");
  2127. version = json_integer_value(json_object_get(res_val, "version"));
  2128. curtime = json_integer_value(json_object_get(res_val, "curtime"));
  2129. bits = json_string_value(json_object_get(res_val, "bits"));
  2130. height = json_integer_value(json_object_get(res_val, "height"));
  2131. coinbasevalue = json_integer_value(json_object_get(res_val, "coinbasevalue"));
  2132. coinbase_aux = json_object_get(res_val, "coinbaseaux");
  2133. flags = json_string_value(json_object_get(coinbase_aux, "flags"));
  2134. if (!previousblockhash || !target || !version || !curtime || !bits || !coinbase_aux || !flags) {
  2135. applog(LOG_ERR, "Pool %d JSON failed to decode GBT", pool->pool_no);
  2136. return false;
  2137. }
  2138. applog(LOG_DEBUG, "previousblockhash: %s", previousblockhash);
  2139. applog(LOG_DEBUG, "target: %s", target);
  2140. applog(LOG_DEBUG, "version: %d", version);
  2141. applog(LOG_DEBUG, "curtime: %d", curtime);
  2142. applog(LOG_DEBUG, "bits: %s", bits);
  2143. applog(LOG_DEBUG, "height: %d", height);
  2144. applog(LOG_DEBUG, "flags: %s", flags);
  2145. cg_wlock(&pool->gbt_lock);
  2146. hex2bin(hash_swap, previousblockhash, 32);
  2147. swap256(pool->previousblockhash, hash_swap);
  2148. __bin2hex(pool->prev_hash, pool->previousblockhash, 32);
  2149. hex2bin(hash_swap, target, 32);
  2150. swab256(pool->gbt_target, hash_swap);
  2151. pool->sdiff = diff_from_target(pool->gbt_target);
  2152. pool->gbt_version = htobe32(version);
  2153. pool->curtime = htobe32(curtime);
  2154. snprintf(pool->ntime, 9, "%08x", curtime);
  2155. snprintf(pool->bbversion, 9, "%08x", version);
  2156. snprintf(pool->nbit, 9, "%s", bits);
  2157. pool->nValue = coinbasevalue;
  2158. hex2bin((unsigned char *)&pool->gbt_bits, bits, 4);
  2159. gbt_merkle_bins(pool, transaction_arr);
  2160. pool->height = height;
  2161. memset(pool->scriptsig_base, 0, 42);
  2162. ofs++; // Leave room for template length
  2163. /* Put block height at start of template. */
  2164. ofs += ser_number(pool->scriptsig_base + ofs, height); // max 5
  2165. /* Followed by flags */
  2166. len = strlen(flags) / 2;
  2167. pool->scriptsig_base[ofs++] = len;
  2168. hex2bin(pool->scriptsig_base + ofs, flags, len);
  2169. ofs += len;
  2170. /* Followed by timestamp */
  2171. cgtime(&now);
  2172. pool->scriptsig_base[ofs++] = 0xfe; // Encode seconds as u32
  2173. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2174. *u32 = htole32(now.tv_sec);
  2175. ofs += 4; // sizeof uint32_t
  2176. pool->scriptsig_base[ofs++] = 0xfe; // Encode usecs as u32
  2177. u32 = (uint32_t *)&pool->scriptsig_base[ofs];
  2178. *u32 = htole32(now.tv_usec);
  2179. ofs += 4; // sizeof uint32_t
  2180. memcpy(pool->scriptsig_base + ofs, "\x09\x63\x67\x6d\x69\x6e\x65\x72\x34\x32", 10);
  2181. ofs += 10;
  2182. /* Followed by extranonce size, fixed at 8 */
  2183. pool->scriptsig_base[ofs++] = 8;
  2184. pool->nonce2_offset = 41 + ofs;
  2185. ofs += 8;
  2186. if (opt_btc_sig) {
  2187. len = strlen(opt_btc_sig);
  2188. if (len > 32)
  2189. len = 32;
  2190. pool->scriptsig_base[ofs++] = len;
  2191. memcpy(pool->scriptsig_base + ofs, opt_btc_sig, len);
  2192. ofs += len;
  2193. }
  2194. pool->scriptsig_base[0] = ofs++; // Template length
  2195. pool->n1_len = ofs;
  2196. len = 41 // prefix
  2197. + ofs // Template length
  2198. + 4 // txin sequence no
  2199. + 1 // transactions
  2200. + 8 // value
  2201. + 1 + 25 // txout
  2202. + 4; // lock
  2203. free(pool->coinbase);
  2204. pool->coinbase = calloc(len, 1);
  2205. if (unlikely(!pool->coinbase))
  2206. quit(1, "Failed to calloc coinbase in gbt_solo_decode");
  2207. memcpy(pool->coinbase + 41, pool->scriptsig_base, ofs);
  2208. memcpy(pool->coinbase + 41 + ofs, "\xff\xff\xff\xff", 4);
  2209. pool->coinbase[41 + ofs + 4] = 1;
  2210. u64 = (uint64_t *)&(pool->coinbase[41 + ofs + 4 + 1]);
  2211. *u64 = htole64(coinbasevalue);
  2212. pool->nonce2 = 0;
  2213. pool->n2size = 4;
  2214. pool->coinbase_len = 41 + ofs + 4 + 1 + 8 + 1 + 25 + 4;
  2215. cg_wunlock(&pool->gbt_lock);
  2216. snprintf(header, 225, "%s%s%s%s%s%s%s",
  2217. pool->bbversion,
  2218. pool->prev_hash,
  2219. "0000000000000000000000000000000000000000000000000000000000000000",
  2220. pool->ntime,
  2221. pool->nbit,
  2222. "00000000", /* nonce */
  2223. workpadding);
  2224. if (unlikely(!hex2bin(pool->header_bin, header, 112)))
  2225. quit(1, "Failed to hex2bin header in gbt_solo_decode");
  2226. return true;
  2227. }
  2228. static bool work_decode(struct pool *pool, struct work *work, json_t *val)
  2229. {
  2230. json_t *res_val = json_object_get(val, "result");
  2231. bool ret = false;
  2232. cgtime(&pool->tv_lastwork);
  2233. if (!res_val || json_is_null(res_val)) {
  2234. applog(LOG_ERR, "JSON Failed to decode result");
  2235. goto out;
  2236. }
  2237. if (pool->gbt_solo) {
  2238. if (unlikely(!gbt_solo_decode(pool, res_val)))
  2239. goto out;
  2240. ret = true;
  2241. goto out;
  2242. } else if (pool->has_gbt) {
  2243. if (unlikely(!gbt_decode(pool, res_val)))
  2244. goto out;
  2245. work->gbt = true;
  2246. ret = true;
  2247. goto out;
  2248. } else if (unlikely(!getwork_decode(res_val, work)))
  2249. goto out;
  2250. memset(work->hash, 0, sizeof(work->hash));
  2251. cgtime(&work->tv_staged);
  2252. ret = true;
  2253. out:
  2254. return ret;
  2255. }
  2256. #else /* HAVE_LIBCURL */
  2257. /* Always true with stratum */
  2258. #define pool_localgen(pool) (true)
  2259. #define json_rpc_call(curl, url, userpass, rpc_req, probe, longpoll, rolltime, pool, share) (NULL)
  2260. #define work_decode(pool, work, val) (false)
  2261. #define gen_gbt_work(pool, work) {}
  2262. #endif /* HAVE_LIBCURL */
  2263. int dev_from_id(int thr_id)
  2264. {
  2265. struct cgpu_info *cgpu = get_thr_cgpu(thr_id);
  2266. return cgpu->device_id;
  2267. }
  2268. /* Create an exponentially decaying average over the opt_log_interval */
  2269. void decay_time(double *f, double fadd, double fsecs, double interval)
  2270. {
  2271. double ftotal, fprop;
  2272. if (fsecs <= 0)
  2273. return;
  2274. fprop = 1.0 - 1 / (exp(fsecs / interval));
  2275. ftotal = 1.0 + fprop;
  2276. *f += (fadd / fsecs * fprop);
  2277. *f /= ftotal;
  2278. }
  2279. static int __total_staged(void)
  2280. {
  2281. return HASH_COUNT(staged_work);
  2282. }
  2283. static int total_staged(void)
  2284. {
  2285. int ret;
  2286. mutex_lock(stgd_lock);
  2287. ret = __total_staged();
  2288. mutex_unlock(stgd_lock);
  2289. return ret;
  2290. }
  2291. #ifdef HAVE_CURSES
  2292. WINDOW *mainwin, *statuswin, *logwin;
  2293. #endif
  2294. double total_secs = 1.0;
  2295. static char statusline[256];
  2296. /* logstart is where the log window should start */
  2297. static int devcursor, logstart, logcursor;
  2298. #ifdef HAVE_CURSES
  2299. /* statusy is where the status window goes up to in cases where it won't fit at startup */
  2300. static int statusy;
  2301. #endif
  2302. #ifdef HAVE_CURSES
  2303. static inline void unlock_curses(void)
  2304. {
  2305. mutex_unlock(&console_lock);
  2306. }
  2307. static inline void lock_curses(void)
  2308. {
  2309. mutex_lock(&console_lock);
  2310. }
  2311. static bool curses_active_locked(void)
  2312. {
  2313. bool ret;
  2314. lock_curses();
  2315. ret = curses_active;
  2316. if (!ret)
  2317. unlock_curses();
  2318. return ret;
  2319. }
  2320. #endif
  2321. /* Convert a uint64_t value into a truncated string for displaying with its
  2322. * associated suitable for Mega, Giga etc. Buf array needs to be long enough */
  2323. static void suffix_string(uint64_t val, char *buf, size_t bufsiz, int sigdigits)
  2324. {
  2325. const double dkilo = 1000.0;
  2326. const uint64_t kilo = 1000ull;
  2327. const uint64_t mega = 1000000ull;
  2328. const uint64_t giga = 1000000000ull;
  2329. const uint64_t tera = 1000000000000ull;
  2330. const uint64_t peta = 1000000000000000ull;
  2331. const uint64_t exa = 1000000000000000000ull;
  2332. char suffix[2] = "";
  2333. bool decimal = true;
  2334. double dval;
  2335. if (val >= exa) {
  2336. val /= peta;
  2337. dval = (double)val / dkilo;
  2338. strcpy(suffix, "E");
  2339. } else if (val >= peta) {
  2340. val /= tera;
  2341. dval = (double)val / dkilo;
  2342. strcpy(suffix, "P");
  2343. } else if (val >= tera) {
  2344. val /= giga;
  2345. dval = (double)val / dkilo;
  2346. strcpy(suffix, "T");
  2347. } else if (val >= giga) {
  2348. val /= mega;
  2349. dval = (double)val / dkilo;
  2350. strcpy(suffix, "G");
  2351. } else if (val >= mega) {
  2352. val /= kilo;
  2353. dval = (double)val / dkilo;
  2354. strcpy(suffix, "M");
  2355. } else if (val >= kilo) {
  2356. dval = (double)val / dkilo;
  2357. strcpy(suffix, "K");
  2358. } else {
  2359. dval = val;
  2360. decimal = false;
  2361. }
  2362. if (!sigdigits) {
  2363. if (decimal)
  2364. snprintf(buf, bufsiz, "%.3g%s", dval, suffix);
  2365. else
  2366. snprintf(buf, bufsiz, "%d%s", (unsigned int)dval, suffix);
  2367. } else {
  2368. /* Always show sigdigits + 1, padded on right with zeroes
  2369. * followed by suffix */
  2370. int ndigits = sigdigits - 1 - (dval > 0.0 ? floor(log10(dval)) : 0);
  2371. snprintf(buf, bufsiz, "%*.*f%s", sigdigits + 1, ndigits, dval, suffix);
  2372. }
  2373. }
  2374. double cgpu_runtime(struct cgpu_info *cgpu)
  2375. {
  2376. struct timeval now;
  2377. double dev_runtime;
  2378. if (cgpu->dev_start_tv.tv_sec == 0)
  2379. dev_runtime = total_secs;
  2380. else {
  2381. cgtime(&now);
  2382. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2383. }
  2384. if (dev_runtime < 1.0)
  2385. dev_runtime = 1.0;
  2386. return dev_runtime;
  2387. }
  2388. double tsince_restart(void)
  2389. {
  2390. struct timeval now;
  2391. cgtime(&now);
  2392. return tdiff(&now, &restart_tv_start);
  2393. }
  2394. double tsince_update(void)
  2395. {
  2396. struct timeval now;
  2397. cgtime(&now);
  2398. return tdiff(&now, &update_tv_start);
  2399. }
  2400. static void get_statline(char *buf, size_t bufsiz, struct cgpu_info *cgpu)
  2401. {
  2402. char displayed_hashes[16], displayed_rolling[16];
  2403. double dev_runtime, wu;
  2404. uint64_t dh64, dr64;
  2405. dev_runtime = cgpu_runtime(cgpu);
  2406. wu = cgpu->diff1 / dev_runtime * 60.0;
  2407. dh64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2408. dr64 = (double)cgpu->rolling * 1000000ull;
  2409. suffix_string(dh64, displayed_hashes, sizeof(displayed_hashes), 4);
  2410. suffix_string(dr64, displayed_rolling, sizeof(displayed_rolling), 4);
  2411. snprintf(buf, bufsiz, "%s%d ", cgpu->drv->name, cgpu->device_id);
  2412. cgpu->drv->get_statline_before(buf, bufsiz, cgpu);
  2413. tailsprintf(buf, bufsiz, "(%ds):%s (avg):%sh/s | A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2414. opt_log_interval,
  2415. displayed_rolling,
  2416. displayed_hashes,
  2417. cgpu->diff_accepted,
  2418. cgpu->diff_rejected,
  2419. cgpu->hw_errors,
  2420. wu);
  2421. cgpu->drv->get_statline(buf, bufsiz, cgpu);
  2422. }
  2423. static bool shared_strategy(void)
  2424. {
  2425. return (pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE);
  2426. }
  2427. #ifdef HAVE_CURSES
  2428. #define CURBUFSIZ 256
  2429. #define cg_mvwprintw(win, y, x, fmt, ...) do { \
  2430. char tmp42[CURBUFSIZ]; \
  2431. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2432. mvwprintw(win, y, x, "%s", tmp42); \
  2433. } while (0)
  2434. #define cg_wprintw(win, fmt, ...) do { \
  2435. char tmp42[CURBUFSIZ]; \
  2436. snprintf(tmp42, sizeof(tmp42), fmt, ##__VA_ARGS__); \
  2437. wprintw(win, "%s", tmp42); \
  2438. } while (0)
  2439. /* Must be called with curses mutex lock held and curses_active */
  2440. static void curses_print_status(void)
  2441. {
  2442. struct pool *pool = current_pool();
  2443. int linewidth = opt_widescreen ? 100 : 80;
  2444. wattron(statuswin, A_BOLD);
  2445. cg_mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  2446. wattroff(statuswin, A_BOLD);
  2447. mvwhline(statuswin, 1, 0, '-', linewidth);
  2448. cg_mvwprintw(statuswin, 2, 0, " %s", statusline);
  2449. wclrtoeol(statuswin);
  2450. if (opt_widescreen) {
  2451. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m |"
  2452. " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2453. total_diff_accepted, total_diff_rejected, hw_errors,
  2454. total_diff1 / total_secs * 60,
  2455. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2456. } else if (alt_status) {
  2457. cg_mvwprintw(statuswin, 3, 0, " ST: %d SS: %"PRId64" NB: %d LW: %d GF: %d RF: %d",
  2458. total_staged(), total_stale, new_blocks, local_work, total_go, total_ro);
  2459. } else {
  2460. cg_mvwprintw(statuswin, 3, 0, " A:%.0f R:%.0f HW:%d WU:%.1f/m",
  2461. total_diff_accepted, total_diff_rejected, hw_errors,
  2462. total_diff1 / total_secs * 60);
  2463. }
  2464. wclrtoeol(statuswin);
  2465. if (shared_strategy() && total_pools > 1) {
  2466. cg_mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s block change notify",
  2467. have_longpoll ? "": "out");
  2468. } else if (pool->has_stratum) {
  2469. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with stratum as user %s",
  2470. pool->sockaddr_url, pool->diff, pool->rpc_user);
  2471. } else {
  2472. cg_mvwprintw(statuswin, 4, 0, " Connected to %s diff %s with%s %s as user %s",
  2473. pool->sockaddr_url, pool->diff, have_longpoll ? "": "out",
  2474. pool->has_gbt ? "GBT" : "LP", pool->rpc_user);
  2475. }
  2476. wclrtoeol(statuswin);
  2477. cg_mvwprintw(statuswin, 5, 0, " Block: %s... Diff:%s Started: %s Best share: %s ",
  2478. prev_block, block_diff, blocktime, best_share);
  2479. mvwhline(statuswin, 6, 0, '-', linewidth);
  2480. mvwhline(statuswin, statusy - 1, 0, '-', linewidth);
  2481. #ifdef USE_USBUTILS
  2482. cg_mvwprintw(statuswin, devcursor - 1, 1, "[U]SB management [P]ool management [S]ettings [D]isplay options [Q]uit");
  2483. #else
  2484. cg_mvwprintw(statuswin, devcursor - 1, 1, "[P]ool management [S]ettings [D]isplay options [Q]uit");
  2485. #endif
  2486. }
  2487. static void adj_width(int var, int *length)
  2488. {
  2489. if ((int)(log10(var) + 1) > *length)
  2490. (*length)++;
  2491. }
  2492. static void adj_fwidth(float var, int *length)
  2493. {
  2494. if ((int)(log10(var) + 1) > *length)
  2495. (*length)++;
  2496. }
  2497. #define STATBEFORELEN 23
  2498. const char blanks[] = " ";
  2499. static void curses_print_devstatus(struct cgpu_info *cgpu, int devno, int count)
  2500. {
  2501. static int devno_width = 1, uid_width = 4, dawidth = 1, drwidth = 1, hwwidth = 1, wuwidth = 1;
  2502. char logline[256], unique_id[16];
  2503. struct timeval now;
  2504. double dev_runtime, wu;
  2505. unsigned int devstatlen;
  2506. if (opt_compact)
  2507. return;
  2508. if (devcursor + count > LINES - 2)
  2509. return;
  2510. if (count >= most_devices)
  2511. return;
  2512. if (cgpu->dev_start_tv.tv_sec == 0)
  2513. dev_runtime = total_secs;
  2514. else {
  2515. cgtime(&now);
  2516. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  2517. }
  2518. if (dev_runtime < 1.0)
  2519. dev_runtime = 1.0;
  2520. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  2521. wu = cgpu->diff1 / dev_runtime * 60;
  2522. wmove(statuswin,devcursor + count, 0);
  2523. adj_width(devno, &devno_width);
  2524. if (cgpu->unique_id) {
  2525. if (uid_width < 12 && (int)strlen(cgpu->unique_id) > uid_width)
  2526. uid_width = MIN(strlen(cgpu->unique_id), 12); // maximum length 12
  2527. unique_id[4] = '\0';
  2528. memcpy(unique_id, blanks, 4); // minimum length 4
  2529. strncpy(unique_id, cgpu->unique_id, uid_width);
  2530. unique_id[uid_width] = '\0';
  2531. } else {
  2532. adj_width(cgpu->device_id, &uid_width);
  2533. if (uid_width < 4)
  2534. uid_width = 4;
  2535. if (uid_width > 12)
  2536. uid_width = 12;
  2537. sprintf(unique_id, "%-*d", uid_width, cgpu->device_id);
  2538. }
  2539. cg_wprintw(statuswin, " %*d: %s %-*s: ", devno_width, devno, cgpu->drv->name,
  2540. uid_width, unique_id);
  2541. logline[0] = '\0';
  2542. cgpu->drv->get_statline_before(logline, sizeof(logline), cgpu);
  2543. devstatlen = strlen(logline);
  2544. if (devstatlen < STATBEFORELEN)
  2545. strncat(logline, blanks, STATBEFORELEN - devstatlen);
  2546. cg_wprintw(statuswin, "%s | ", logline);
  2547. #ifdef USE_USBUTILS
  2548. if (cgpu->usbinfo.nodev)
  2549. cg_wprintw(statuswin, "ZOMBIE");
  2550. else
  2551. #endif
  2552. if (cgpu->status == LIFE_DEAD)
  2553. cg_wprintw(statuswin, "DEAD ");
  2554. else if (cgpu->status == LIFE_SICK)
  2555. cg_wprintw(statuswin, "SICK ");
  2556. else if (cgpu->deven == DEV_DISABLED)
  2557. cg_wprintw(statuswin, "OFF ");
  2558. else if (cgpu->deven == DEV_RECOVER)
  2559. cg_wprintw(statuswin, "REST ");
  2560. else if (opt_widescreen) {
  2561. char displayed_hashes[16], displayed_rolling[16];
  2562. uint64_t d64;
  2563. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2564. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2565. d64 = (double)cgpu->rolling * 1000000ull;
  2566. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2567. adj_width(wu, &wuwidth);
  2568. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2569. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2570. adj_width(cgpu->hw_errors, &hwwidth);
  2571. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m "
  2572. "A:%*.0f R:%*.0f HW:%*d",
  2573. displayed_rolling,
  2574. displayed_hashes, wuwidth + 2, wu,
  2575. dawidth, cgpu->diff_accepted,
  2576. drwidth, cgpu->diff_rejected,
  2577. hwwidth, cgpu->hw_errors);
  2578. } else if (!alt_status) {
  2579. char displayed_hashes[16], displayed_rolling[16];
  2580. uint64_t d64;
  2581. d64 = (double)cgpu->total_mhashes / dev_runtime * 1000000ull;
  2582. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  2583. d64 = (double)cgpu->rolling * 1000000ull;
  2584. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  2585. adj_width(wu, &wuwidth);
  2586. cg_wprintw(statuswin, "%6s / %6sh/s WU:%*.1f/m", displayed_rolling,
  2587. displayed_hashes, wuwidth + 2, wu);
  2588. } else {
  2589. adj_fwidth(cgpu->diff_accepted, &dawidth);
  2590. adj_fwidth(cgpu->diff_rejected, &drwidth);
  2591. adj_width(cgpu->hw_errors, &hwwidth);
  2592. cg_wprintw(statuswin, "A:%*.0f R:%*.0f HW:%*d",
  2593. dawidth, cgpu->diff_accepted,
  2594. drwidth, cgpu->diff_rejected,
  2595. hwwidth, cgpu->hw_errors);
  2596. }
  2597. logline[0] = '\0';
  2598. cgpu->drv->get_statline(logline, sizeof(logline), cgpu);
  2599. cg_wprintw(statuswin, "%s", logline);
  2600. wclrtoeol(statuswin);
  2601. }
  2602. #endif
  2603. #ifdef HAVE_CURSES
  2604. /* Check for window resize. Called with curses mutex locked */
  2605. static inline void change_logwinsize(void)
  2606. {
  2607. int x, y, logx, logy;
  2608. getmaxyx(mainwin, y, x);
  2609. if (x < 80 || y < 25)
  2610. return;
  2611. if (y > statusy + 2 && statusy < logstart) {
  2612. if (y - 2 < logstart)
  2613. statusy = y - 2;
  2614. else
  2615. statusy = logstart;
  2616. logcursor = statusy + 1;
  2617. mvwin(logwin, logcursor, 0);
  2618. wresize(statuswin, statusy, x);
  2619. }
  2620. y -= logcursor;
  2621. getmaxyx(logwin, logy, logx);
  2622. /* Detect screen size change */
  2623. if (x != logx || y != logy)
  2624. wresize(logwin, y, x);
  2625. }
  2626. static void check_winsizes(void)
  2627. {
  2628. if (!use_curses)
  2629. return;
  2630. if (curses_active_locked()) {
  2631. int y, x;
  2632. erase();
  2633. x = getmaxx(statuswin);
  2634. if (logstart > LINES - 2)
  2635. statusy = LINES - 2;
  2636. else
  2637. statusy = logstart;
  2638. logcursor = statusy;
  2639. wresize(statuswin, statusy, x);
  2640. getmaxyx(mainwin, y, x);
  2641. y -= logcursor;
  2642. wresize(logwin, y, x);
  2643. mvwin(logwin, logcursor, 0);
  2644. unlock_curses();
  2645. }
  2646. }
  2647. static void disable_curses_windows(void);
  2648. static void enable_curses_windows(void);
  2649. static void switch_logsize(bool __maybe_unused newdevs)
  2650. {
  2651. if (curses_active_locked()) {
  2652. #ifdef WIN32
  2653. if (newdevs)
  2654. disable_curses_windows();
  2655. #endif
  2656. if (opt_compact) {
  2657. logstart = devcursor + 1;
  2658. logcursor = logstart + 1;
  2659. } else {
  2660. logstart = devcursor + most_devices + 1;
  2661. logcursor = logstart + 1;
  2662. }
  2663. #ifdef WIN32
  2664. if (newdevs)
  2665. enable_curses_windows();
  2666. #endif
  2667. unlock_curses();
  2668. check_winsizes();
  2669. }
  2670. }
  2671. /* For mandatory printing when mutex is already locked */
  2672. void _wlog(const char *str)
  2673. {
  2674. wprintw(logwin, "%s", str);
  2675. }
  2676. /* Mandatory printing */
  2677. void _wlogprint(const char *str)
  2678. {
  2679. if (curses_active_locked()) {
  2680. wprintw(logwin, "%s", str);
  2681. unlock_curses();
  2682. }
  2683. }
  2684. #endif
  2685. #ifdef HAVE_CURSES
  2686. bool log_curses_only(int prio, const char *datetime, const char *str)
  2687. {
  2688. bool high_prio;
  2689. high_prio = (prio == LOG_WARNING || prio == LOG_ERR);
  2690. if (curses_active_locked()) {
  2691. if (!opt_loginput || high_prio) {
  2692. wprintw(logwin, "%s%s\n", datetime, str);
  2693. if (high_prio) {
  2694. touchwin(logwin);
  2695. wrefresh(logwin);
  2696. }
  2697. }
  2698. unlock_curses();
  2699. return true;
  2700. }
  2701. return false;
  2702. }
  2703. void clear_logwin(void)
  2704. {
  2705. if (curses_active_locked()) {
  2706. erase();
  2707. wclear(logwin);
  2708. unlock_curses();
  2709. }
  2710. }
  2711. void logwin_update(void)
  2712. {
  2713. if (curses_active_locked()) {
  2714. touchwin(logwin);
  2715. wrefresh(logwin);
  2716. unlock_curses();
  2717. }
  2718. }
  2719. #endif
  2720. static void enable_pool(struct pool *pool)
  2721. {
  2722. if (pool->enabled != POOL_ENABLED) {
  2723. enabled_pools++;
  2724. pool->enabled = POOL_ENABLED;
  2725. }
  2726. }
  2727. #ifdef HAVE_CURSES
  2728. static void disable_pool(struct pool *pool)
  2729. {
  2730. if (pool->enabled == POOL_ENABLED)
  2731. enabled_pools--;
  2732. pool->enabled = POOL_DISABLED;
  2733. }
  2734. #endif
  2735. static void reject_pool(struct pool *pool)
  2736. {
  2737. if (pool->enabled == POOL_ENABLED)
  2738. enabled_pools--;
  2739. pool->enabled = POOL_REJECTING;
  2740. }
  2741. static void restart_threads(void);
  2742. /* Theoretically threads could race when modifying accepted and
  2743. * rejected values but the chance of two submits completing at the
  2744. * same time is zero so there is no point adding extra locking */
  2745. static void
  2746. share_result(json_t *val, json_t *res, json_t *err, const struct work *work,
  2747. char *hashshow, bool resubmit, char *worktime)
  2748. {
  2749. struct pool *pool = work->pool;
  2750. struct cgpu_info *cgpu;
  2751. cgpu = get_thr_cgpu(work->thr_id);
  2752. if (json_is_true(res) || (work->gbt && json_is_null(res))) {
  2753. mutex_lock(&stats_lock);
  2754. cgpu->accepted++;
  2755. total_accepted++;
  2756. pool->accepted++;
  2757. cgpu->diff_accepted += work->work_difficulty;
  2758. total_diff_accepted += work->work_difficulty;
  2759. pool->diff_accepted += work->work_difficulty;
  2760. mutex_unlock(&stats_lock);
  2761. pool->seq_rejects = 0;
  2762. cgpu->last_share_pool = pool->pool_no;
  2763. cgpu->last_share_pool_time = time(NULL);
  2764. cgpu->last_share_diff = work->work_difficulty;
  2765. pool->last_share_time = cgpu->last_share_pool_time;
  2766. pool->last_share_diff = work->work_difficulty;
  2767. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2768. if (!QUIET) {
  2769. if (total_pools > 1)
  2770. applog(LOG_NOTICE, "Accepted %s %s %d pool %d %s%s",
  2771. hashshow, cgpu->drv->name, cgpu->device_id, work->pool->pool_no, resubmit ? "(resubmit)" : "", worktime);
  2772. else
  2773. applog(LOG_NOTICE, "Accepted %s %s %d %s%s",
  2774. hashshow, cgpu->drv->name, cgpu->device_id, resubmit ? "(resubmit)" : "", worktime);
  2775. }
  2776. sharelog("accept", work);
  2777. if (opt_shares && total_diff_accepted >= opt_shares) {
  2778. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2779. kill_work();
  2780. return;
  2781. }
  2782. /* Detect if a pool that has been temporarily disabled for
  2783. * continually rejecting shares has started accepting shares.
  2784. * This will only happen with the work returned from a
  2785. * longpoll */
  2786. if (unlikely(pool->enabled == POOL_REJECTING)) {
  2787. applog(LOG_WARNING, "Rejecting pool %d now accepting shares, re-enabling!", pool->pool_no);
  2788. enable_pool(pool);
  2789. switch_pools(NULL);
  2790. }
  2791. /* If we know we found the block we know better than anyone
  2792. * that new work is needed. */
  2793. if (unlikely(work->block))
  2794. restart_threads();
  2795. } else {
  2796. mutex_lock(&stats_lock);
  2797. cgpu->rejected++;
  2798. total_rejected++;
  2799. pool->rejected++;
  2800. cgpu->diff_rejected += work->work_difficulty;
  2801. total_diff_rejected += work->work_difficulty;
  2802. pool->diff_rejected += work->work_difficulty;
  2803. pool->seq_rejects++;
  2804. mutex_unlock(&stats_lock);
  2805. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2806. if (!QUIET) {
  2807. char where[20];
  2808. char disposition[36] = "reject";
  2809. char reason[32];
  2810. strcpy(reason, "");
  2811. if (total_pools > 1)
  2812. snprintf(where, sizeof(where), "pool %d", work->pool->pool_no);
  2813. else
  2814. strcpy(where, "");
  2815. if (!work->gbt)
  2816. res = json_object_get(val, "reject-reason");
  2817. if (res) {
  2818. const char *reasontmp = json_string_value(res);
  2819. size_t reasonLen = strlen(reasontmp);
  2820. if (reasonLen > 28)
  2821. reasonLen = 28;
  2822. reason[0] = ' '; reason[1] = '(';
  2823. memcpy(2 + reason, reasontmp, reasonLen);
  2824. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  2825. memcpy(disposition + 7, reasontmp, reasonLen);
  2826. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  2827. } else if (work->stratum && err) {
  2828. if (json_is_array(err)) {
  2829. json_t *reason_val = json_array_get(err, 1);
  2830. char *reason_str;
  2831. if (reason_val && json_is_string(reason_val)) {
  2832. reason_str = (char *)json_string_value(reason_val);
  2833. snprintf(reason, 31, " (%s)", reason_str);
  2834. }
  2835. } else if (json_is_string(err)) {
  2836. const char *s = json_string_value(err);
  2837. snprintf(reason, 31, " (%s)", s);
  2838. }
  2839. }
  2840. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  2841. hashshow, cgpu->drv->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  2842. sharelog(disposition, work);
  2843. }
  2844. /* Once we have more than a nominal amount of sequential rejects,
  2845. * at least 10 and more than 3 mins at the current utility,
  2846. * disable the pool because some pool error is likely to have
  2847. * ensued. Do not do this if we know the share just happened to
  2848. * be stale due to networking delays.
  2849. */
  2850. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  2851. double utility = total_accepted / total_secs * 60;
  2852. if (pool->seq_rejects > utility * 3 && enabled_pools > 1) {
  2853. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  2854. pool->pool_no, pool->seq_rejects);
  2855. reject_pool(pool);
  2856. if (pool == current_pool())
  2857. switch_pools(NULL);
  2858. pool->seq_rejects = 0;
  2859. }
  2860. }
  2861. }
  2862. }
  2863. static void show_hash(struct work *work, char *hashshow)
  2864. {
  2865. unsigned char rhash[32];
  2866. char diffdisp[16];
  2867. unsigned long h32;
  2868. uint32_t *hash32;
  2869. uint64_t uintdiff;
  2870. int ofs;
  2871. swab256(rhash, work->hash);
  2872. for (ofs = 0; ofs <= 28; ofs ++) {
  2873. if (rhash[ofs])
  2874. break;
  2875. }
  2876. hash32 = (uint32_t *)(rhash + ofs);
  2877. h32 = be32toh(*hash32);
  2878. uintdiff = round(work->work_difficulty);
  2879. suffix_string(work->share_diff, diffdisp, sizeof (diffdisp), 0);
  2880. snprintf(hashshow, 64, "%08lx Diff %s/%"PRIu64"%s", h32, diffdisp, uintdiff,
  2881. work->block? " BLOCK!" : "");
  2882. }
  2883. #ifdef HAVE_LIBCURL
  2884. static void text_print_status(int thr_id)
  2885. {
  2886. struct cgpu_info *cgpu;
  2887. char logline[256];
  2888. cgpu = get_thr_cgpu(thr_id);
  2889. if (cgpu) {
  2890. get_statline(logline, sizeof(logline), cgpu);
  2891. printf("%s\n", logline);
  2892. }
  2893. }
  2894. static void print_status(int thr_id)
  2895. {
  2896. if (!curses_active)
  2897. text_print_status(thr_id);
  2898. }
  2899. static bool submit_upstream_work(struct work *work, CURL *curl, bool resubmit)
  2900. {
  2901. json_t *val, *res, *err;
  2902. char *s;
  2903. bool rc = false;
  2904. int thr_id = work->thr_id;
  2905. struct cgpu_info *cgpu;
  2906. struct pool *pool = work->pool;
  2907. int rolltime;
  2908. struct timeval tv_submit, tv_submit_reply;
  2909. char hashshow[64 + 4] = "";
  2910. char worktime[200] = "";
  2911. struct timeval now;
  2912. double dev_runtime;
  2913. cgpu = get_thr_cgpu(thr_id);
  2914. /* build JSON-RPC request */
  2915. if (work->gbt) {
  2916. char gbt_block[1024], varint[12];
  2917. unsigned char data[80];
  2918. flip80(data, work->data);
  2919. __bin2hex(gbt_block, data, 80); // 160 length
  2920. if (work->gbt_txns < 0xfd) {
  2921. uint8_t val8 = work->gbt_txns;
  2922. __bin2hex(varint, (const unsigned char *)&val8, 1);
  2923. } else if (work->gbt_txns <= 0xffff) {
  2924. uint16_t val16 = htole16(work->gbt_txns);
  2925. strcat(gbt_block, "fd"); // +2
  2926. __bin2hex(varint, (const unsigned char *)&val16, 2);
  2927. } else {
  2928. uint32_t val32 = htole32(work->gbt_txns);
  2929. strcat(gbt_block, "fe"); // +2
  2930. __bin2hex(varint, (const unsigned char *)&val32, 4);
  2931. }
  2932. strcat(gbt_block, varint); // +8 max
  2933. strcat(gbt_block, work->coinbase);
  2934. s = malloc(1024);
  2935. if (unlikely(!s))
  2936. quit(1, "Failed to malloc s in submit_upstream_work");
  2937. sprintf(s, "{\"id\": 0, \"method\": \"submitblock\", \"params\": [\"%s", gbt_block);
  2938. /* Has submit/coinbase support */
  2939. if (!pool->has_gbt) {
  2940. cg_rlock(&pool->gbt_lock);
  2941. if (pool->txn_data)
  2942. s = realloc_strcat(s, pool->txn_data);
  2943. cg_runlock(&pool->gbt_lock);
  2944. }
  2945. if (work->job_id) {
  2946. s = realloc_strcat(s, "\", {\"workid\": \"");
  2947. s = realloc_strcat(s, work->job_id);
  2948. s = realloc_strcat(s, "\"}]}");
  2949. } else
  2950. s = realloc_strcat(s, "\"]}");
  2951. } else {
  2952. char *hexstr;
  2953. endian_flip128(work->data, work->data);
  2954. /* build hex string */
  2955. hexstr = bin2hex(work->data, 118);
  2956. s = strdup("{\"method\": \"getwork\", \"params\": [ \"");
  2957. s = realloc_strcat(s, hexstr);
  2958. s = realloc_strcat(s, "\" ], \"id\":1}");
  2959. free(hexstr);
  2960. }
  2961. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, s);
  2962. s = realloc_strcat(s, "\n");
  2963. cgtime(&tv_submit);
  2964. /* issue JSON-RPC request */
  2965. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  2966. cgtime(&tv_submit_reply);
  2967. free(s);
  2968. if (unlikely(!val)) {
  2969. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  2970. if (!pool_tset(pool, &pool->submit_fail)) {
  2971. total_ro++;
  2972. pool->remotefail_occasions++;
  2973. if (opt_lowmem) {
  2974. applog(LOG_WARNING, "Pool %d communication failure, discarding shares", pool->pool_no);
  2975. goto out;
  2976. }
  2977. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  2978. }
  2979. cgsleep_ms(5000);
  2980. goto out;
  2981. } else if (pool_tclear(pool, &pool->submit_fail))
  2982. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  2983. res = json_object_get(val, "result");
  2984. err = json_object_get(val, "error");
  2985. if (!QUIET) {
  2986. show_hash(work, hashshow);
  2987. if (opt_worktime) {
  2988. char workclone[20];
  2989. struct tm *tm, tm_getwork, tm_submit_reply;
  2990. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  2991. (struct timeval *)&(work->tv_getwork));
  2992. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  2993. (struct timeval *)&(work->tv_getwork_reply));
  2994. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  2995. (struct timeval *)&(work->tv_work_start));
  2996. double work_to_submit = tdiff(&tv_submit,
  2997. (struct timeval *)&(work->tv_work_found));
  2998. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  2999. int diffplaces = 3;
  3000. time_t tmp_time = work->tv_getwork.tv_sec;
  3001. tm = localtime(&tmp_time);
  3002. memcpy(&tm_getwork, tm, sizeof(struct tm));
  3003. tmp_time = tv_submit_reply.tv_sec;
  3004. tm = localtime(&tmp_time);
  3005. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  3006. if (work->clone) {
  3007. snprintf(workclone, sizeof(workclone), "C:%1.3f",
  3008. tdiff((struct timeval *)&(work->tv_cloned),
  3009. (struct timeval *)&(work->tv_getwork_reply)));
  3010. }
  3011. else
  3012. strcpy(workclone, "O");
  3013. if (work->work_difficulty < 1)
  3014. diffplaces = 6;
  3015. snprintf(worktime, sizeof(worktime),
  3016. " <-%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",
  3017. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  3018. (unsigned long)be32toh(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  3019. work->getwork_mode, diffplaces, work->work_difficulty,
  3020. tm_getwork.tm_hour, tm_getwork.tm_min,
  3021. tm_getwork.tm_sec, getwork_time, workclone,
  3022. getwork_to_work, work_time, work_to_submit, submit_time,
  3023. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  3024. tm_submit_reply.tm_sec);
  3025. }
  3026. }
  3027. share_result(val, res, err, work, hashshow, resubmit, worktime);
  3028. if (cgpu->dev_start_tv.tv_sec == 0)
  3029. dev_runtime = total_secs;
  3030. else {
  3031. cgtime(&now);
  3032. dev_runtime = tdiff(&now, &(cgpu->dev_start_tv));
  3033. }
  3034. if (dev_runtime < 1.0)
  3035. dev_runtime = 1.0;
  3036. cgpu->utility = cgpu->accepted / dev_runtime * 60;
  3037. if (!opt_realquiet)
  3038. print_status(thr_id);
  3039. if (!want_per_device_stats) {
  3040. char logline[256];
  3041. get_statline(logline, sizeof(logline), cgpu);
  3042. applog(LOG_INFO, "%s", logline);
  3043. }
  3044. json_decref(val);
  3045. rc = true;
  3046. out:
  3047. return rc;
  3048. }
  3049. static bool get_upstream_work(struct work *work, CURL *curl)
  3050. {
  3051. struct pool *pool = work->pool;
  3052. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  3053. struct timeval tv_elapsed;
  3054. json_t *val = NULL;
  3055. bool rc = false;
  3056. char *url;
  3057. url = pool->rpc_url;
  3058. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", url, pool->rpc_req);
  3059. cgtime(&work->tv_getwork);
  3060. val = json_rpc_call(curl, url, pool->rpc_userpass, pool->rpc_req, false,
  3061. false, &work->rolltime, pool, false);
  3062. pool_stats->getwork_attempts++;
  3063. if (likely(val)) {
  3064. rc = work_decode(pool, work, val);
  3065. if (unlikely(!rc))
  3066. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  3067. } else
  3068. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  3069. cgtime(&work->tv_getwork_reply);
  3070. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  3071. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  3072. pool_stats->getwork_wait_rolling /= 1.63;
  3073. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  3074. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  3075. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  3076. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  3077. }
  3078. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  3079. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  3080. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  3081. }
  3082. pool_stats->getwork_calls++;
  3083. work->pool = pool;
  3084. work->longpoll = false;
  3085. work->getwork_mode = GETWORK_MODE_POOL;
  3086. calc_diff(work, 0);
  3087. total_getworks++;
  3088. pool->getwork_requested++;
  3089. if (likely(val))
  3090. json_decref(val);
  3091. return rc;
  3092. }
  3093. #endif /* HAVE_LIBCURL */
  3094. /* Specifies whether we can use this pool for work or not. */
  3095. static bool pool_unworkable(struct pool *pool)
  3096. {
  3097. if (pool->idle)
  3098. return true;
  3099. if (pool->enabled != POOL_ENABLED)
  3100. return true;
  3101. if (pool->has_stratum && !pool->stratum_active)
  3102. return true;
  3103. return false;
  3104. }
  3105. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  3106. * rolling average per 10 minutes and if pools start getting more, it biases
  3107. * away from them to distribute work evenly. The share count is reset to the
  3108. * rolling average every 10 minutes to not send all work to one pool after it
  3109. * has been disabled/out for an extended period. */
  3110. static struct pool *select_balanced(struct pool *cp)
  3111. {
  3112. int i, lowest = cp->shares;
  3113. struct pool *ret = cp;
  3114. for (i = 0; i < total_pools; i++) {
  3115. struct pool *pool = pools[i];
  3116. if (pool_unworkable(pool))
  3117. continue;
  3118. if (pool->shares < lowest) {
  3119. lowest = pool->shares;
  3120. ret = pool;
  3121. }
  3122. }
  3123. ret->shares++;
  3124. return ret;
  3125. }
  3126. static struct pool *priority_pool(int choice);
  3127. static bool pool_unusable(struct pool *pool);
  3128. /* Select any active pool in a rotating fashion when loadbalance is chosen if
  3129. * it has any quota left. */
  3130. static inline struct pool *select_pool(bool lagging)
  3131. {
  3132. static int rotating_pool = 0;
  3133. struct pool *pool, *cp;
  3134. bool avail = false;
  3135. int tested, i;
  3136. cp = current_pool();
  3137. if (pool_strategy == POOL_BALANCE) {
  3138. pool = select_balanced(cp);
  3139. goto out;
  3140. }
  3141. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only)) {
  3142. pool = cp;
  3143. goto out;
  3144. } else
  3145. pool = NULL;
  3146. for (i = 0; i < total_pools; i++) {
  3147. struct pool *tp = pools[i];
  3148. if (tp->quota_used < tp->quota_gcd) {
  3149. avail = true;
  3150. break;
  3151. }
  3152. }
  3153. /* There are no pools with quota, so reset them. */
  3154. if (!avail) {
  3155. for (i = 0; i < total_pools; i++)
  3156. pools[i]->quota_used = 0;
  3157. if (++rotating_pool >= total_pools)
  3158. rotating_pool = 0;
  3159. }
  3160. /* Try to find the first pool in the rotation that is usable */
  3161. tested = 0;
  3162. while (!pool && tested++ < total_pools) {
  3163. pool = pools[rotating_pool];
  3164. if (pool->quota_used++ < pool->quota_gcd) {
  3165. if (!pool_unworkable(pool))
  3166. break;
  3167. /* Failover-only flag for load-balance means distribute
  3168. * unused quota to priority pool 0. */
  3169. if (opt_fail_only)
  3170. priority_pool(0)->quota_used--;
  3171. }
  3172. pool = NULL;
  3173. if (++rotating_pool >= total_pools)
  3174. rotating_pool = 0;
  3175. }
  3176. /* If there are no alive pools with quota, choose according to
  3177. * priority. */
  3178. if (!pool) {
  3179. for (i = 0; i < total_pools; i++) {
  3180. struct pool *tp = priority_pool(i);
  3181. if (!pool_unusable(tp)) {
  3182. pool = tp;
  3183. break;
  3184. }
  3185. }
  3186. }
  3187. /* If still nothing is usable, use the current pool */
  3188. if (!pool)
  3189. pool = cp;
  3190. out:
  3191. applog(LOG_DEBUG, "Selecting pool %d for work", pool->pool_no);
  3192. return pool;
  3193. }
  3194. /* truediffone == 0x00000000FFFF0000000000000000000000000000000000000000000000000000
  3195. * Generate a 256 bit binary LE target by cutting up diff into 64 bit sized
  3196. * portions or vice versa. */
  3197. static const double truediffone = 26959535291011309493156476344723991336010898738574164086137773096960.0;
  3198. static const double bits192 = 6277101735386680763835789423207666416102355444464034512896.0;
  3199. static const double bits128 = 340282366920938463463374607431768211456.0;
  3200. static const double bits64 = 18446744073709551616.0;
  3201. /* Converts a little endian 256 bit value to a double */
  3202. static double le256todouble(const void *target)
  3203. {
  3204. uint64_t *data64;
  3205. double dcut64;
  3206. data64 = (uint64_t *)(target + 24);
  3207. dcut64 = le64toh(*data64) * bits192;
  3208. data64 = (uint64_t *)(target + 16);
  3209. dcut64 += le64toh(*data64) * bits128;
  3210. data64 = (uint64_t *)(target + 8);
  3211. dcut64 += le64toh(*data64) * bits64;
  3212. data64 = (uint64_t *)(target);
  3213. dcut64 += le64toh(*data64);
  3214. return dcut64;
  3215. }
  3216. static double diff_from_target(void *target)
  3217. {
  3218. double d64, dcut64;
  3219. d64 = truediffone;
  3220. if (opt_scrypt)
  3221. d64 *= (double)65536;
  3222. dcut64 = le256todouble(target);
  3223. if (unlikely(!dcut64))
  3224. dcut64 = 1;
  3225. return d64 / dcut64;
  3226. }
  3227. /*
  3228. * Calculate the work->work_difficulty based on the work->target
  3229. */
  3230. static void calc_diff(struct work *work, double known)
  3231. {
  3232. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  3233. double difficulty;
  3234. uint64_t uintdiff;
  3235. if (known)
  3236. work->work_difficulty = known;
  3237. else
  3238. work->work_difficulty = diff_from_target(work->target);
  3239. difficulty = work->work_difficulty;
  3240. pool_stats->last_diff = difficulty;
  3241. uintdiff = round(difficulty);
  3242. suffix_string(uintdiff, work->pool->diff, sizeof(work->pool->diff), 0);
  3243. if (difficulty == pool_stats->min_diff)
  3244. pool_stats->min_diff_count++;
  3245. else if (difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  3246. pool_stats->min_diff = difficulty;
  3247. pool_stats->min_diff_count = 1;
  3248. }
  3249. if (difficulty == pool_stats->max_diff)
  3250. pool_stats->max_diff_count++;
  3251. else if (difficulty > pool_stats->max_diff) {
  3252. pool_stats->max_diff = difficulty;
  3253. pool_stats->max_diff_count = 1;
  3254. }
  3255. }
  3256. static unsigned char bench_hidiff_bins[16][160];
  3257. static unsigned char bench_lodiff_bins[16][160];
  3258. static unsigned char bench_target[32];
  3259. /* Iterate over the lo and hi diff benchmark work items such that we find one
  3260. * diff 32+ share every 32 work items. */
  3261. static void get_benchmark_work(struct work *work)
  3262. {
  3263. work->work_difficulty = 32;
  3264. memcpy(work->target, bench_target, 32);
  3265. work->drv_rolllimit = 0;
  3266. work->mandatory = true;
  3267. work->pool = pools[0];
  3268. cgtime(&work->tv_getwork);
  3269. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3270. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3271. }
  3272. static void benchfile_dspwork(struct work *work, uint32_t nonce)
  3273. {
  3274. char buf[1024];
  3275. uint32_t dn;
  3276. int i;
  3277. dn = 0;
  3278. for (i = 0; i < 4; i++) {
  3279. dn *= 0x100;
  3280. dn += nonce & 0xff;
  3281. nonce /= 0x100;
  3282. }
  3283. if ((sizeof(work->data) * 2 + 1) > sizeof(buf))
  3284. quithere(1, "BENCHFILE Invalid buf size");
  3285. __bin2hex(buf, work->data, sizeof(work->data));
  3286. applog(LOG_ERR, "BENCHFILE nonce %u=0x%08x for work=%s",
  3287. (unsigned int)dn, (unsigned int)dn, buf);
  3288. }
  3289. static bool benchfile_get_work(struct work *work)
  3290. {
  3291. char buf[1024];
  3292. char item[1024];
  3293. bool got = false;
  3294. if (!benchfile_in) {
  3295. if (opt_benchfile)
  3296. benchfile_in = fopen(opt_benchfile, "r");
  3297. else
  3298. quit(1, "BENCHFILE Invalid benchfile NULL");
  3299. if (!benchfile_in)
  3300. quit(1, "BENCHFILE Failed to open benchfile '%s'", opt_benchfile);
  3301. benchfile_line = 0;
  3302. if (!fgets(buf, 1024, benchfile_in))
  3303. quit(1, "BENCHFILE Failed to read benchfile '%s'", opt_benchfile);
  3304. got = true;
  3305. benchfile_work = 0;
  3306. }
  3307. if (!got) {
  3308. if (!fgets(buf, 1024, benchfile_in)) {
  3309. if (benchfile_work == 0)
  3310. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3311. fclose(benchfile_in);
  3312. benchfile_in = NULL;
  3313. return benchfile_get_work(work);
  3314. }
  3315. }
  3316. do {
  3317. benchfile_line++;
  3318. // Empty lines and lines starting with '#' or '/' are ignored
  3319. if (*buf != '\0' && *buf != '#' && *buf != '/') {
  3320. char *commas[BENCHWORK_COUNT];
  3321. int i, j, len;
  3322. long nonce_time;
  3323. commas[0] = buf;
  3324. for (i = 1; i < BENCHWORK_COUNT; i++) {
  3325. commas[i] = strchr(commas[i-1], ',');
  3326. if (!commas[i]) {
  3327. quit(1, "BENCHFILE Invalid input file line %d"
  3328. " - field count is %d but should be %d",
  3329. benchfile_line, i, BENCHWORK_COUNT);
  3330. }
  3331. len = commas[i] - commas[i-1];
  3332. if (benchfile_data[i-1].length &&
  3333. (len != benchfile_data[i-1].length)) {
  3334. quit(1, "BENCHFILE Invalid input file line %d "
  3335. "field %d (%s) length is %d but should be %d",
  3336. benchfile_line, i,
  3337. benchfile_data[i-1].name,
  3338. len, benchfile_data[i-1].length);
  3339. }
  3340. *(commas[i]++) = '\0';
  3341. }
  3342. // NonceTime may have LF's etc
  3343. len = strlen(commas[BENCHWORK_NONCETIME]);
  3344. if (len < benchfile_data[BENCHWORK_NONCETIME].length) {
  3345. quit(1, "BENCHFILE Invalid input file line %d field %d"
  3346. " (%s) length is %d but should be least %d",
  3347. benchfile_line, BENCHWORK_NONCETIME+1,
  3348. benchfile_data[BENCHWORK_NONCETIME].name, len,
  3349. benchfile_data[BENCHWORK_NONCETIME].length);
  3350. }
  3351. sprintf(item, "0000000%c", commas[BENCHWORK_VERSION][0]);
  3352. j = strlen(item);
  3353. for (i = benchfile_data[BENCHWORK_PREVHASH].length-8; i >= 0; i -= 8) {
  3354. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_PREVHASH][i]);
  3355. j += 8;
  3356. }
  3357. for (i = benchfile_data[BENCHWORK_MERKLEROOT].length-8; i >= 0; i -= 8) {
  3358. sprintf(&(item[j]), "%.8s", &commas[BENCHWORK_MERKLEROOT][i]);
  3359. j += 8;
  3360. }
  3361. nonce_time = atol(commas[BENCHWORK_NONCETIME]);
  3362. sprintf(&(item[j]), "%08lx", nonce_time);
  3363. j += 8;
  3364. strcpy(&(item[j]), commas[BENCHWORK_DIFFBITS]);
  3365. j += benchfile_data[BENCHWORK_DIFFBITS].length;
  3366. memset(work, 0, sizeof(*work));
  3367. hex2bin(work->data, item, j >> 1);
  3368. calc_midstate(work);
  3369. benchfile_work++;
  3370. return true;
  3371. }
  3372. } while (fgets(buf, 1024, benchfile_in));
  3373. if (benchfile_work == 0)
  3374. quit(1, "BENCHFILE No work in benchfile '%s'", opt_benchfile);
  3375. fclose(benchfile_in);
  3376. benchfile_in = NULL;
  3377. return benchfile_get_work(work);
  3378. }
  3379. static void get_benchfile_work(struct work *work)
  3380. {
  3381. benchfile_get_work(work);
  3382. work->mandatory = true;
  3383. work->pool = pools[0];
  3384. cgtime(&work->tv_getwork);
  3385. copy_time(&work->tv_getwork_reply, &work->tv_getwork);
  3386. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  3387. calc_diff(work, 0);
  3388. }
  3389. #ifdef HAVE_CURSES
  3390. static void disable_curses_windows(void)
  3391. {
  3392. leaveok(logwin, false);
  3393. leaveok(statuswin, false);
  3394. leaveok(mainwin, false);
  3395. nocbreak();
  3396. echo();
  3397. delwin(logwin);
  3398. delwin(statuswin);
  3399. }
  3400. /* Force locking of curses console_lock on shutdown since a dead thread might
  3401. * have grabbed the lock. */
  3402. static bool curses_active_forcelocked(void)
  3403. {
  3404. bool ret;
  3405. mutex_trylock(&console_lock);
  3406. ret = curses_active;
  3407. if (!ret)
  3408. unlock_curses();
  3409. return ret;
  3410. }
  3411. static void disable_curses(void)
  3412. {
  3413. if (curses_active_forcelocked()) {
  3414. use_curses = false;
  3415. curses_active = false;
  3416. disable_curses_windows();
  3417. delwin(mainwin);
  3418. endwin();
  3419. #ifdef WIN32
  3420. // Move the cursor to after curses output.
  3421. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  3422. CONSOLE_SCREEN_BUFFER_INFO csbi;
  3423. COORD coord;
  3424. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  3425. coord.X = 0;
  3426. coord.Y = csbi.dwSize.Y - 1;
  3427. SetConsoleCursorPosition(hout, coord);
  3428. }
  3429. #endif
  3430. unlock_curses();
  3431. }
  3432. }
  3433. #endif
  3434. static void kill_timeout(struct thr_info *thr)
  3435. {
  3436. cg_completion_timeout(&thr_info_cancel, thr, 1000);
  3437. }
  3438. static void kill_mining(void)
  3439. {
  3440. struct thr_info *thr;
  3441. int i;
  3442. forcelog(LOG_DEBUG, "Killing off mining threads");
  3443. /* Kill the mining threads*/
  3444. for (i = 0; i < mining_threads; i++) {
  3445. pthread_t *pth = NULL;
  3446. thr = get_thread(i);
  3447. if (thr && PTH(thr) != 0L)
  3448. pth = &thr->pth;
  3449. thr_info_cancel(thr);
  3450. #ifndef WIN32
  3451. if (pth && *pth)
  3452. pthread_join(*pth, NULL);
  3453. #else
  3454. if (pth && pth->p)
  3455. pthread_join(*pth, NULL);
  3456. #endif
  3457. }
  3458. }
  3459. static void __kill_work(void)
  3460. {
  3461. struct thr_info *thr;
  3462. int i;
  3463. if (!successful_connect)
  3464. return;
  3465. forcelog(LOG_INFO, "Received kill message");
  3466. #ifdef USE_USBUTILS
  3467. /* Best to get rid of it first so it doesn't
  3468. * try to create any new devices */
  3469. forcelog(LOG_DEBUG, "Killing off HotPlug thread");
  3470. thr = &control_thr[hotplug_thr_id];
  3471. kill_timeout(thr);
  3472. #endif
  3473. forcelog(LOG_DEBUG, "Killing off watchpool thread");
  3474. /* Kill the watchpool thread */
  3475. thr = &control_thr[watchpool_thr_id];
  3476. kill_timeout(thr);
  3477. forcelog(LOG_DEBUG, "Killing off watchdog thread");
  3478. /* Kill the watchdog thread */
  3479. thr = &control_thr[watchdog_thr_id];
  3480. kill_timeout(thr);
  3481. forcelog(LOG_DEBUG, "Shutting down mining threads");
  3482. for (i = 0; i < mining_threads; i++) {
  3483. struct cgpu_info *cgpu;
  3484. thr = get_thread(i);
  3485. if (!thr)
  3486. continue;
  3487. cgpu = thr->cgpu;
  3488. if (!cgpu)
  3489. continue;
  3490. cgpu->shutdown = true;
  3491. }
  3492. sleep(1);
  3493. cg_completion_timeout(&kill_mining, NULL, 3000);
  3494. /* Stop the others */
  3495. forcelog(LOG_DEBUG, "Killing off API thread");
  3496. thr = &control_thr[api_thr_id];
  3497. kill_timeout(thr);
  3498. #ifdef USE_USBUTILS
  3499. /* Release USB resources in case it's a restart
  3500. * and not a QUIT */
  3501. forcelog(LOG_DEBUG, "Releasing all USB devices");
  3502. cg_completion_timeout(&usb_cleanup, NULL, 1000);
  3503. forcelog(LOG_DEBUG, "Killing off usbres thread");
  3504. thr = &control_thr[usbres_thr_id];
  3505. kill_timeout(thr);
  3506. #endif
  3507. }
  3508. /* This should be the common exit path */
  3509. void kill_work(void)
  3510. {
  3511. cg_completion_timeout(&__kill_work, NULL, 5000);
  3512. quit(0, "Shutdown signal received.");
  3513. }
  3514. static
  3515. #ifdef WIN32
  3516. const
  3517. #endif
  3518. char **initial_args;
  3519. static void clean_up(bool restarting);
  3520. void app_restart(void)
  3521. {
  3522. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  3523. cg_completion_timeout(&__kill_work, NULL, 5000);
  3524. clean_up(true);
  3525. #if defined(unix) || defined(__APPLE__)
  3526. if (forkpid > 0) {
  3527. kill(forkpid, SIGTERM);
  3528. forkpid = 0;
  3529. }
  3530. #endif
  3531. execv(initial_args[0], (EXECV_2ND_ARG_TYPE)initial_args);
  3532. applog(LOG_WARNING, "Failed to restart application");
  3533. }
  3534. static void sighandler(int __maybe_unused sig)
  3535. {
  3536. /* Restore signal handlers so we can still quit if kill_work fails */
  3537. sigaction(SIGTERM, &termhandler, NULL);
  3538. sigaction(SIGINT, &inthandler, NULL);
  3539. kill_work();
  3540. }
  3541. static void _stage_work(struct work *work);
  3542. #define stage_work(WORK) do { \
  3543. _stage_work(WORK); \
  3544. WORK = NULL; \
  3545. } while (0)
  3546. /* Adjust an existing char ntime field with a relative noffset */
  3547. static void modify_ntime(char *ntime, int noffset)
  3548. {
  3549. unsigned char bin[4];
  3550. uint32_t h32, *be32 = (uint32_t *)bin;
  3551. hex2bin(bin, ntime, 4);
  3552. h32 = be32toh(*be32) + noffset;
  3553. *be32 = htobe32(h32);
  3554. __bin2hex(ntime, bin, 4);
  3555. }
  3556. void roll_work(struct work *work)
  3557. {
  3558. uint32_t *work_ntime;
  3559. uint32_t ntime;
  3560. work_ntime = (uint32_t *)(work->data + 68);
  3561. ntime = be32toh(*work_ntime);
  3562. ntime++;
  3563. *work_ntime = htobe32(ntime);
  3564. local_work++;
  3565. work->rolls++;
  3566. work->nonce = 0;
  3567. applog(LOG_DEBUG, "Successfully rolled work");
  3568. /* Change the ntime field if this is stratum work */
  3569. if (work->ntime)
  3570. modify_ntime(work->ntime, 1);
  3571. /* This is now a different work item so it needs a different ID for the
  3572. * hashtable */
  3573. work->id = total_work_inc();
  3574. }
  3575. struct work *make_clone(struct work *work)
  3576. {
  3577. struct work *work_clone = copy_work(work);
  3578. work_clone->clone = true;
  3579. cgtime((struct timeval *)&(work_clone->tv_cloned));
  3580. work_clone->longpoll = false;
  3581. work_clone->mandatory = false;
  3582. /* Make cloned work appear slightly older to bias towards keeping the
  3583. * master work item which can be further rolled */
  3584. work_clone->tv_staged.tv_sec -= 1;
  3585. return work_clone;
  3586. }
  3587. #ifdef HAVE_LIBCURL
  3588. /* Called with pool_lock held. Recruit an extra curl if none are available for
  3589. * this pool. */
  3590. static void recruit_curl(struct pool *pool)
  3591. {
  3592. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  3593. if (unlikely(!ce))
  3594. quit(1, "Failed to calloc in recruit_curl");
  3595. ce->curl = curl_easy_init();
  3596. if (unlikely(!ce->curl))
  3597. quit(1, "Failed to init in recruit_curl");
  3598. list_add(&ce->node, &pool->curlring);
  3599. pool->curls++;
  3600. }
  3601. /* Grab an available curl if there is one. If not, then recruit extra curls
  3602. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  3603. * and there are already 5 curls in circulation. Limit total number to the
  3604. * number of mining threads per pool as well to prevent blasting a pool during
  3605. * network delays/outages. */
  3606. static struct curl_ent *pop_curl_entry(struct pool *pool)
  3607. {
  3608. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  3609. bool recruited = false;
  3610. struct curl_ent *ce;
  3611. mutex_lock(&pool->pool_lock);
  3612. retry:
  3613. if (!pool->curls) {
  3614. recruit_curl(pool);
  3615. recruited = true;
  3616. } else if (list_empty(&pool->curlring)) {
  3617. if (pool->curls >= curl_limit) {
  3618. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  3619. goto retry;
  3620. } else {
  3621. recruit_curl(pool);
  3622. recruited = true;
  3623. }
  3624. }
  3625. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  3626. list_del(&ce->node);
  3627. mutex_unlock(&pool->pool_lock);
  3628. if (recruited)
  3629. applog(LOG_DEBUG, "Recruited curl for pool %d", pool->pool_no);
  3630. return ce;
  3631. }
  3632. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  3633. {
  3634. mutex_lock(&pool->pool_lock);
  3635. list_add_tail(&ce->node, &pool->curlring);
  3636. cgtime(&ce->tv);
  3637. pthread_cond_broadcast(&pool->cr_cond);
  3638. mutex_unlock(&pool->pool_lock);
  3639. }
  3640. static bool stale_work(struct work *work, bool share);
  3641. static inline bool should_roll(struct work *work)
  3642. {
  3643. struct timeval now;
  3644. time_t expiry;
  3645. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  3646. return false;
  3647. if (work->rolltime > opt_scantime)
  3648. expiry = work->rolltime;
  3649. else
  3650. expiry = opt_scantime;
  3651. expiry = expiry * 2 / 3;
  3652. /* We shouldn't roll if we're unlikely to get one shares' duration
  3653. * work out of doing so */
  3654. cgtime(&now);
  3655. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  3656. return false;
  3657. return true;
  3658. }
  3659. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  3660. * reject blocks as invalid. */
  3661. static inline bool can_roll(struct work *work)
  3662. {
  3663. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  3664. work->rolls < 7000 && !stale_work(work, false));
  3665. }
  3666. static void *submit_work_thread(void *userdata)
  3667. {
  3668. struct work *work = (struct work *)userdata;
  3669. struct pool *pool = work->pool;
  3670. bool resubmit = false;
  3671. struct curl_ent *ce;
  3672. pthread_detach(pthread_self());
  3673. RenameThread("SubmitWork");
  3674. applog(LOG_DEBUG, "Creating extra submit work thread");
  3675. ce = pop_curl_entry(pool);
  3676. /* submit solution to bitcoin via JSON-RPC */
  3677. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  3678. if (opt_lowmem) {
  3679. applog(LOG_NOTICE, "Pool %d share being discarded to minimise memory cache", pool->pool_no);
  3680. break;
  3681. }
  3682. resubmit = true;
  3683. if (stale_work(work, true)) {
  3684. applog(LOG_NOTICE, "Pool %d share became stale while retrying submit, discarding", pool->pool_no);
  3685. mutex_lock(&stats_lock);
  3686. total_stale++;
  3687. pool->stale_shares++;
  3688. total_diff_stale += work->work_difficulty;
  3689. pool->diff_stale += work->work_difficulty;
  3690. mutex_unlock(&stats_lock);
  3691. free_work(work);
  3692. break;
  3693. }
  3694. /* pause, then restart work-request loop */
  3695. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  3696. }
  3697. push_curl_entry(ce, pool);
  3698. return NULL;
  3699. }
  3700. static bool clone_available(void)
  3701. {
  3702. struct work *work_clone = NULL, *work, *tmp;
  3703. bool cloned = false;
  3704. mutex_lock(stgd_lock);
  3705. if (!staged_rollable)
  3706. goto out_unlock;
  3707. HASH_ITER(hh, staged_work, work, tmp) {
  3708. if (can_roll(work) && should_roll(work)) {
  3709. roll_work(work);
  3710. work_clone = make_clone(work);
  3711. roll_work(work);
  3712. cloned = true;
  3713. break;
  3714. }
  3715. }
  3716. out_unlock:
  3717. mutex_unlock(stgd_lock);
  3718. if (cloned) {
  3719. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  3720. stage_work(work_clone);
  3721. }
  3722. return cloned;
  3723. }
  3724. /* Clones work by rolling it if possible, and returning a clone instead of the
  3725. * original work item which gets staged again to possibly be rolled again in
  3726. * the future */
  3727. static struct work *clone_work(struct work *work)
  3728. {
  3729. int mrs = mining_threads + opt_queue - total_staged();
  3730. struct work *work_clone;
  3731. bool cloned;
  3732. if (mrs < 1)
  3733. return work;
  3734. cloned = false;
  3735. work_clone = make_clone(work);
  3736. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3737. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3738. stage_work(work_clone);
  3739. roll_work(work);
  3740. work_clone = make_clone(work);
  3741. /* Roll it again to prevent duplicates should this be used
  3742. * directly later on */
  3743. roll_work(work);
  3744. cloned = true;
  3745. }
  3746. if (cloned) {
  3747. stage_work(work);
  3748. return work_clone;
  3749. }
  3750. free_work(work_clone);
  3751. return work;
  3752. }
  3753. #else /* HAVE_LIBCURL */
  3754. static void *submit_work_thread(void __maybe_unused *userdata)
  3755. {
  3756. pthread_detach(pthread_self());
  3757. return NULL;
  3758. }
  3759. #endif /* HAVE_LIBCURL */
  3760. /* Return an adjusted ntime if we're submitting work that a device has
  3761. * internally offset the ntime. */
  3762. static char *offset_ntime(const char *ntime, int noffset)
  3763. {
  3764. unsigned char bin[4];
  3765. uint32_t h32, *be32 = (uint32_t *)bin;
  3766. hex2bin(bin, ntime, 4);
  3767. h32 = be32toh(*be32) + noffset;
  3768. *be32 = htobe32(h32);
  3769. return bin2hex(bin, 4);
  3770. }
  3771. /* Duplicates any dynamically allocated arrays within the work struct to
  3772. * prevent a copied work struct from freeing ram belonging to another struct */
  3773. static void _copy_work(struct work *work, const struct work *base_work, int noffset)
  3774. {
  3775. uint32_t id = work->id;
  3776. clean_work(work);
  3777. memcpy(work, base_work, sizeof(struct work));
  3778. /* Keep the unique new id assigned during make_work to prevent copied
  3779. * work from having the same id. */
  3780. work->id = id;
  3781. if (base_work->job_id)
  3782. work->job_id = strdup(base_work->job_id);
  3783. if (base_work->nonce1)
  3784. work->nonce1 = strdup(base_work->nonce1);
  3785. if (base_work->ntime) {
  3786. /* If we are passed an noffset the binary work->data ntime and
  3787. * the work->ntime hex string need to be adjusted. */
  3788. if (noffset) {
  3789. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3790. uint32_t ntime = be32toh(*work_ntime);
  3791. ntime += noffset;
  3792. *work_ntime = htobe32(ntime);
  3793. work->ntime = offset_ntime(base_work->ntime, noffset);
  3794. } else
  3795. work->ntime = strdup(base_work->ntime);
  3796. } else if (noffset) {
  3797. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3798. uint32_t ntime = be32toh(*work_ntime);
  3799. ntime += noffset;
  3800. *work_ntime = htobe32(ntime);
  3801. }
  3802. if (base_work->coinbase)
  3803. work->coinbase = strdup(base_work->coinbase);
  3804. }
  3805. void set_work_ntime(struct work *work, int ntime)
  3806. {
  3807. uint32_t *work_ntime = (uint32_t *)(work->data + 68);
  3808. *work_ntime = htobe32(ntime);
  3809. if (work->ntime) {
  3810. free(work->ntime);
  3811. work->ntime = bin2hex((unsigned char *)work_ntime, 4);
  3812. }
  3813. }
  3814. /* Generates a copy of an existing work struct, creating fresh heap allocations
  3815. * for all dynamically allocated arrays within the struct. noffset is used for
  3816. * when a driver has internally rolled the ntime, noffset is a relative value.
  3817. * The macro copy_work() calls this function with an noffset of 0. */
  3818. struct work *copy_work_noffset(struct work *base_work, int noffset)
  3819. {
  3820. struct work *work = make_work();
  3821. _copy_work(work, base_work, noffset);
  3822. return work;
  3823. }
  3824. void pool_died(struct pool *pool)
  3825. {
  3826. if (!pool_tset(pool, &pool->idle)) {
  3827. cgtime(&pool->tv_idle);
  3828. if (pool == current_pool()) {
  3829. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3830. switch_pools(NULL);
  3831. } else
  3832. applog(LOG_INFO, "Pool %d %s failed to return work", pool->pool_no, pool->rpc_url);
  3833. }
  3834. }
  3835. static bool stale_work(struct work *work, bool share)
  3836. {
  3837. struct timeval now;
  3838. time_t work_expiry;
  3839. struct pool *pool;
  3840. int getwork_delay;
  3841. if (opt_benchmark || opt_benchfile)
  3842. return false;
  3843. if (work->work_block != work_block) {
  3844. applog(LOG_DEBUG, "Work stale due to block mismatch");
  3845. return true;
  3846. }
  3847. /* Technically the rolltime should be correct but some pools
  3848. * advertise a broken expire= that is lower than a meaningful
  3849. * scantime */
  3850. if (work->rolltime > opt_scantime)
  3851. work_expiry = work->rolltime;
  3852. else
  3853. work_expiry = opt_expiry;
  3854. pool = work->pool;
  3855. if (!share && pool->has_stratum) {
  3856. bool same_job;
  3857. if (!pool->stratum_active || !pool->stratum_notify) {
  3858. applog(LOG_DEBUG, "Work stale due to stratum inactive");
  3859. return true;
  3860. }
  3861. same_job = true;
  3862. cg_rlock(&pool->data_lock);
  3863. if (strcmp(work->job_id, pool->swork.job_id))
  3864. same_job = false;
  3865. cg_runlock(&pool->data_lock);
  3866. if (!same_job) {
  3867. applog(LOG_DEBUG, "Work stale due to stratum job_id mismatch");
  3868. return true;
  3869. }
  3870. }
  3871. /* Factor in the average getwork delay of this pool, rounding it up to
  3872. * the nearest second */
  3873. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  3874. work_expiry -= getwork_delay;
  3875. if (unlikely(work_expiry < 5))
  3876. work_expiry = 5;
  3877. cgtime(&now);
  3878. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  3879. applog(LOG_DEBUG, "Work stale due to expiry");
  3880. return true;
  3881. }
  3882. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  3883. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  3884. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  3885. return true;
  3886. }
  3887. return false;
  3888. }
  3889. uint64_t share_diff(const struct work *work)
  3890. {
  3891. bool new_best = false;
  3892. double d64, s64;
  3893. uint64_t ret;
  3894. d64 = truediffone;
  3895. if (opt_scrypt)
  3896. d64 *= (double)65536;
  3897. s64 = le256todouble(work->hash);
  3898. if (unlikely(!s64))
  3899. s64 = 0;
  3900. ret = round(d64 / s64);
  3901. cg_wlock(&control_lock);
  3902. if (unlikely(ret > best_diff)) {
  3903. new_best = true;
  3904. best_diff = ret;
  3905. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  3906. }
  3907. if (unlikely(ret > work->pool->best_diff))
  3908. work->pool->best_diff = ret;
  3909. cg_wunlock(&control_lock);
  3910. if (unlikely(new_best))
  3911. applog(LOG_INFO, "New best share: %s", best_share);
  3912. return ret;
  3913. }
  3914. static void regen_hash(struct work *work)
  3915. {
  3916. uint32_t *data32 = (uint32_t *)(work->data);
  3917. unsigned char swap[80];
  3918. uint32_t *swap32 = (uint32_t *)swap;
  3919. unsigned char hash1[32];
  3920. flip80(swap32, data32);
  3921. sha256(swap, 80, hash1);
  3922. sha256(hash1, 32, (unsigned char *)(work->hash));
  3923. }
  3924. static void rebuild_hash(struct work *work)
  3925. {
  3926. if (opt_scrypt)
  3927. scrypt_regenhash(work);
  3928. else
  3929. regen_hash(work);
  3930. }
  3931. static bool cnx_needed(struct pool *pool);
  3932. /* Find the pool that currently has the highest priority */
  3933. static struct pool *priority_pool(int choice)
  3934. {
  3935. struct pool *ret = NULL;
  3936. int i;
  3937. for (i = 0; i < total_pools; i++) {
  3938. struct pool *pool = pools[i];
  3939. if (pool->prio == choice) {
  3940. ret = pool;
  3941. break;
  3942. }
  3943. }
  3944. if (unlikely(!ret)) {
  3945. applog(LOG_ERR, "WTF No pool %d found!", choice);
  3946. return pools[choice];
  3947. }
  3948. return ret;
  3949. }
  3950. /* Specifies whether we can switch to this pool or not. */
  3951. static bool pool_unusable(struct pool *pool)
  3952. {
  3953. if (pool->idle)
  3954. return true;
  3955. if (pool->enabled != POOL_ENABLED)
  3956. return true;
  3957. return false;
  3958. }
  3959. void switch_pools(struct pool *selected)
  3960. {
  3961. struct pool *pool, *last_pool;
  3962. int i, pool_no, next_pool;
  3963. cg_wlock(&control_lock);
  3964. last_pool = currentpool;
  3965. pool_no = currentpool->pool_no;
  3966. /* Switch selected to pool number 0 and move the rest down */
  3967. if (selected) {
  3968. if (selected->prio != 0) {
  3969. for (i = 0; i < total_pools; i++) {
  3970. pool = pools[i];
  3971. if (pool->prio < selected->prio)
  3972. pool->prio++;
  3973. }
  3974. selected->prio = 0;
  3975. }
  3976. }
  3977. switch (pool_strategy) {
  3978. /* All of these set to the master pool */
  3979. case POOL_BALANCE:
  3980. case POOL_FAILOVER:
  3981. case POOL_LOADBALANCE:
  3982. for (i = 0; i < total_pools; i++) {
  3983. pool = priority_pool(i);
  3984. if (pool_unusable(pool))
  3985. continue;
  3986. pool_no = pool->pool_no;
  3987. break;
  3988. }
  3989. break;
  3990. /* Both of these simply increment and cycle */
  3991. case POOL_ROUNDROBIN:
  3992. case POOL_ROTATE:
  3993. if (selected && !selected->idle) {
  3994. pool_no = selected->pool_no;
  3995. break;
  3996. }
  3997. next_pool = pool_no;
  3998. /* Select the next alive pool */
  3999. for (i = 1; i < total_pools; i++) {
  4000. next_pool++;
  4001. if (next_pool >= total_pools)
  4002. next_pool = 0;
  4003. pool = pools[next_pool];
  4004. if (pool_unusable(pool))
  4005. continue;
  4006. pool_no = next_pool;
  4007. break;
  4008. }
  4009. break;
  4010. default:
  4011. break;
  4012. }
  4013. currentpool = pools[pool_no];
  4014. pool = currentpool;
  4015. cg_wunlock(&control_lock);
  4016. /* Set the lagging flag to avoid pool not providing work fast enough
  4017. * messages in failover only mode since we have to get all fresh work
  4018. * as in restart_threads */
  4019. if (opt_fail_only)
  4020. pool_tset(pool, &pool->lagging);
  4021. if (pool != last_pool && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4022. applog(LOG_WARNING, "Switching to pool %d %s", pool->pool_no, pool->rpc_url);
  4023. if (pool_localgen(pool) || opt_fail_only)
  4024. clear_pool_work(last_pool);
  4025. }
  4026. mutex_lock(&lp_lock);
  4027. pthread_cond_broadcast(&lp_cond);
  4028. mutex_unlock(&lp_lock);
  4029. }
  4030. void _discard_work(struct work *work)
  4031. {
  4032. if (!work->clone && !work->rolls && !work->mined) {
  4033. if (work->pool) {
  4034. work->pool->discarded_work++;
  4035. work->pool->quota_used--;
  4036. work->pool->works--;
  4037. }
  4038. total_discarded++;
  4039. applog(LOG_DEBUG, "Discarded work");
  4040. } else
  4041. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  4042. free_work(work);
  4043. }
  4044. static void wake_gws(void)
  4045. {
  4046. mutex_lock(stgd_lock);
  4047. pthread_cond_signal(&gws_cond);
  4048. mutex_unlock(stgd_lock);
  4049. }
  4050. static void discard_stale(void)
  4051. {
  4052. struct work *work, *tmp;
  4053. int stale = 0;
  4054. mutex_lock(stgd_lock);
  4055. HASH_ITER(hh, staged_work, work, tmp) {
  4056. if (stale_work(work, false)) {
  4057. HASH_DEL(staged_work, work);
  4058. discard_work(work);
  4059. stale++;
  4060. }
  4061. }
  4062. pthread_cond_signal(&gws_cond);
  4063. mutex_unlock(stgd_lock);
  4064. if (stale)
  4065. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  4066. }
  4067. /* A generic wait function for threads that poll that will wait a specified
  4068. * time tdiff waiting on the pthread conditional that is broadcast when a
  4069. * work restart is required. Returns the value of pthread_cond_timedwait
  4070. * which is zero if the condition was met or ETIMEDOUT if not.
  4071. */
  4072. int restart_wait(struct thr_info *thr, unsigned int mstime)
  4073. {
  4074. struct timeval now, then, tdiff;
  4075. struct timespec abstime;
  4076. int rc;
  4077. tdiff.tv_sec = mstime / 1000;
  4078. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  4079. cgtime(&now);
  4080. timeradd(&now, &tdiff, &then);
  4081. abstime.tv_sec = then.tv_sec;
  4082. abstime.tv_nsec = then.tv_usec * 1000;
  4083. mutex_lock(&restart_lock);
  4084. if (thr->work_restart)
  4085. rc = 0;
  4086. else
  4087. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  4088. mutex_unlock(&restart_lock);
  4089. return rc;
  4090. }
  4091. static void *restart_thread(void __maybe_unused *arg)
  4092. {
  4093. struct pool *cp = current_pool();
  4094. struct cgpu_info *cgpu;
  4095. int i, mt;
  4096. pthread_detach(pthread_self());
  4097. /* Artificially set the lagging flag to avoid pool not providing work
  4098. * fast enough messages after every long poll */
  4099. pool_tset(cp, &cp->lagging);
  4100. /* Discard staged work that is now stale */
  4101. discard_stale();
  4102. rd_lock(&mining_thr_lock);
  4103. mt = mining_threads;
  4104. rd_unlock(&mining_thr_lock);
  4105. for (i = 0; i < mt; i++) {
  4106. cgpu = mining_thr[i]->cgpu;
  4107. if (unlikely(!cgpu))
  4108. continue;
  4109. if (cgpu->deven != DEV_ENABLED)
  4110. continue;
  4111. mining_thr[i]->work_restart = true;
  4112. flush_queue(cgpu);
  4113. cgpu->drv->flush_work(cgpu);
  4114. }
  4115. mutex_lock(&restart_lock);
  4116. pthread_cond_broadcast(&restart_cond);
  4117. mutex_unlock(&restart_lock);
  4118. #ifdef USE_USBUTILS
  4119. /* Cancels any cancellable usb transfers. Flagged as such it means they
  4120. * are usualy waiting on a read result and it's safe to abort the read
  4121. * early. */
  4122. cancel_usb_transfers();
  4123. #endif
  4124. return NULL;
  4125. }
  4126. /* In order to prevent a deadlock via the various drv->flush_work
  4127. * implementations we send the restart messages via a separate thread. */
  4128. static void restart_threads(void)
  4129. {
  4130. pthread_t rthread;
  4131. cgtime(&restart_tv_start);
  4132. if (unlikely(pthread_create(&rthread, NULL, restart_thread, NULL)))
  4133. quit(1, "Failed to create restart thread");
  4134. }
  4135. static void signal_work_update(void)
  4136. {
  4137. int i;
  4138. applog(LOG_INFO, "Work update message received");
  4139. cgtime(&update_tv_start);
  4140. rd_lock(&mining_thr_lock);
  4141. for (i = 0; i < mining_threads; i++)
  4142. mining_thr[i]->work_update = true;
  4143. rd_unlock(&mining_thr_lock);
  4144. }
  4145. static void set_curblock(char *hexstr, unsigned char *bedata)
  4146. {
  4147. int ofs;
  4148. cg_wlock(&ch_lock);
  4149. cgtime(&block_timeval);
  4150. strcpy(current_hash, hexstr);
  4151. memcpy(current_block, bedata, 32);
  4152. get_timestamp(blocktime, sizeof(blocktime), &block_timeval);
  4153. cg_wunlock(&ch_lock);
  4154. for (ofs = 0; ofs <= 56; ofs++) {
  4155. if (memcmp(&current_hash[ofs], "0", 1))
  4156. break;
  4157. }
  4158. strncpy(prev_block, &current_hash[ofs], 8);
  4159. prev_block[8] = '\0';
  4160. applog(LOG_INFO, "New block: %s... diff %s", current_hash, block_diff);
  4161. }
  4162. /* Search to see if this string is from a block that has been seen before */
  4163. static bool block_exists(char *hexstr)
  4164. {
  4165. struct block *s;
  4166. rd_lock(&blk_lock);
  4167. HASH_FIND_STR(blocks, hexstr, s);
  4168. rd_unlock(&blk_lock);
  4169. if (s)
  4170. return true;
  4171. return false;
  4172. }
  4173. /* Tests if this work is from a block that has been seen before */
  4174. static inline bool from_existing_block(struct work *work)
  4175. {
  4176. char *hexstr = bin2hex(work->data + 8, 18);
  4177. bool ret;
  4178. ret = block_exists(hexstr);
  4179. free(hexstr);
  4180. return ret;
  4181. }
  4182. static int block_sort(struct block *blocka, struct block *blockb)
  4183. {
  4184. return blocka->block_no - blockb->block_no;
  4185. }
  4186. /* Decode the current block difficulty which is in packed form */
  4187. static void set_blockdiff(const struct work *work)
  4188. {
  4189. uint8_t pow = work->data[72];
  4190. int powdiff = (8 * (0x1d - 3)) - (8 * (pow - 3));
  4191. uint32_t diff32 = be32toh(*((uint32_t *)(work->data + 72))) & 0x00FFFFFF;
  4192. double numerator = 0xFFFFULL << powdiff;
  4193. double ddiff = numerator / (double)diff32;
  4194. if (unlikely(current_diff != ddiff)) {
  4195. suffix_string(ddiff, block_diff, sizeof(block_diff), 0);
  4196. current_diff = ddiff;
  4197. applog(LOG_NOTICE, "Network diff set to %s", block_diff);
  4198. }
  4199. }
  4200. static bool test_work_current(struct work *work)
  4201. {
  4202. struct pool *pool = work->pool;
  4203. unsigned char bedata[32];
  4204. char hexstr[68];
  4205. bool ret = true;
  4206. if (work->mandatory)
  4207. return ret;
  4208. swap256(bedata, work->data + 4);
  4209. __bin2hex(hexstr, bedata, 32);
  4210. /* Search to see if this block exists yet and if not, consider it a
  4211. * new block and set the current block details to this one */
  4212. if (!block_exists(hexstr)) {
  4213. struct block *s = calloc(sizeof(struct block), 1);
  4214. int deleted_block = 0;
  4215. if (unlikely(!s))
  4216. quit (1, "test_work_current OOM");
  4217. strcpy(s->hash, hexstr);
  4218. s->block_no = new_blocks++;
  4219. wr_lock(&blk_lock);
  4220. /* Only keep the last hour's worth of blocks in memory since
  4221. * work from blocks before this is virtually impossible and we
  4222. * want to prevent memory usage from continually rising */
  4223. if (HASH_COUNT(blocks) > 6) {
  4224. struct block *oldblock;
  4225. HASH_SORT(blocks, block_sort);
  4226. oldblock = blocks;
  4227. deleted_block = oldblock->block_no;
  4228. HASH_DEL(blocks, oldblock);
  4229. free(oldblock);
  4230. }
  4231. HASH_ADD_STR(blocks, hash, s);
  4232. set_blockdiff(work);
  4233. wr_unlock(&blk_lock);
  4234. if (deleted_block)
  4235. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  4236. set_curblock(hexstr, bedata);
  4237. /* Copy the information to this pool's prev_block since it
  4238. * knows the new block exists. */
  4239. memcpy(pool->prev_block, bedata, 32);
  4240. if (unlikely(new_blocks == 1)) {
  4241. ret = false;
  4242. goto out;
  4243. }
  4244. work->work_block = ++work_block;
  4245. if (work->longpoll) {
  4246. if (work->stratum) {
  4247. applog(LOG_NOTICE, "Stratum from pool %d detected new block",
  4248. pool->pool_no);
  4249. } else {
  4250. applog(LOG_NOTICE, "%sLONGPOLL from pool %d detected new block",
  4251. work->gbt ? "GBT " : "", work->pool->pool_no);
  4252. }
  4253. } else if (have_longpoll && !pool->gbt_solo)
  4254. applog(LOG_NOTICE, "New block detected on network before pool notification");
  4255. else if (!pool->gbt_solo)
  4256. applog(LOG_NOTICE, "New block detected on network");
  4257. restart_threads();
  4258. } else {
  4259. if (memcmp(pool->prev_block, bedata, 32)) {
  4260. /* Work doesn't match what this pool has stored as
  4261. * prev_block. Let's see if the work is from an old
  4262. * block or the pool is just learning about a new
  4263. * block. */
  4264. if (memcmp(bedata, current_block, 32)) {
  4265. /* Doesn't match current block. It's stale */
  4266. applog(LOG_DEBUG, "Stale data from pool %d", pool->pool_no);
  4267. ret = false;
  4268. } else {
  4269. /* Work is from new block and pool is up now
  4270. * current. */
  4271. applog(LOG_INFO, "Pool %d now up to date", pool->pool_no);
  4272. memcpy(pool->prev_block, bedata, 32);
  4273. }
  4274. }
  4275. #if 0
  4276. /* This isn't ideal, this pool is still on an old block but
  4277. * accepting shares from it. To maintain fair work distribution
  4278. * we work on it anyway. */
  4279. if (memcmp(bedata, current_block, 32))
  4280. applog(LOG_DEBUG, "Pool %d still on old block", pool->pool_no);
  4281. #endif
  4282. if (work->longpoll) {
  4283. work->work_block = ++work_block;
  4284. if (shared_strategy() || work->pool == current_pool()) {
  4285. if (work->stratum) {
  4286. applog(LOG_NOTICE, "Stratum from pool %d requested work restart",
  4287. pool->pool_no);
  4288. } else {
  4289. applog(LOG_NOTICE, "%sLONGPOLL from pool %d requested work restart",
  4290. work->gbt ? "GBT " : "", work->pool->pool_no);
  4291. }
  4292. restart_threads();
  4293. }
  4294. }
  4295. }
  4296. out:
  4297. work->longpoll = false;
  4298. return ret;
  4299. }
  4300. static int tv_sort(struct work *worka, struct work *workb)
  4301. {
  4302. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  4303. }
  4304. static bool work_rollable(struct work *work)
  4305. {
  4306. return (!work->clone && work->rolltime);
  4307. }
  4308. static bool hash_push(struct work *work)
  4309. {
  4310. bool rc = true;
  4311. mutex_lock(stgd_lock);
  4312. if (work_rollable(work))
  4313. staged_rollable++;
  4314. if (likely(!getq->frozen)) {
  4315. HASH_ADD_INT(staged_work, id, work);
  4316. HASH_SORT(staged_work, tv_sort);
  4317. } else
  4318. rc = false;
  4319. pthread_cond_broadcast(&getq->cond);
  4320. mutex_unlock(stgd_lock);
  4321. return rc;
  4322. }
  4323. static void _stage_work(struct work *work)
  4324. {
  4325. applog(LOG_DEBUG, "Pushing work from pool %d to hash queue", work->pool->pool_no);
  4326. work->work_block = work_block;
  4327. test_work_current(work);
  4328. work->pool->works++;
  4329. hash_push(work);
  4330. }
  4331. #ifdef HAVE_CURSES
  4332. int curses_int(const char *query)
  4333. {
  4334. int ret;
  4335. char *cvar;
  4336. cvar = curses_input(query);
  4337. ret = atoi(cvar);
  4338. free(cvar);
  4339. return ret;
  4340. }
  4341. #endif
  4342. #ifdef HAVE_CURSES
  4343. static bool input_pool(bool live);
  4344. #endif
  4345. #ifdef HAVE_CURSES
  4346. static void display_pool_summary(struct pool *pool)
  4347. {
  4348. double efficiency = 0.0;
  4349. if (curses_active_locked()) {
  4350. wlog("Pool: %s\n", pool->rpc_url);
  4351. if (pool->solved)
  4352. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  4353. if (!pool->has_stratum)
  4354. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  4355. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  4356. wlog(" Share submissions: %"PRId64"\n", pool->accepted + pool->rejected);
  4357. wlog(" Accepted shares: %"PRId64"\n", pool->accepted);
  4358. wlog(" Rejected shares: %"PRId64"\n", pool->rejected);
  4359. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  4360. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  4361. if (pool->accepted || pool->rejected)
  4362. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4363. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4364. if (!pool_localgen(pool))
  4365. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  4366. wlog(" Items worked on: %d\n", pool->works);
  4367. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  4368. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  4369. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  4370. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  4371. unlock_curses();
  4372. }
  4373. }
  4374. #endif
  4375. /* We can't remove the memory used for this struct pool because there may
  4376. * still be work referencing it. We just remove it from the pools list */
  4377. void remove_pool(struct pool *pool)
  4378. {
  4379. int i, last_pool = total_pools - 1;
  4380. struct pool *other;
  4381. /* Boost priority of any lower prio than this one */
  4382. for (i = 0; i < total_pools; i++) {
  4383. other = pools[i];
  4384. if (other->prio > pool->prio)
  4385. other->prio--;
  4386. }
  4387. if (pool->pool_no < last_pool) {
  4388. /* Swap the last pool for this one */
  4389. (pools[last_pool])->pool_no = pool->pool_no;
  4390. pools[pool->pool_no] = pools[last_pool];
  4391. }
  4392. /* Give it an invalid number */
  4393. pool->pool_no = total_pools;
  4394. pool->removed = true;
  4395. total_pools--;
  4396. }
  4397. /* add a mutex if this needs to be thread safe in the future */
  4398. static struct JE {
  4399. char *buf;
  4400. struct JE *next;
  4401. } *jedata = NULL;
  4402. static void json_escape_free()
  4403. {
  4404. struct JE *jeptr = jedata;
  4405. struct JE *jenext;
  4406. jedata = NULL;
  4407. while (jeptr) {
  4408. jenext = jeptr->next;
  4409. free(jeptr->buf);
  4410. free(jeptr);
  4411. jeptr = jenext;
  4412. }
  4413. }
  4414. static char *json_escape(char *str)
  4415. {
  4416. struct JE *jeptr;
  4417. char *buf, *ptr;
  4418. /* 2x is the max, may as well just allocate that */
  4419. ptr = buf = malloc(strlen(str) * 2 + 1);
  4420. jeptr = malloc(sizeof(*jeptr));
  4421. jeptr->buf = buf;
  4422. jeptr->next = jedata;
  4423. jedata = jeptr;
  4424. while (*str) {
  4425. if (*str == '\\' || *str == '"')
  4426. *(ptr++) = '\\';
  4427. *(ptr++) = *(str++);
  4428. }
  4429. *ptr = '\0';
  4430. return buf;
  4431. }
  4432. void write_config(FILE *fcfg)
  4433. {
  4434. struct opt_table *opt;
  4435. int i;
  4436. /* Write pool values */
  4437. fputs("{\n\"pools\" : [", fcfg);
  4438. for(i = 0; i < total_pools; i++) {
  4439. struct pool *pool = priority_pool(i);
  4440. if (pool->quota != 1) {
  4441. fprintf(fcfg, "%s\n\t{\n\t\t\"quota\" : \"%s%s%s%d;%s\",", i > 0 ? "," : "",
  4442. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4443. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4444. pool->rpc_proxy ? "|" : "",
  4445. pool->quota,
  4446. json_escape(pool->rpc_url));
  4447. } else {
  4448. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  4449. pool->rpc_proxy ? json_escape((char *)proxytype(pool->rpc_proxytype)) : "",
  4450. pool->rpc_proxy ? json_escape(pool->rpc_proxy) : "",
  4451. pool->rpc_proxy ? "|" : "",
  4452. json_escape(pool->rpc_url));
  4453. }
  4454. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pool->rpc_user));
  4455. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pool->rpc_pass));
  4456. }
  4457. fputs("\n]\n", fcfg);
  4458. /* Simple bool,int and char options */
  4459. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  4460. char *p, *name = strdup(opt->names);
  4461. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  4462. if (p[1] != '-')
  4463. continue;
  4464. if (opt->desc == opt_hidden)
  4465. continue;
  4466. if (opt->type & OPT_NOARG &&
  4467. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  4468. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool))) {
  4469. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  4470. continue;
  4471. }
  4472. if (opt->type & OPT_HASARG &&
  4473. ((void *)opt->cb_arg == (void *)opt_set_intval ||
  4474. (void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  4475. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  4476. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  4477. (void *)opt->cb_arg == (void *)set_int_1_to_10 ||
  4478. (void *)opt->cb_arg == (void *)set_int_0_to_100 ||
  4479. (void *)opt->cb_arg == (void *)set_int_0_to_255 ||
  4480. (void *)opt->cb_arg == (void *)set_int_0_to_200 ||
  4481. (void *)opt->cb_arg == (void *)set_int_0_to_4 ||
  4482. (void *)opt->cb_arg == (void *)set_int_32_to_63 ||
  4483. (void *)opt->cb_arg == (void *)set_int_1_to_1024)) {
  4484. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  4485. continue;
  4486. }
  4487. if (opt->type & OPT_HASARG &&
  4488. ((void *)opt->cb_arg == (void *)set_float_125_to_500)) {
  4489. fprintf(fcfg, ",\n\"%s\" : \"%.1f\"", p+2, *(float *)opt->u.arg);
  4490. continue;
  4491. }
  4492. if (opt->type & (OPT_HASARG | OPT_PROCESSARG) &&
  4493. (opt->u.arg != &opt_set_null)) {
  4494. char *carg = *(char **)opt->u.arg;
  4495. if (carg)
  4496. fprintf(fcfg, ",\n\"%s\" : \"%s\"", p+2, json_escape(carg));
  4497. continue;
  4498. }
  4499. }
  4500. free(name);
  4501. }
  4502. /* Special case options */
  4503. if (pool_strategy == POOL_BALANCE)
  4504. fputs(",\n\"balance\" : true", fcfg);
  4505. if (pool_strategy == POOL_LOADBALANCE)
  4506. fputs(",\n\"load-balance\" : true", fcfg);
  4507. if (pool_strategy == POOL_ROUNDROBIN)
  4508. fputs(",\n\"round-robin\" : true", fcfg);
  4509. if (pool_strategy == POOL_ROTATE)
  4510. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  4511. fputs("\n}\n", fcfg);
  4512. json_escape_free();
  4513. }
  4514. void zero_bestshare(void)
  4515. {
  4516. int i;
  4517. best_diff = 0;
  4518. memset(best_share, 0, 8);
  4519. suffix_string(best_diff, best_share, sizeof(best_share), 0);
  4520. for (i = 0; i < total_pools; i++) {
  4521. struct pool *pool = pools[i];
  4522. pool->best_diff = 0;
  4523. }
  4524. }
  4525. static struct timeval tv_hashmeter;
  4526. static time_t hashdisplay_t;
  4527. void zero_stats(void)
  4528. {
  4529. int i;
  4530. cgtime(&total_tv_start);
  4531. copy_time(&tv_hashmeter, &total_tv_start);
  4532. total_rolling = 0;
  4533. rolling1 = 0;
  4534. rolling5 = 0;
  4535. rolling15 = 0;
  4536. total_mhashes_done = 0;
  4537. total_getworks = 0;
  4538. total_accepted = 0;
  4539. total_rejected = 0;
  4540. hw_errors = 0;
  4541. total_stale = 0;
  4542. total_discarded = 0;
  4543. local_work = 0;
  4544. total_go = 0;
  4545. total_ro = 0;
  4546. total_secs = 1.0;
  4547. total_diff1 = 0;
  4548. found_blocks = 0;
  4549. total_diff_accepted = 0;
  4550. total_diff_rejected = 0;
  4551. total_diff_stale = 0;
  4552. for (i = 0; i < total_pools; i++) {
  4553. struct pool *pool = pools[i];
  4554. pool->getwork_requested = 0;
  4555. pool->accepted = 0;
  4556. pool->rejected = 0;
  4557. pool->stale_shares = 0;
  4558. pool->discarded_work = 0;
  4559. pool->getfail_occasions = 0;
  4560. pool->remotefail_occasions = 0;
  4561. pool->last_share_time = 0;
  4562. pool->diff1 = 0;
  4563. pool->diff_accepted = 0;
  4564. pool->diff_rejected = 0;
  4565. pool->diff_stale = 0;
  4566. pool->last_share_diff = 0;
  4567. }
  4568. zero_bestshare();
  4569. for (i = 0; i < total_devices; ++i) {
  4570. struct cgpu_info *cgpu = get_devices(i);
  4571. copy_time(&cgpu->dev_start_tv, &total_tv_start);
  4572. mutex_lock(&hash_lock);
  4573. cgpu->total_mhashes = 0;
  4574. cgpu->accepted = 0;
  4575. cgpu->rejected = 0;
  4576. cgpu->hw_errors = 0;
  4577. cgpu->utility = 0.0;
  4578. cgpu->last_share_pool_time = 0;
  4579. cgpu->diff1 = 0;
  4580. cgpu->diff_accepted = 0;
  4581. cgpu->diff_rejected = 0;
  4582. cgpu->last_share_diff = 0;
  4583. mutex_unlock(&hash_lock);
  4584. /* Don't take any locks in the driver zero stats function, as
  4585. * it's called async from everything else and we don't want to
  4586. * deadlock. */
  4587. cgpu->drv->zero_stats(cgpu);
  4588. }
  4589. }
  4590. static void set_highprio(void)
  4591. {
  4592. #ifndef WIN32
  4593. int ret = nice(-10);
  4594. if (!ret)
  4595. applog(LOG_DEBUG, "Unable to set thread to high priority");
  4596. #else
  4597. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
  4598. #endif
  4599. }
  4600. static void set_lowprio(void)
  4601. {
  4602. #ifndef WIN32
  4603. int ret = nice(10);
  4604. if (!ret)
  4605. applog(LOG_INFO, "Unable to set thread to low priority");
  4606. #else
  4607. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
  4608. #endif
  4609. }
  4610. #ifdef HAVE_CURSES
  4611. static void display_pools(void)
  4612. {
  4613. struct pool *pool;
  4614. int selected, i;
  4615. char input;
  4616. opt_loginput = true;
  4617. immedok(logwin, true);
  4618. clear_logwin();
  4619. updated:
  4620. for (i = 0; i < total_pools; i++) {
  4621. pool = pools[i];
  4622. if (pool == current_pool())
  4623. wattron(logwin, A_BOLD);
  4624. if (pool->enabled != POOL_ENABLED)
  4625. wattron(logwin, A_DIM);
  4626. wlogprint("%d: ", pool->pool_no);
  4627. switch (pool->enabled) {
  4628. case POOL_ENABLED:
  4629. wlogprint("Enabled ");
  4630. break;
  4631. case POOL_DISABLED:
  4632. wlogprint("Disabled ");
  4633. break;
  4634. case POOL_REJECTING:
  4635. wlogprint("Rejecting ");
  4636. break;
  4637. }
  4638. wlogprint("%s Quota %d Prio %d: %s User:%s\n",
  4639. pool->idle? "Dead" : "Alive",
  4640. pool->quota,
  4641. pool->prio,
  4642. pool->rpc_url, pool->rpc_user);
  4643. wattroff(logwin, A_BOLD | A_DIM);
  4644. }
  4645. retry:
  4646. wlogprint("\nCurrent pool management strategy: %s\n",
  4647. strategies[pool_strategy].s);
  4648. if (pool_strategy == POOL_ROTATE)
  4649. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  4650. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  4651. wlogprint("Pool [A]dd [R]emove [D]isable [E]nable [Q]uota change\n");
  4652. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  4653. wlogprint("Or press any other key to continue\n");
  4654. logwin_update();
  4655. input = getch();
  4656. if (!strncasecmp(&input, "a", 1)) {
  4657. input_pool(true);
  4658. goto updated;
  4659. } else if (!strncasecmp(&input, "r", 1)) {
  4660. if (total_pools <= 1) {
  4661. wlogprint("Cannot remove last pool");
  4662. goto retry;
  4663. }
  4664. selected = curses_int("Select pool number");
  4665. if (selected < 0 || selected >= total_pools) {
  4666. wlogprint("Invalid selection\n");
  4667. goto retry;
  4668. }
  4669. pool = pools[selected];
  4670. if (pool == current_pool())
  4671. switch_pools(NULL);
  4672. if (pool == current_pool()) {
  4673. wlogprint("Unable to remove pool due to activity\n");
  4674. goto retry;
  4675. }
  4676. disable_pool(pool);
  4677. remove_pool(pool);
  4678. goto updated;
  4679. } else if (!strncasecmp(&input, "s", 1)) {
  4680. selected = curses_int("Select pool number");
  4681. if (selected < 0 || selected >= total_pools) {
  4682. wlogprint("Invalid selection\n");
  4683. goto retry;
  4684. }
  4685. pool = pools[selected];
  4686. enable_pool(pool);
  4687. switch_pools(pool);
  4688. goto updated;
  4689. } else if (!strncasecmp(&input, "d", 1)) {
  4690. if (enabled_pools <= 1) {
  4691. wlogprint("Cannot disable last pool");
  4692. goto retry;
  4693. }
  4694. selected = curses_int("Select pool number");
  4695. if (selected < 0 || selected >= total_pools) {
  4696. wlogprint("Invalid selection\n");
  4697. goto retry;
  4698. }
  4699. pool = pools[selected];
  4700. disable_pool(pool);
  4701. if (pool == current_pool())
  4702. switch_pools(NULL);
  4703. goto updated;
  4704. } else if (!strncasecmp(&input, "e", 1)) {
  4705. selected = curses_int("Select pool number");
  4706. if (selected < 0 || selected >= total_pools) {
  4707. wlogprint("Invalid selection\n");
  4708. goto retry;
  4709. }
  4710. pool = pools[selected];
  4711. enable_pool(pool);
  4712. if (pool->prio < current_pool()->prio)
  4713. switch_pools(pool);
  4714. goto updated;
  4715. } else if (!strncasecmp(&input, "c", 1)) {
  4716. for (i = 0; i <= TOP_STRATEGY; i++)
  4717. wlogprint("%d: %s\n", i, strategies[i].s);
  4718. selected = curses_int("Select strategy number type");
  4719. if (selected < 0 || selected > TOP_STRATEGY) {
  4720. wlogprint("Invalid selection\n");
  4721. goto retry;
  4722. }
  4723. if (selected == POOL_ROTATE) {
  4724. opt_rotate_period = curses_int("Select interval in minutes");
  4725. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  4726. opt_rotate_period = 0;
  4727. wlogprint("Invalid selection\n");
  4728. goto retry;
  4729. }
  4730. }
  4731. pool_strategy = selected;
  4732. switch_pools(NULL);
  4733. goto updated;
  4734. } else if (!strncasecmp(&input, "i", 1)) {
  4735. selected = curses_int("Select pool number");
  4736. if (selected < 0 || selected >= total_pools) {
  4737. wlogprint("Invalid selection\n");
  4738. goto retry;
  4739. }
  4740. pool = pools[selected];
  4741. display_pool_summary(pool);
  4742. goto retry;
  4743. } else if (!strncasecmp(&input, "q", 1)) {
  4744. selected = curses_int("Select pool number");
  4745. if (selected < 0 || selected >= total_pools) {
  4746. wlogprint("Invalid selection\n");
  4747. goto retry;
  4748. }
  4749. pool = pools[selected];
  4750. selected = curses_int("Set quota");
  4751. if (selected < 0) {
  4752. wlogprint("Invalid negative quota\n");
  4753. goto retry;
  4754. }
  4755. pool->quota = selected;
  4756. adjust_quota_gcd();
  4757. goto updated;
  4758. } else if (!strncasecmp(&input, "f", 1)) {
  4759. opt_fail_only ^= true;
  4760. goto updated;
  4761. } else
  4762. clear_logwin();
  4763. immedok(logwin, false);
  4764. opt_loginput = false;
  4765. }
  4766. static void display_options(void)
  4767. {
  4768. int selected;
  4769. char input;
  4770. opt_loginput = true;
  4771. immedok(logwin, true);
  4772. clear_logwin();
  4773. retry:
  4774. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  4775. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n"
  4776. "[R]PC debug:%s\n[W]orkTime details:%s\nco[M]pact: %s\n"
  4777. "[T]oggle status switching:%s\n"
  4778. "w[I]descreen:%s\n"
  4779. "[Z]ero statistics\n"
  4780. "[L]og interval:%d\n",
  4781. opt_debug ? "on" : "off",
  4782. want_per_device_stats? "on" : "off",
  4783. opt_quiet ? "on" : "off",
  4784. opt_log_output ? "on" : "off",
  4785. opt_protocol ? "on" : "off",
  4786. opt_worktime ? "on" : "off",
  4787. opt_compact ? "on" : "off",
  4788. switch_status ? "enabled" : "disabled",
  4789. opt_widescreen ? "enabled" : "disabled",
  4790. opt_log_interval);
  4791. wlogprint("Select an option or any other key to return\n");
  4792. logwin_update();
  4793. input = getch();
  4794. if (!strncasecmp(&input, "q", 1)) {
  4795. opt_quiet ^= true;
  4796. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  4797. goto retry;
  4798. } else if (!strncasecmp(&input, "v", 1)) {
  4799. opt_log_output ^= true;
  4800. if (opt_log_output)
  4801. opt_quiet = false;
  4802. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  4803. goto retry;
  4804. } else if (!strncasecmp(&input, "n", 1)) {
  4805. opt_log_output = false;
  4806. opt_debug = false;
  4807. opt_quiet = false;
  4808. opt_protocol = false;
  4809. opt_compact = false;
  4810. want_per_device_stats = false;
  4811. wlogprint("Output mode reset to normal\n");
  4812. switch_logsize(false);
  4813. goto retry;
  4814. } else if (!strncasecmp(&input, "d", 1)) {
  4815. opt_debug ^= true;
  4816. opt_log_output = opt_debug;
  4817. if (opt_debug)
  4818. opt_quiet = false;
  4819. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  4820. goto retry;
  4821. } else if (!strncasecmp(&input, "m", 1)) {
  4822. opt_compact ^= true;
  4823. wlogprint("Compact mode %s\n", opt_compact ? "enabled" : "disabled");
  4824. switch_logsize(false);
  4825. goto retry;
  4826. } else if (!strncasecmp(&input, "p", 1)) {
  4827. want_per_device_stats ^= true;
  4828. opt_log_output = want_per_device_stats;
  4829. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  4830. goto retry;
  4831. } else if (!strncasecmp(&input, "r", 1)) {
  4832. opt_protocol ^= true;
  4833. if (opt_protocol)
  4834. opt_quiet = false;
  4835. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  4836. goto retry;
  4837. } else if (!strncasecmp(&input, "c", 1))
  4838. clear_logwin();
  4839. else if (!strncasecmp(&input, "l", 1)) {
  4840. selected = curses_int("Interval in seconds");
  4841. if (selected < 0 || selected > 9999) {
  4842. wlogprint("Invalid selection\n");
  4843. goto retry;
  4844. }
  4845. opt_log_interval = selected;
  4846. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  4847. goto retry;
  4848. } else if (!strncasecmp(&input, "s", 1)) {
  4849. opt_realquiet = true;
  4850. } else if (!strncasecmp(&input, "w", 1)) {
  4851. opt_worktime ^= true;
  4852. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  4853. goto retry;
  4854. } else if (!strncasecmp(&input, "t", 1)) {
  4855. switch_status ^= true;
  4856. goto retry;
  4857. } else if (!strncasecmp(&input, "i", 1)) {
  4858. opt_widescreen ^= true;
  4859. goto retry;
  4860. } else if (!strncasecmp(&input, "z", 1)) {
  4861. zero_stats();
  4862. goto retry;
  4863. } else
  4864. clear_logwin();
  4865. immedok(logwin, false);
  4866. opt_loginput = false;
  4867. }
  4868. #endif
  4869. void default_save_file(char *filename)
  4870. {
  4871. if (default_config && *default_config) {
  4872. strcpy(filename, default_config);
  4873. return;
  4874. }
  4875. #if defined(unix) || defined(__APPLE__)
  4876. if (getenv("HOME") && *getenv("HOME")) {
  4877. strcpy(filename, getenv("HOME"));
  4878. strcat(filename, "/");
  4879. }
  4880. else
  4881. strcpy(filename, "");
  4882. strcat(filename, ".cgminer/");
  4883. mkdir(filename, 0777);
  4884. #else
  4885. strcpy(filename, "");
  4886. #endif
  4887. strcat(filename, def_conf);
  4888. }
  4889. #ifdef HAVE_CURSES
  4890. static void set_options(void)
  4891. {
  4892. int selected;
  4893. char input;
  4894. opt_loginput = true;
  4895. immedok(logwin, true);
  4896. clear_logwin();
  4897. retry:
  4898. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  4899. "[W]rite config file\n[C]gminer restart\n",
  4900. opt_queue, opt_scantime, opt_expiry);
  4901. wlogprint("Select an option or any other key to return\n");
  4902. logwin_update();
  4903. input = getch();
  4904. if (!strncasecmp(&input, "q", 1)) {
  4905. selected = curses_int("Extra work items to queue");
  4906. if (selected < 0 || selected > 9999) {
  4907. wlogprint("Invalid selection\n");
  4908. goto retry;
  4909. }
  4910. opt_queue = selected;
  4911. if (opt_queue < max_queue)
  4912. max_queue = opt_queue;
  4913. goto retry;
  4914. } else if (!strncasecmp(&input, "s", 1)) {
  4915. selected = curses_int("Set scantime in seconds");
  4916. if (selected < 0 || selected > 9999) {
  4917. wlogprint("Invalid selection\n");
  4918. goto retry;
  4919. }
  4920. opt_scantime = selected;
  4921. goto retry;
  4922. } else if (!strncasecmp(&input, "e", 1)) {
  4923. selected = curses_int("Set expiry time in seconds");
  4924. if (selected < 0 || selected > 9999) {
  4925. wlogprint("Invalid selection\n");
  4926. goto retry;
  4927. }
  4928. opt_expiry = selected;
  4929. goto retry;
  4930. } else if (!strncasecmp(&input, "w", 1)) {
  4931. FILE *fcfg;
  4932. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  4933. default_save_file(filename);
  4934. snprintf(prompt, sizeof(prompt), "Config filename to write (Enter for default) [%s]", filename);
  4935. str = curses_input(prompt);
  4936. if (strcmp(str, "-1")) {
  4937. struct stat statbuf;
  4938. strcpy(filename, str);
  4939. free(str);
  4940. if (!stat(filename, &statbuf)) {
  4941. wlogprint("File exists, overwrite?\n");
  4942. input = getch();
  4943. if (strncasecmp(&input, "y", 1))
  4944. goto retry;
  4945. }
  4946. }
  4947. else
  4948. free(str);
  4949. fcfg = fopen(filename, "w");
  4950. if (!fcfg) {
  4951. wlogprint("Cannot open or create file\n");
  4952. goto retry;
  4953. }
  4954. write_config(fcfg);
  4955. fclose(fcfg);
  4956. goto retry;
  4957. } else if (!strncasecmp(&input, "c", 1)) {
  4958. wlogprint("Are you sure?\n");
  4959. input = getch();
  4960. if (!strncasecmp(&input, "y", 1))
  4961. app_restart();
  4962. else
  4963. clear_logwin();
  4964. } else
  4965. clear_logwin();
  4966. immedok(logwin, false);
  4967. opt_loginput = false;
  4968. }
  4969. #ifdef USE_USBUTILS
  4970. static void mt_enable(struct thr_info *mythr)
  4971. {
  4972. cgsem_post(&mythr->sem);
  4973. }
  4974. static void set_usb(void)
  4975. {
  4976. int selected, i, mt, enabled, disabled, zombie, total, blacklisted;
  4977. struct cgpu_info *cgpu;
  4978. struct thr_info *thr;
  4979. double val;
  4980. char input;
  4981. opt_loginput = true;
  4982. immedok(logwin, true);
  4983. clear_logwin();
  4984. retry:
  4985. enabled = 0;
  4986. disabled = 0;
  4987. zombie = 0;
  4988. total = 0;
  4989. blacklisted = 0;
  4990. rd_lock(&mining_thr_lock);
  4991. mt = mining_threads;
  4992. rd_unlock(&mining_thr_lock);
  4993. for (i = 0; i < mt; i++) {
  4994. cgpu = mining_thr[i]->cgpu;
  4995. if (unlikely(!cgpu))
  4996. continue;
  4997. if (cgpu->usbinfo.nodev)
  4998. zombie++;
  4999. else if (cgpu->deven == DEV_DISABLED)
  5000. disabled++;
  5001. else
  5002. enabled++;
  5003. if (cgpu->blacklisted)
  5004. blacklisted++;
  5005. total++;
  5006. }
  5007. wlogprint("Hotplug interval:%d\n", hotplug_time);
  5008. wlogprint("%d USB devices, %d enabled, %d disabled, %d zombie\n",
  5009. total, enabled, disabled, zombie);
  5010. wlogprint("[S]ummary of device information\n");
  5011. wlogprint("[E]nable device\n");
  5012. wlogprint("[D]isable device\n");
  5013. wlogprint("[U]nplug to allow hotplug restart\n");
  5014. wlogprint("[R]eset device USB\n");
  5015. wlogprint("[L]ist all known devices\n");
  5016. wlogprint("[B]lacklist current device from current instance of cgminer\n");
  5017. wlogprint("[W]hitelist previously blacklisted device\n");
  5018. wlogprint("[H]otplug interval (0 to disable)\n");
  5019. wlogprint("Select an option or any other key to return\n");
  5020. logwin_update();
  5021. input = getch();
  5022. if (!strncasecmp(&input, "s", 1)) {
  5023. selected = curses_int("Select device number");
  5024. if (selected < 0 || selected >= mt) {
  5025. wlogprint("Invalid selection\n");
  5026. goto retry;
  5027. }
  5028. cgpu = mining_thr[selected]->cgpu;
  5029. wlogprint("Device %03u:%03u\n", cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  5030. wlogprint("Name %s\n", cgpu->drv->name);
  5031. wlogprint("ID %d\n", cgpu->device_id);
  5032. wlogprint("Enabled: %s\n", cgpu->deven != DEV_DISABLED ? "Yes" : "No");
  5033. wlogprint("Temperature %.1f\n", cgpu->temp);
  5034. wlogprint("MHS av %.0f\n", cgpu->total_mhashes / cgpu_runtime(cgpu));
  5035. wlogprint("Accepted %d\n", cgpu->accepted);
  5036. wlogprint("Rejected %d\n", cgpu->rejected);
  5037. wlogprint("Hardware Errors %d\n", cgpu->hw_errors);
  5038. wlogprint("Last Share Pool %d\n", cgpu->last_share_pool_time > 0 ? cgpu->last_share_pool : -1);
  5039. wlogprint("Total MH %.1f\n", cgpu->total_mhashes);
  5040. wlogprint("Diff1 Work %"PRId64"\n", cgpu->diff1);
  5041. wlogprint("Difficulty Accepted %.1f\n", cgpu->diff_accepted);
  5042. wlogprint("Difficulty Rejected %.1f\n", cgpu->diff_rejected);
  5043. wlogprint("Last Share Difficulty %.1f\n", cgpu->last_share_diff);
  5044. wlogprint("No Device: %s\n", cgpu->usbinfo.nodev ? "True" : "False");
  5045. wlogprint("Last Valid Work %"PRIu64"\n", (uint64_t)cgpu->last_device_valid_work);
  5046. val = 0;
  5047. if (cgpu->hw_errors + cgpu->diff1)
  5048. val = cgpu->hw_errors / (cgpu->hw_errors + cgpu->diff1);
  5049. wlogprint("Device Hardware %.1f%%\n", val);
  5050. val = 0;
  5051. if (cgpu->diff1)
  5052. val = cgpu->diff_rejected / cgpu->diff1;
  5053. wlogprint("Device Rejected %.1f%%\n", val);
  5054. goto retry;
  5055. } else if (!strncasecmp(&input, "e", 1)) {
  5056. selected = curses_int("Select device number");
  5057. if (selected < 0 || selected >= mt) {
  5058. wlogprint("Invalid selection\n");
  5059. goto retry;
  5060. }
  5061. cgpu = mining_thr[selected]->cgpu;
  5062. if (cgpu->usbinfo.nodev) {
  5063. wlogprint("Device removed, unable to re-enable!\n");
  5064. goto retry;
  5065. }
  5066. thr = get_thread(selected);
  5067. cgpu->deven = DEV_ENABLED;
  5068. mt_enable(thr);
  5069. goto retry;
  5070. } else if (!strncasecmp(&input, "d", 1)) {
  5071. selected = curses_int("Select device number");
  5072. if (selected < 0 || selected >= mt) {
  5073. wlogprint("Invalid selection\n");
  5074. goto retry;
  5075. }
  5076. cgpu = mining_thr[selected]->cgpu;
  5077. cgpu->deven = DEV_DISABLED;
  5078. goto retry;
  5079. } else if (!strncasecmp(&input, "u", 1)) {
  5080. selected = curses_int("Select device number");
  5081. if (selected < 0 || selected >= mt) {
  5082. wlogprint("Invalid selection\n");
  5083. goto retry;
  5084. }
  5085. cgpu = mining_thr[selected]->cgpu;
  5086. if (cgpu->usbinfo.nodev) {
  5087. wlogprint("Device already removed, unable to unplug!\n");
  5088. goto retry;
  5089. }
  5090. usb_nodev(cgpu);
  5091. goto retry;
  5092. } else if (!strncasecmp(&input, "r", 1)) {
  5093. selected = curses_int("Select device number");
  5094. if (selected < 0 || selected >= mt) {
  5095. wlogprint("Invalid selection\n");
  5096. goto retry;
  5097. }
  5098. cgpu = mining_thr[selected]->cgpu;
  5099. if (cgpu->usbinfo.nodev) {
  5100. wlogprint("Device already removed, unable to reset!\n");
  5101. goto retry;
  5102. }
  5103. usb_reset(cgpu);
  5104. goto retry;
  5105. } else if (!strncasecmp(&input, "b", 1)) {
  5106. selected = curses_int("Select device number");
  5107. if (selected < 0 || selected >= mt) {
  5108. wlogprint("Invalid selection\n");
  5109. goto retry;
  5110. }
  5111. cgpu = mining_thr[selected]->cgpu;
  5112. if (cgpu->usbinfo.nodev) {
  5113. wlogprint("Device already removed, unable to blacklist!\n");
  5114. goto retry;
  5115. }
  5116. blacklist_cgpu(cgpu);
  5117. goto retry;
  5118. } else if (!strncasecmp(&input, "w", 1)) {
  5119. if (!blacklisted) {
  5120. wlogprint("No blacklisted devices!\n");
  5121. goto retry;
  5122. }
  5123. wlogprint("Blacklisted devices:\n");
  5124. for (i = 0; i < mt; i++) {
  5125. cgpu = mining_thr[i]->cgpu;
  5126. if (unlikely(!cgpu))
  5127. continue;
  5128. if (cgpu->blacklisted) {
  5129. wlogprint("%d: %s %d %03u:%03u\n", i, cgpu->drv->name,
  5130. cgpu->device_id, cgpu->usbinfo.bus_number,
  5131. cgpu->usbinfo.device_address);
  5132. }
  5133. }
  5134. selected = curses_int("Select device number");
  5135. if (selected < 0 || selected >= mt) {
  5136. wlogprint("Invalid selection\n");
  5137. goto retry;
  5138. }
  5139. cgpu = mining_thr[selected]->cgpu;
  5140. if (!cgpu->blacklisted) {
  5141. wlogprint("Device not blacklisted, unable to whitelist\n");
  5142. goto retry;
  5143. }
  5144. whitelist_cgpu(cgpu);
  5145. goto retry;
  5146. } else if (!strncasecmp(&input, "h", 1)) {
  5147. selected = curses_int("Select hotplug interval in seconds (0 to disable)");
  5148. if (selected < 0 || selected > 9999) {
  5149. wlogprint("Invalid value\n");
  5150. goto retry;
  5151. }
  5152. hotplug_time = selected;
  5153. goto retry;
  5154. } else if (!strncasecmp(&input, "l", 1)) {
  5155. usb_list();
  5156. goto retry;
  5157. } else
  5158. clear_logwin();
  5159. immedok(logwin, false);
  5160. opt_loginput = false;
  5161. }
  5162. #endif
  5163. static void *input_thread(void __maybe_unused *userdata)
  5164. {
  5165. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5166. RenameThread("Input");
  5167. if (!curses_active)
  5168. return NULL;
  5169. while (1) {
  5170. char input;
  5171. input = getch();
  5172. if (!strncasecmp(&input, "q", 1)) {
  5173. kill_work();
  5174. return NULL;
  5175. } else if (!strncasecmp(&input, "d", 1))
  5176. display_options();
  5177. else if (!strncasecmp(&input, "p", 1))
  5178. display_pools();
  5179. else if (!strncasecmp(&input, "s", 1))
  5180. set_options();
  5181. #ifdef USE_USBUTILS
  5182. else if (!strncasecmp(&input, "u", 1))
  5183. set_usb();
  5184. #endif
  5185. if (opt_realquiet) {
  5186. disable_curses();
  5187. break;
  5188. }
  5189. }
  5190. return NULL;
  5191. }
  5192. #endif
  5193. static void *api_thread(void *userdata)
  5194. {
  5195. struct thr_info *mythr = userdata;
  5196. pthread_detach(pthread_self());
  5197. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  5198. RenameThread("API");
  5199. set_lowprio();
  5200. api(api_thr_id);
  5201. PTH(mythr) = 0L;
  5202. return NULL;
  5203. }
  5204. /* Sole work devices are serialised wrt calling get_work so they report in on
  5205. * each pass through their scanhash function as well as in get_work whereas
  5206. * queued work devices work asynchronously so get them to report in and out
  5207. * only across get_work. */
  5208. static void thread_reportin(struct thr_info *thr)
  5209. {
  5210. thr->getwork = false;
  5211. cgtime(&thr->last);
  5212. thr->cgpu->status = LIFE_WELL;
  5213. thr->cgpu->device_last_well = time(NULL);
  5214. }
  5215. /* Tell the watchdog thread this thread is waiting on get work and should not
  5216. * be restarted */
  5217. static void thread_reportout(struct thr_info *thr)
  5218. {
  5219. thr->getwork = true;
  5220. cgtime(&thr->last);
  5221. thr->cgpu->status = LIFE_WELL;
  5222. thr->cgpu->device_last_well = time(NULL);
  5223. }
  5224. static void hashmeter(int thr_id, uint64_t hashes_done)
  5225. {
  5226. bool showlog = false;
  5227. double tv_tdiff, mhashes_done = 0.0;
  5228. time_t now_t;
  5229. int diff_t;
  5230. cgtime(&total_tv_end);
  5231. tv_tdiff = tdiff(&total_tv_end, &tv_hashmeter);
  5232. now_t = total_tv_end.tv_sec;
  5233. diff_t = now_t - hashdisplay_t;
  5234. if (diff_t >= opt_log_interval) {
  5235. alt_status ^= switch_status;
  5236. hashdisplay_t = now_t;
  5237. showlog = true;
  5238. } else if (thr_id < 0) {
  5239. /* hashmeter is called by non-mining threads in case nothing
  5240. * has reported in to allow hashrate to converge to zero , but
  5241. * we only update if it has been more than opt_log_interval */
  5242. return;
  5243. }
  5244. copy_time(&tv_hashmeter, &total_tv_end);
  5245. if (thr_id >= 0) {
  5246. struct thr_info *thr = get_thread(thr_id);
  5247. struct cgpu_info *cgpu = thr->cgpu;
  5248. double device_tdiff, thr_mhs;
  5249. /* Update the last time this thread reported in */
  5250. copy_time(&thr->last, &total_tv_end);
  5251. cgpu->device_last_well = now_t;
  5252. device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5253. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5254. thr_mhs = (double)hashes_done / device_tdiff / 1000000;
  5255. applog(LOG_DEBUG, "[thread %d: %"PRIu64" hashes, %.1f mhash/sec]",
  5256. thr_id, hashes_done, thr_mhs);
  5257. mhashes_done = hashes_done / 1000000.0;
  5258. mutex_lock(&hash_lock);
  5259. cgpu->total_mhashes += mhashes_done;
  5260. decay_time(&cgpu->rolling, mhashes_done, device_tdiff, opt_log_interval);
  5261. decay_time(&cgpu->rolling1, mhashes_done, device_tdiff, 60.0);
  5262. decay_time(&cgpu->rolling5, mhashes_done, device_tdiff, 300.0);
  5263. decay_time(&cgpu->rolling15, mhashes_done, device_tdiff, 900.0);
  5264. mutex_unlock(&hash_lock);
  5265. if (want_per_device_stats && showlog) {
  5266. char logline[256];
  5267. get_statline(logline, sizeof(logline), cgpu);
  5268. if (!curses_active) {
  5269. printf("%s \r", logline);
  5270. fflush(stdout);
  5271. } else
  5272. applog(LOG_INFO, "%s", logline);
  5273. }
  5274. } else {
  5275. /* No device has reported in, we have been called from the
  5276. * watchdog thread so decay all the hashrates */
  5277. mutex_lock(&hash_lock);
  5278. for (thr_id = 0; thr_id < mining_threads; thr_id++) {
  5279. struct thr_info *thr = get_thread(thr_id);
  5280. struct cgpu_info *cgpu = thr->cgpu;
  5281. double device_tdiff = tdiff(&total_tv_end, &cgpu->last_message_tv);
  5282. copy_time(&cgpu->last_message_tv, &total_tv_end);
  5283. decay_time(&cgpu->rolling, 0, device_tdiff, opt_log_interval);
  5284. decay_time(&cgpu->rolling1, 0, device_tdiff, 60.0);
  5285. decay_time(&cgpu->rolling5, 0, device_tdiff, 300.0);
  5286. decay_time(&cgpu->rolling15, 0, device_tdiff, 900.0);
  5287. }
  5288. mutex_unlock(&hash_lock);
  5289. }
  5290. mutex_lock(&hash_lock);
  5291. total_mhashes_done += mhashes_done;
  5292. decay_time(&total_rolling, mhashes_done, tv_tdiff, opt_log_interval);
  5293. decay_time(&rolling1, mhashes_done, tv_tdiff, 60.0);
  5294. decay_time(&rolling5, mhashes_done, tv_tdiff, 300.0);
  5295. decay_time(&rolling15, mhashes_done, tv_tdiff, 900.0);
  5296. global_hashrate = llround(total_rolling) * 1000000;
  5297. total_secs = tdiff(&total_tv_end, &total_tv_start);
  5298. if (showlog) {
  5299. char displayed_hashes[16], displayed_rolling[16];
  5300. char displayed_r1[16], displayed_r5[16], displayed_r15[16];
  5301. uint64_t d64;
  5302. d64 = (double)total_mhashes_done / total_secs * 1000000ull;
  5303. suffix_string(d64, displayed_hashes, sizeof(displayed_hashes), 4);
  5304. d64 = (double)total_rolling * 1000000ull;
  5305. suffix_string(d64, displayed_rolling, sizeof(displayed_rolling), 4);
  5306. d64 = (double)rolling1 * 1000000ull;
  5307. suffix_string(d64, displayed_r1, sizeof(displayed_rolling), 4);
  5308. d64 = (double)rolling5 * 1000000ull;
  5309. suffix_string(d64, displayed_r5, sizeof(displayed_rolling), 4);
  5310. d64 = (double)rolling15 * 1000000ull;
  5311. suffix_string(d64, displayed_r15, sizeof(displayed_rolling), 4);
  5312. snprintf(statusline, sizeof(statusline),
  5313. "(%ds):%s (1m):%s (5m):%s (15m):%s (avg):%sh/s",
  5314. opt_log_interval, displayed_rolling, displayed_r1, displayed_r5,
  5315. displayed_r15, displayed_hashes);
  5316. }
  5317. mutex_unlock(&hash_lock);
  5318. if (showlog) {
  5319. if (!curses_active) {
  5320. printf("%s \r", statusline);
  5321. fflush(stdout);
  5322. } else
  5323. applog(LOG_INFO, "%s", statusline);
  5324. }
  5325. }
  5326. static void stratum_share_result(json_t *val, json_t *res_val, json_t *err_val,
  5327. struct stratum_share *sshare)
  5328. {
  5329. struct work *work = sshare->work;
  5330. time_t now_t = time(NULL);
  5331. char hashshow[64];
  5332. int srdiff;
  5333. srdiff = now_t - sshare->sshare_sent;
  5334. if (opt_debug || srdiff > 0) {
  5335. applog(LOG_INFO, "Pool %d stratum share result lag time %d seconds",
  5336. work->pool->pool_no, srdiff);
  5337. }
  5338. show_hash(work, hashshow);
  5339. share_result(val, res_val, err_val, work, hashshow, false, "");
  5340. }
  5341. /* Parses stratum json responses and tries to find the id that the request
  5342. * matched to and treat it accordingly. */
  5343. static bool parse_stratum_response(struct pool *pool, char *s)
  5344. {
  5345. json_t *val = NULL, *err_val, *res_val, *id_val;
  5346. struct stratum_share *sshare;
  5347. json_error_t err;
  5348. bool ret = false;
  5349. int id;
  5350. val = JSON_LOADS(s, &err);
  5351. if (!val) {
  5352. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  5353. goto out;
  5354. }
  5355. res_val = json_object_get(val, "result");
  5356. if (!res_val)
  5357. goto out;
  5358. err_val = json_object_get(val, "error");
  5359. id_val = json_object_get(val, "id");
  5360. if (json_is_null(id_val) || !id_val) {
  5361. char *ss;
  5362. if (err_val)
  5363. ss = json_dumps(err_val, JSON_INDENT(3));
  5364. else
  5365. ss = strdup("(unknown reason)");
  5366. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  5367. free(ss);
  5368. goto out;
  5369. }
  5370. id = json_integer_value(id_val);
  5371. mutex_lock(&sshare_lock);
  5372. HASH_FIND_INT(stratum_shares, &id, sshare);
  5373. if (sshare) {
  5374. HASH_DEL(stratum_shares, sshare);
  5375. pool->sshares--;
  5376. }
  5377. mutex_unlock(&sshare_lock);
  5378. if (!sshare) {
  5379. double pool_diff;
  5380. /* Since the share is untracked, we can only guess at what the
  5381. * work difficulty is based on the current pool diff. */
  5382. cg_rlock(&pool->data_lock);
  5383. pool_diff = pool->sdiff;
  5384. cg_runlock(&pool->data_lock);
  5385. if (json_is_true(res_val)) {
  5386. applog(LOG_NOTICE, "Accepted untracked stratum share from pool %d", pool->pool_no);
  5387. /* We don't know what device this came from so we can't
  5388. * attribute the work to the relevant cgpu */
  5389. mutex_lock(&stats_lock);
  5390. total_accepted++;
  5391. pool->accepted++;
  5392. total_diff_accepted += pool_diff;
  5393. pool->diff_accepted += pool_diff;
  5394. mutex_unlock(&stats_lock);
  5395. } else {
  5396. applog(LOG_NOTICE, "Rejected untracked stratum share from pool %d", pool->pool_no);
  5397. mutex_lock(&stats_lock);
  5398. total_rejected++;
  5399. pool->rejected++;
  5400. total_diff_rejected += pool_diff;
  5401. pool->diff_rejected += pool_diff;
  5402. mutex_unlock(&stats_lock);
  5403. }
  5404. goto out;
  5405. }
  5406. stratum_share_result(val, res_val, err_val, sshare);
  5407. free_work(sshare->work);
  5408. free(sshare);
  5409. ret = true;
  5410. out:
  5411. if (val)
  5412. json_decref(val);
  5413. return ret;
  5414. }
  5415. void clear_stratum_shares(struct pool *pool)
  5416. {
  5417. struct stratum_share *sshare, *tmpshare;
  5418. double diff_cleared = 0;
  5419. int cleared = 0;
  5420. mutex_lock(&sshare_lock);
  5421. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  5422. if (sshare->work->pool == pool) {
  5423. HASH_DEL(stratum_shares, sshare);
  5424. diff_cleared += sshare->work->work_difficulty;
  5425. free_work(sshare->work);
  5426. pool->sshares--;
  5427. free(sshare);
  5428. cleared++;
  5429. }
  5430. }
  5431. mutex_unlock(&sshare_lock);
  5432. if (cleared) {
  5433. applog(LOG_WARNING, "Lost %d shares due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5434. pool->stale_shares += cleared;
  5435. total_stale += cleared;
  5436. pool->diff_stale += diff_cleared;
  5437. total_diff_stale += diff_cleared;
  5438. }
  5439. }
  5440. void clear_pool_work(struct pool *pool)
  5441. {
  5442. struct work *work, *tmp;
  5443. int cleared = 0;
  5444. mutex_lock(stgd_lock);
  5445. HASH_ITER(hh, staged_work, work, tmp) {
  5446. if (work->pool == pool) {
  5447. HASH_DEL(staged_work, work);
  5448. free_work(work);
  5449. cleared++;
  5450. }
  5451. }
  5452. mutex_unlock(stgd_lock);
  5453. if (cleared)
  5454. applog(LOG_INFO, "Cleared %d work items due to stratum disconnect on pool %d", cleared, pool->pool_no);
  5455. }
  5456. static int cp_prio(void)
  5457. {
  5458. int prio;
  5459. cg_rlock(&control_lock);
  5460. prio = currentpool->prio;
  5461. cg_runlock(&control_lock);
  5462. return prio;
  5463. }
  5464. /* We only need to maintain a secondary pool connection when we need the
  5465. * capacity to get work from the backup pools while still on the primary */
  5466. static bool cnx_needed(struct pool *pool)
  5467. {
  5468. struct pool *cp;
  5469. if (pool->enabled != POOL_ENABLED)
  5470. return false;
  5471. /* Balance strategies need all pools online */
  5472. if (pool_strategy == POOL_BALANCE)
  5473. return true;
  5474. if (pool_strategy == POOL_LOADBALANCE)
  5475. return true;
  5476. /* Idle stratum pool needs something to kick it alive again */
  5477. if (pool->has_stratum && pool->idle)
  5478. return true;
  5479. /* Getwork pools without opt_fail_only need backup pools up to be able
  5480. * to leak shares */
  5481. cp = current_pool();
  5482. if (cp == pool)
  5483. return true;
  5484. if (!pool_localgen(cp) && (!opt_fail_only || !cp->hdr_path))
  5485. return true;
  5486. /* If we're waiting for a response from shares submitted, keep the
  5487. * connection open. */
  5488. if (pool->sshares)
  5489. return true;
  5490. /* If the pool has only just come to life and is higher priority than
  5491. * the current pool keep the connection open so we can fail back to
  5492. * it. */
  5493. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5494. return true;
  5495. /* We've run out of work, bring anything back to life. */
  5496. if (no_work)
  5497. return true;
  5498. return false;
  5499. }
  5500. static void wait_lpcurrent(struct pool *pool);
  5501. static void pool_resus(struct pool *pool);
  5502. static void gen_stratum_work(struct pool *pool, struct work *work);
  5503. void stratum_resumed(struct pool *pool)
  5504. {
  5505. if (pool_tclear(pool, &pool->idle)) {
  5506. applog(LOG_INFO, "Stratum connection to pool %d resumed", pool->pool_no);
  5507. pool_resus(pool);
  5508. }
  5509. }
  5510. static bool supports_resume(struct pool *pool)
  5511. {
  5512. bool ret;
  5513. cg_rlock(&pool->data_lock);
  5514. ret = (pool->sessionid != NULL);
  5515. cg_runlock(&pool->data_lock);
  5516. return ret;
  5517. }
  5518. /* One stratum receive thread per pool that has stratum waits on the socket
  5519. * checking for new messages and for the integrity of the socket connection. We
  5520. * reset the connection based on the integrity of the receive side only as the
  5521. * send side will eventually expire data it fails to send. */
  5522. static void *stratum_rthread(void *userdata)
  5523. {
  5524. struct pool *pool = (struct pool *)userdata;
  5525. char threadname[16];
  5526. pthread_detach(pthread_self());
  5527. snprintf(threadname, sizeof(threadname), "%d/RStratum", pool->pool_no);
  5528. RenameThread(threadname);
  5529. while (42) {
  5530. struct timeval timeout;
  5531. int sel_ret;
  5532. fd_set rd;
  5533. char *s;
  5534. if (unlikely(pool->removed)) {
  5535. suspend_stratum(pool);
  5536. break;
  5537. }
  5538. /* Check to see whether we need to maintain this connection
  5539. * indefinitely or just bring it up when we switch to this
  5540. * pool */
  5541. if (!sock_full(pool) && !cnx_needed(pool)) {
  5542. suspend_stratum(pool);
  5543. clear_stratum_shares(pool);
  5544. clear_pool_work(pool);
  5545. wait_lpcurrent(pool);
  5546. while (!restart_stratum(pool)) {
  5547. if (pool->removed)
  5548. goto out;
  5549. if (enabled_pools > 1)
  5550. cgsleep_ms(30000);
  5551. else
  5552. cgsleep_ms(3000);
  5553. }
  5554. }
  5555. FD_ZERO(&rd);
  5556. FD_SET(pool->sock, &rd);
  5557. timeout.tv_sec = 90;
  5558. timeout.tv_usec = 0;
  5559. /* The protocol specifies that notify messages should be sent
  5560. * every minute so if we fail to receive any for 90 seconds we
  5561. * assume the connection has been dropped and treat this pool
  5562. * as dead */
  5563. if (!sock_full(pool) && (sel_ret = select(pool->sock + 1, &rd, NULL, NULL, &timeout)) < 1) {
  5564. applog(LOG_DEBUG, "Stratum select failed on pool %d with value %d", pool->pool_no, sel_ret);
  5565. s = NULL;
  5566. } else
  5567. s = recv_line(pool);
  5568. if (!s) {
  5569. applog(LOG_NOTICE, "Stratum connection to pool %d interrupted", pool->pool_no);
  5570. pool->getfail_occasions++;
  5571. total_go++;
  5572. /* If the socket to our stratum pool disconnects, all
  5573. * tracked submitted shares are lost and we will leak
  5574. * the memory if we don't discard their records. */
  5575. if (!supports_resume(pool) || opt_lowmem)
  5576. clear_stratum_shares(pool);
  5577. clear_pool_work(pool);
  5578. if (pool == current_pool())
  5579. restart_threads();
  5580. while (!restart_stratum(pool)) {
  5581. if (pool->removed)
  5582. goto out;
  5583. cgsleep_ms(30000);
  5584. }
  5585. continue;
  5586. }
  5587. /* Check this pool hasn't died while being a backup pool and
  5588. * has not had its idle flag cleared */
  5589. stratum_resumed(pool);
  5590. if (!parse_method(pool, s) && !parse_stratum_response(pool, s))
  5591. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  5592. else if (pool->swork.clean) {
  5593. struct work *work = make_work();
  5594. /* Generate a single work item to update the current
  5595. * block database */
  5596. pool->swork.clean = false;
  5597. gen_stratum_work(pool, work);
  5598. work->longpoll = true;
  5599. /* Return value doesn't matter. We're just informing
  5600. * that we may need to restart. */
  5601. test_work_current(work);
  5602. free_work(work);
  5603. }
  5604. free(s);
  5605. }
  5606. out:
  5607. return NULL;
  5608. }
  5609. /* Each pool has one stratum send thread for sending shares to avoid many
  5610. * threads being created for submission since all sends need to be serialised
  5611. * anyway. */
  5612. static void *stratum_sthread(void *userdata)
  5613. {
  5614. struct pool *pool = (struct pool *)userdata;
  5615. char threadname[16];
  5616. pthread_detach(pthread_self());
  5617. snprintf(threadname, sizeof(threadname), "%d/SStratum", pool->pool_no);
  5618. RenameThread(threadname);
  5619. pool->stratum_q = tq_new();
  5620. if (!pool->stratum_q)
  5621. quit(1, "Failed to create stratum_q in stratum_sthread");
  5622. while (42) {
  5623. char noncehex[12], nonce2hex[20], s[1024];
  5624. struct stratum_share *sshare;
  5625. uint32_t *hash32, nonce;
  5626. unsigned char nonce2[8];
  5627. uint64_t *nonce2_64;
  5628. struct work *work;
  5629. bool submitted;
  5630. if (unlikely(pool->removed))
  5631. break;
  5632. work = tq_pop(pool->stratum_q, NULL);
  5633. if (unlikely(!work))
  5634. quit(1, "Stratum q returned empty work");
  5635. if (unlikely(work->nonce2_len > 8)) {
  5636. applog(LOG_ERR, "Pool %d asking for inappropriately long nonce2 length %d",
  5637. pool->pool_no, (int)work->nonce2_len);
  5638. applog(LOG_ERR, "Not attempting to submit shares");
  5639. free_work(work);
  5640. continue;
  5641. }
  5642. sshare = calloc(sizeof(struct stratum_share), 1);
  5643. hash32 = (uint32_t *)work->hash;
  5644. submitted = false;
  5645. sshare->sshare_time = time(NULL);
  5646. /* This work item is freed in parse_stratum_response */
  5647. sshare->work = work;
  5648. nonce = *((uint32_t *)(work->data + 76));
  5649. __bin2hex(noncehex, (const unsigned char *)&nonce, 4);
  5650. memset(s, 0, 1024);
  5651. mutex_lock(&sshare_lock);
  5652. /* Give the stratum share a unique id */
  5653. sshare->id = swork_id++;
  5654. mutex_unlock(&sshare_lock);
  5655. nonce2_64 = (uint64_t *)nonce2;
  5656. *nonce2_64 = htole64(work->nonce2);
  5657. __bin2hex(nonce2hex, nonce2, work->nonce2_len);
  5658. snprintf(s, sizeof(s),
  5659. "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  5660. pool->rpc_user, work->job_id, nonce2hex, work->ntime, noncehex, sshare->id);
  5661. applog(LOG_INFO, "Submitting share %08lx to pool %d",
  5662. (long unsigned int)htole32(hash32[6]), pool->pool_no);
  5663. /* Try resubmitting for up to 2 minutes if we fail to submit
  5664. * once and the stratum pool nonce1 still matches suggesting
  5665. * we may be able to resume. */
  5666. while (time(NULL) < sshare->sshare_time + 120) {
  5667. bool sessionid_match;
  5668. if (likely(stratum_send(pool, s, strlen(s)))) {
  5669. mutex_lock(&sshare_lock);
  5670. HASH_ADD_INT(stratum_shares, id, sshare);
  5671. pool->sshares++;
  5672. mutex_unlock(&sshare_lock);
  5673. if (pool_tclear(pool, &pool->submit_fail))
  5674. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  5675. applog(LOG_DEBUG, "Successfully submitted, adding to stratum_shares db");
  5676. submitted = true;
  5677. break;
  5678. }
  5679. if (!pool_tset(pool, &pool->submit_fail) && cnx_needed(pool)) {
  5680. applog(LOG_WARNING, "Pool %d stratum share submission failure", pool->pool_no);
  5681. total_ro++;
  5682. pool->remotefail_occasions++;
  5683. }
  5684. if (opt_lowmem) {
  5685. applog(LOG_DEBUG, "Lowmem option prevents resubmitting stratum share");
  5686. break;
  5687. }
  5688. cg_rlock(&pool->data_lock);
  5689. sessionid_match = (pool->nonce1 && !strcmp(work->nonce1, pool->nonce1));
  5690. cg_runlock(&pool->data_lock);
  5691. if (!sessionid_match) {
  5692. applog(LOG_DEBUG, "No matching session id for resubmitting stratum share");
  5693. break;
  5694. }
  5695. /* Retry every 5 seconds */
  5696. sleep(5);
  5697. }
  5698. if (unlikely(!submitted)) {
  5699. applog(LOG_DEBUG, "Failed to submit stratum share, discarding");
  5700. free_work(work);
  5701. free(sshare);
  5702. pool->stale_shares++;
  5703. total_stale++;
  5704. } else {
  5705. int ssdiff;
  5706. sshare->sshare_sent = time(NULL);
  5707. ssdiff = sshare->sshare_sent - sshare->sshare_time;
  5708. if (opt_debug || ssdiff > 0) {
  5709. applog(LOG_INFO, "Pool %d stratum share submission lag time %d seconds",
  5710. pool->pool_no, ssdiff);
  5711. }
  5712. }
  5713. }
  5714. /* Freeze the work queue but don't free up its memory in case there is
  5715. * work still trying to be submitted to the removed pool. */
  5716. tq_freeze(pool->stratum_q);
  5717. return NULL;
  5718. }
  5719. static void init_stratum_threads(struct pool *pool)
  5720. {
  5721. have_longpoll = true;
  5722. if (unlikely(pthread_create(&pool->stratum_sthread, NULL, stratum_sthread, (void *)pool)))
  5723. quit(1, "Failed to create stratum sthread");
  5724. if (unlikely(pthread_create(&pool->stratum_rthread, NULL, stratum_rthread, (void *)pool)))
  5725. quit(1, "Failed to create stratum rthread");
  5726. }
  5727. static void *longpoll_thread(void *userdata);
  5728. static bool stratum_works(struct pool *pool)
  5729. {
  5730. applog(LOG_INFO, "Testing pool %d stratum %s", pool->pool_no, pool->stratum_url);
  5731. check_extranonce_option(pool, pool->stratum_url);
  5732. if (!extract_sockaddr(pool->stratum_url, &pool->sockaddr_url, &pool->stratum_port))
  5733. return false;
  5734. if (!initiate_stratum(pool))
  5735. return false;
  5736. return true;
  5737. }
  5738. #ifdef HAVE_LIBCURL
  5739. static void __setup_gbt_solo(struct pool *pool)
  5740. {
  5741. cg_wlock(&pool->gbt_lock);
  5742. memcpy(pool->coinbase, scriptsig_header_bin, 41);
  5743. pool->coinbase[41 + pool->n1_len + 4 + 1 + 8] = 25;
  5744. memcpy(pool->coinbase + 41 + pool->n1_len + 4 + 1 + 8 + 1, pool->script_pubkey, 25);
  5745. cg_wunlock(&pool->gbt_lock);
  5746. }
  5747. static bool setup_gbt_solo(CURL *curl, struct pool *pool)
  5748. {
  5749. char s[256];
  5750. int uninitialised_var(rolltime);
  5751. bool ret = false;
  5752. json_t *val = NULL, *res_val, *valid_val;
  5753. if (!opt_btc_address) {
  5754. applog(LOG_ERR, "No BTC address specified, unable to mine solo on %s",
  5755. pool->rpc_url);
  5756. goto out;
  5757. }
  5758. snprintf(s, 256, "{\"method\": \"validateaddress\", \"params\": [\"%s\"]}\n", opt_btc_address);
  5759. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, true,
  5760. false, &rolltime, pool, false);
  5761. if (!val)
  5762. goto out;
  5763. res_val = json_object_get(val, "result");
  5764. if (!res_val)
  5765. goto out;
  5766. valid_val = json_object_get(res_val, "isvalid");
  5767. if (!valid_val)
  5768. goto out;
  5769. if (!json_is_true(valid_val)) {
  5770. applog(LOG_ERR, "Bitcoin address %s is NOT valid", opt_btc_address);
  5771. goto out;
  5772. }
  5773. applog(LOG_NOTICE, "Solo mining to valid address: %s", opt_btc_address);
  5774. ret = true;
  5775. address_to_pubkeyhash(pool->script_pubkey, opt_btc_address);
  5776. hex2bin(scriptsig_header_bin, scriptsig_header, 41);
  5777. __setup_gbt_solo(pool);
  5778. if (opt_debug) {
  5779. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  5780. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  5781. free(cb);
  5782. }
  5783. pool->gbt_curl = curl_easy_init();
  5784. if (unlikely(!pool->gbt_curl))
  5785. quit(1, "GBT CURL initialisation failed");
  5786. out:
  5787. if (val)
  5788. json_decref(val);
  5789. return ret;
  5790. }
  5791. #else
  5792. static bool setup_gbt_solo(CURL __maybe_unused *curl, struct pool __maybe_unused *pool)
  5793. {
  5794. return false;
  5795. }
  5796. #endif
  5797. static void pool_start_lp(struct pool *pool)
  5798. {
  5799. if (!pool->lp_started) {
  5800. pool->lp_started = true;
  5801. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  5802. quit(1, "Failed to create pool longpoll thread");
  5803. }
  5804. }
  5805. static bool pool_active(struct pool *pool, bool pinging)
  5806. {
  5807. struct timeval tv_getwork, tv_getwork_reply;
  5808. json_t *val = NULL;
  5809. bool ret = false;
  5810. CURL *curl;
  5811. int uninitialised_var(rolltime);
  5812. if (pool->has_gbt)
  5813. applog(LOG_DEBUG, "Retrieving block template from pool %s", pool->rpc_url);
  5814. else
  5815. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  5816. /* This is the central point we activate stratum when we can */
  5817. retry_stratum:
  5818. if (pool->has_stratum) {
  5819. /* We create the stratum thread for each pool just after
  5820. * successful authorisation. Once the init flag has been set
  5821. * we never unset it and the stratum thread is responsible for
  5822. * setting/unsetting the active flag */
  5823. bool init = pool_tset(pool, &pool->stratum_init);
  5824. if (!init) {
  5825. bool ret = initiate_stratum(pool) && auth_stratum(pool);
  5826. if (ret)
  5827. init_stratum_threads(pool);
  5828. else
  5829. pool_tclear(pool, &pool->stratum_init);
  5830. return ret;
  5831. }
  5832. return pool->stratum_active;
  5833. }
  5834. curl = curl_easy_init();
  5835. if (unlikely(!curl)) {
  5836. applog(LOG_ERR, "CURL initialisation failed");
  5837. return false;
  5838. }
  5839. /* Probe for GBT support on first pass */
  5840. if (!pool->probed) {
  5841. applog(LOG_DEBUG, "Probing for GBT support");
  5842. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5843. gbt_req, true, false, &rolltime, pool, false);
  5844. if (val) {
  5845. bool append = false, submit = false, transactions = false;
  5846. json_t *res_val, *mutables;
  5847. int i, mutsize = 0;
  5848. res_val = json_object_get(val, "result");
  5849. if (res_val) {
  5850. mutables = json_object_get(res_val, "mutable");
  5851. mutsize = json_array_size(mutables);
  5852. }
  5853. for (i = 0; i < mutsize; i++) {
  5854. json_t *arrval = json_array_get(mutables, i);
  5855. if (json_is_string(arrval)) {
  5856. const char *mutable = json_string_value(arrval);
  5857. if (!strncasecmp(mutable, "coinbase/append", 15))
  5858. append = true;
  5859. else if (!strncasecmp(mutable, "submit/coinbase", 15))
  5860. submit = true;
  5861. else if (!strncasecmp(mutable, "transactions", 12))
  5862. transactions = true;
  5863. }
  5864. }
  5865. json_decref(val);
  5866. /* Only use GBT if it supports coinbase append and
  5867. * submit coinbase */
  5868. if (append && submit) {
  5869. pool->has_gbt = true;
  5870. pool->rpc_req = gbt_req;
  5871. } else if (transactions) {
  5872. pool->gbt_solo = true;
  5873. pool->rpc_req = gbt_solo_req;
  5874. }
  5875. }
  5876. /* Reset this so we can probe fully just after this. It will be
  5877. * set to true that time.*/
  5878. pool->probed = false;
  5879. if (pool->has_gbt)
  5880. applog(LOG_DEBUG, "GBT coinbase + append support found, switching to GBT protocol");
  5881. else if (pool->gbt_solo)
  5882. applog(LOG_DEBUG, "GBT coinbase without append found, switching to GBT solo protocol");
  5883. else
  5884. applog(LOG_DEBUG, "No GBT coinbase + append support found, using getwork protocol");
  5885. }
  5886. cgtime(&tv_getwork);
  5887. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass,
  5888. pool->rpc_req, true, false, &rolltime, pool, false);
  5889. cgtime(&tv_getwork_reply);
  5890. /* Detect if a http getwork pool has an X-Stratum header at startup,
  5891. * and if so, switch to that in preference to getwork if it works */
  5892. if (pool->stratum_url && !opt_fix_protocol && stratum_works(pool)) {
  5893. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  5894. if (!pool->rpc_url)
  5895. pool->rpc_url = strdup(pool->stratum_url);
  5896. pool->has_stratum = true;
  5897. curl_easy_cleanup(curl);
  5898. goto retry_stratum;
  5899. }
  5900. if (val) {
  5901. struct work *work = make_work();
  5902. bool rc;
  5903. rc = work_decode(pool, work, val);
  5904. if (rc) {
  5905. if (pool->gbt_solo) {
  5906. ret = setup_gbt_solo(curl, pool);
  5907. if (ret)
  5908. pool_start_lp(pool);
  5909. free_work(work);
  5910. goto out;
  5911. }
  5912. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  5913. pool->pool_no, pool->rpc_url);
  5914. work->pool = pool;
  5915. work->rolltime = rolltime;
  5916. copy_time(&work->tv_getwork, &tv_getwork);
  5917. copy_time(&work->tv_getwork_reply, &tv_getwork_reply);
  5918. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  5919. calc_diff(work, 0);
  5920. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  5921. stage_work(work);
  5922. total_getworks++;
  5923. pool->getwork_requested++;
  5924. ret = true;
  5925. } else {
  5926. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  5927. pool->pool_no, pool->rpc_url);
  5928. free_work(work);
  5929. }
  5930. if (pool->lp_url)
  5931. goto out;
  5932. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  5933. if (pool->hdr_path) {
  5934. char *copy_start, *hdr_path;
  5935. bool need_slash = false;
  5936. size_t siz;
  5937. hdr_path = pool->hdr_path;
  5938. if (strstr(hdr_path, "://")) {
  5939. pool->lp_url = hdr_path;
  5940. hdr_path = NULL;
  5941. } else {
  5942. /* absolute path, on current server */
  5943. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  5944. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  5945. need_slash = true;
  5946. siz = strlen(pool->rpc_url) + strlen(copy_start) + 2;
  5947. pool->lp_url = malloc(siz);
  5948. if (!pool->lp_url) {
  5949. applog(LOG_ERR, "Malloc failure in pool_active");
  5950. return false;
  5951. }
  5952. snprintf(pool->lp_url, siz, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  5953. }
  5954. } else
  5955. pool->lp_url = NULL;
  5956. pool_start_lp(pool);
  5957. } else {
  5958. /* If we failed to parse a getwork, this could be a stratum
  5959. * url without the prefix stratum+tcp:// so let's check it */
  5960. if (initiate_stratum(pool)) {
  5961. pool->has_stratum = true;
  5962. goto retry_stratum;
  5963. }
  5964. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  5965. pool->pool_no, pool->rpc_url);
  5966. if (!pinging && !pool->idle)
  5967. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  5968. }
  5969. out:
  5970. if (val)
  5971. json_decref(val);
  5972. curl_easy_cleanup(curl);
  5973. return ret;
  5974. }
  5975. static void pool_resus(struct pool *pool)
  5976. {
  5977. pool->seq_getfails = 0;
  5978. if (pool_strategy == POOL_FAILOVER && pool->prio < cp_prio())
  5979. applog(LOG_WARNING, "Pool %d %s alive, testing stability", pool->pool_no, pool->rpc_url);
  5980. else
  5981. applog(LOG_INFO, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  5982. }
  5983. static bool work_filled;
  5984. static bool work_emptied;
  5985. /* If this is called non_blocking, it will return NULL for work so that must
  5986. * be handled. */
  5987. static struct work *hash_pop(bool blocking)
  5988. {
  5989. struct work *work = NULL, *tmp;
  5990. int hc;
  5991. mutex_lock(stgd_lock);
  5992. if (!HASH_COUNT(staged_work)) {
  5993. /* Increase the queue if we reach zero and we know we can reach
  5994. * the maximum we're asking for. */
  5995. if (work_filled && max_queue < opt_queue) {
  5996. max_queue++;
  5997. work_filled = false;
  5998. }
  5999. work_emptied = true;
  6000. if (!blocking)
  6001. goto out_unlock;
  6002. do {
  6003. struct timespec then;
  6004. struct timeval now;
  6005. int rc;
  6006. cgtime(&now);
  6007. then.tv_sec = now.tv_sec + 10;
  6008. then.tv_nsec = now.tv_usec * 1000;
  6009. pthread_cond_signal(&gws_cond);
  6010. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, &then);
  6011. /* Check again for !no_work as multiple threads may be
  6012. * waiting on this condition and another may set the
  6013. * bool separately. */
  6014. if (rc && !no_work) {
  6015. no_work = true;
  6016. applog(LOG_WARNING, "Waiting for work to be available from pools.");
  6017. }
  6018. } while (!HASH_COUNT(staged_work));
  6019. }
  6020. if (no_work) {
  6021. applog(LOG_WARNING, "Work available from pools, resuming.");
  6022. no_work = false;
  6023. }
  6024. hc = HASH_COUNT(staged_work);
  6025. /* Find clone work if possible, to allow masters to be reused */
  6026. if (hc > staged_rollable) {
  6027. HASH_ITER(hh, staged_work, work, tmp) {
  6028. if (!work_rollable(work))
  6029. break;
  6030. }
  6031. } else
  6032. work = staged_work;
  6033. HASH_DEL(staged_work, work);
  6034. if (work_rollable(work))
  6035. staged_rollable--;
  6036. /* Signal the getwork scheduler to look for more work */
  6037. pthread_cond_signal(&gws_cond);
  6038. /* Signal hash_pop again in case there are mutliple hash_pop waiters */
  6039. pthread_cond_signal(&getq->cond);
  6040. /* Keep track of last getwork grabbed */
  6041. last_getwork = time(NULL);
  6042. out_unlock:
  6043. mutex_unlock(stgd_lock);
  6044. return work;
  6045. }
  6046. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  6047. {
  6048. unsigned char hash1[32];
  6049. sha256(data, len, hash1);
  6050. sha256(hash1, 32, hash);
  6051. }
  6052. void set_target(unsigned char *dest_target, double diff)
  6053. {
  6054. unsigned char target[32];
  6055. uint64_t *data64, h64;
  6056. double d64, dcut64;
  6057. if (unlikely(diff == 0.0)) {
  6058. /* This shouldn't happen but best we check to prevent a crash */
  6059. applog(LOG_ERR, "Diff zero passed to set_target");
  6060. diff = 1.0;
  6061. }
  6062. d64 = truediffone;
  6063. if (opt_scrypt)
  6064. d64 *= (double)65536;
  6065. d64 /= diff;
  6066. dcut64 = d64 / bits192;
  6067. h64 = dcut64;
  6068. data64 = (uint64_t *)(target + 24);
  6069. *data64 = htole64(h64);
  6070. dcut64 = h64;
  6071. dcut64 *= bits192;
  6072. d64 -= dcut64;
  6073. dcut64 = d64 / bits128;
  6074. h64 = dcut64;
  6075. data64 = (uint64_t *)(target + 16);
  6076. *data64 = htole64(h64);
  6077. dcut64 = h64;
  6078. dcut64 *= bits128;
  6079. d64 -= dcut64;
  6080. dcut64 = d64 / bits64;
  6081. h64 = dcut64;
  6082. data64 = (uint64_t *)(target + 8);
  6083. *data64 = htole64(h64);
  6084. dcut64 = h64;
  6085. dcut64 *= bits64;
  6086. d64 -= dcut64;
  6087. h64 = d64;
  6088. data64 = (uint64_t *)(target);
  6089. *data64 = htole64(h64);
  6090. if (opt_debug) {
  6091. char *htarget = bin2hex(target, 32);
  6092. applog(LOG_DEBUG, "Generated target %s", htarget);
  6093. free(htarget);
  6094. }
  6095. memcpy(dest_target, target, 32);
  6096. }
  6097. #if defined (USE_AVALON2) || defined (USE_HASHRATIO)
  6098. bool submit_nonce2_nonce(struct thr_info *thr, struct pool *pool, struct pool *real_pool,
  6099. uint32_t nonce2, uint32_t nonce)
  6100. {
  6101. const int thr_id = thr->id;
  6102. struct cgpu_info *cgpu = thr->cgpu;
  6103. struct device_drv *drv = cgpu->drv;
  6104. struct work *work = make_work();
  6105. bool ret;
  6106. cg_wlock(&pool->data_lock);
  6107. pool->nonce2 = nonce2;
  6108. cg_wunlock(&pool->data_lock);
  6109. gen_stratum_work(pool, work);
  6110. work->pool = real_pool;
  6111. work->thr_id = thr_id;
  6112. work->work_block = work_block;
  6113. work->pool->works++;
  6114. work->mined = true;
  6115. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6116. work->device_diff = MAX(drv->min_diff, work->device_diff);
  6117. ret = submit_nonce(thr, work, nonce);
  6118. free_work(work);
  6119. return ret;
  6120. }
  6121. #endif
  6122. /* Generates stratum based work based on the most recent notify information
  6123. * from the pool. This will keep generating work while a pool is down so we use
  6124. * other means to detect when the pool has died in stratum_thread */
  6125. static void gen_stratum_work(struct pool *pool, struct work *work)
  6126. {
  6127. unsigned char merkle_root[32], merkle_sha[64];
  6128. uint32_t *data32, *swap32;
  6129. uint64_t nonce2le;
  6130. int i;
  6131. cg_wlock(&pool->data_lock);
  6132. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6133. * from left to right and prevent overflow errors with small n2sizes */
  6134. nonce2le = htole64(pool->nonce2);
  6135. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6136. work->nonce2 = pool->nonce2++;
  6137. work->nonce2_len = pool->n2size;
  6138. /* Downgrade to a read lock to read off the pool variables */
  6139. cg_dwlock(&pool->data_lock);
  6140. /* Generate merkle root */
  6141. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6142. memcpy(merkle_sha, merkle_root, 32);
  6143. for (i = 0; i < pool->merkles; i++) {
  6144. memcpy(merkle_sha + 32, pool->swork.merkle_bin[i], 32);
  6145. gen_hash(merkle_sha, merkle_root, 64);
  6146. memcpy(merkle_sha, merkle_root, 32);
  6147. }
  6148. data32 = (uint32_t *)merkle_sha;
  6149. swap32 = (uint32_t *)merkle_root;
  6150. flip32(swap32, data32);
  6151. /* Copy the data template from header_bin */
  6152. memcpy(work->data, pool->header_bin, 112);
  6153. memcpy(work->data + 36, merkle_root, 32);
  6154. /* Store the stratum work diff to check it still matches the pool's
  6155. * stratum diff when submitting shares */
  6156. work->sdiff = pool->sdiff;
  6157. /* Copy parameters required for share submission */
  6158. work->job_id = strdup(pool->swork.job_id);
  6159. work->nonce1 = strdup(pool->nonce1);
  6160. work->ntime = strdup(pool->ntime);
  6161. cg_runlock(&pool->data_lock);
  6162. if (opt_debug) {
  6163. char *header, *merkle_hash;
  6164. header = bin2hex(work->data, 112);
  6165. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6166. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  6167. applog(LOG_DEBUG, "Generated stratum header %s", header);
  6168. applog(LOG_DEBUG, "Work job_id %s nonce2 %"PRIu64" ntime %s", work->job_id,
  6169. work->nonce2, work->ntime);
  6170. free(header);
  6171. free(merkle_hash);
  6172. }
  6173. calc_midstate(work);
  6174. set_target(work->target, work->sdiff);
  6175. local_work++;
  6176. work->pool = pool;
  6177. work->stratum = true;
  6178. work->nonce = 0;
  6179. work->longpoll = false;
  6180. work->getwork_mode = GETWORK_MODE_STRATUM;
  6181. work->work_block = work_block;
  6182. /* Nominally allow a driver to ntime roll 60 seconds */
  6183. work->drv_rolllimit = 60;
  6184. calc_diff(work, work->sdiff);
  6185. cgtime(&work->tv_staged);
  6186. }
  6187. #ifdef HAVE_LIBCURL
  6188. static void gen_solo_work(struct pool *pool, struct work *work);
  6189. /* Use the one instance of gbt_curl, protecting the bool with the gbt_lock but
  6190. * avoiding holding the lock once we've set the bool. */
  6191. static void get_gbt_curl(struct pool *pool, int poll)
  6192. {
  6193. cg_ilock(&pool->gbt_lock);
  6194. while (pool->gbt_curl_inuse) {
  6195. cg_uilock(&pool->gbt_lock);
  6196. cgsleep_ms(poll);
  6197. cg_ilock(&pool->gbt_lock);
  6198. }
  6199. cg_ulock(&pool->gbt_lock);
  6200. pool->gbt_curl_inuse = true;
  6201. cg_wunlock(&pool->gbt_lock);
  6202. }
  6203. /* No need for locking here */
  6204. static inline void release_gbt_curl(struct pool *pool)
  6205. {
  6206. pool->gbt_curl_inuse = false;
  6207. }
  6208. static void update_gbt_solo(struct pool *pool)
  6209. {
  6210. struct work *work = make_work();
  6211. int rolltime;
  6212. json_t *val;
  6213. get_gbt_curl(pool, 10);
  6214. retry:
  6215. /* Bitcoind doesn't like many open RPC connections. */
  6216. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  6217. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, pool->rpc_req,
  6218. true, false, &rolltime, pool, false);
  6219. if (likely(val)) {
  6220. bool rc = work_decode(pool, work, val);
  6221. if (rc) {
  6222. __setup_gbt_solo(pool);
  6223. gen_solo_work(pool, work);
  6224. stage_work(work);
  6225. } else
  6226. free_work(work);
  6227. json_decref(val);
  6228. } else {
  6229. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get gbt, retrying in 5s",
  6230. pool->pool_no);
  6231. if (++pool->seq_getfails > 5) {
  6232. pool_died(pool);
  6233. goto out;
  6234. }
  6235. cgsleep_ms(5000);
  6236. goto retry;
  6237. }
  6238. out:
  6239. release_gbt_curl(pool);
  6240. }
  6241. static void gen_solo_work(struct pool *pool, struct work *work)
  6242. {
  6243. unsigned char merkle_root[32], merkle_sha[64];
  6244. uint32_t *data32, *swap32;
  6245. struct timeval now;
  6246. uint64_t nonce2le;
  6247. int i;
  6248. cgtime(&now);
  6249. if (now.tv_sec - pool->tv_lastwork.tv_sec > 60)
  6250. update_gbt_solo(pool);
  6251. cg_wlock(&pool->gbt_lock);
  6252. /* Update coinbase. Always use an LE encoded nonce2 to fill in values
  6253. * from left to right and prevent overflow errors with small n2sizes */
  6254. nonce2le = htole64(pool->nonce2);
  6255. memcpy(pool->coinbase + pool->nonce2_offset, &nonce2le, pool->n2size);
  6256. work->nonce2 = pool->nonce2++;
  6257. work->nonce2_len = pool->n2size;
  6258. work->gbt_txns = pool->transactions + 1;
  6259. /* Downgrade to a read lock to read off the pool variables */
  6260. cg_dwlock(&pool->gbt_lock);
  6261. work->coinbase = bin2hex(pool->coinbase, pool->coinbase_len);
  6262. /* Generate merkle root */
  6263. gen_hash(pool->coinbase, merkle_root, pool->coinbase_len);
  6264. memcpy(merkle_sha, merkle_root, 32);
  6265. for (i = 0; i < pool->merkles; i++) {
  6266. unsigned char *merkle_bin;
  6267. merkle_bin = pool->merklebin + (i * 32);
  6268. memcpy(merkle_sha + 32, merkle_bin, 32);
  6269. gen_hash(merkle_sha, merkle_root, 64);
  6270. memcpy(merkle_sha, merkle_root, 32);
  6271. }
  6272. data32 = (uint32_t *)merkle_sha;
  6273. swap32 = (uint32_t *)merkle_root;
  6274. flip32(swap32, data32);
  6275. /* Copy the data template from header_bin */
  6276. memcpy(work->data, pool->header_bin, 112);
  6277. memcpy(work->data + 36, merkle_root, 32);
  6278. work->sdiff = pool->sdiff;
  6279. /* Copy parameters required for share submission */
  6280. work->ntime = strdup(pool->ntime);
  6281. memcpy(work->target, pool->gbt_target, 32);
  6282. cg_runlock(&pool->gbt_lock);
  6283. if (opt_debug) {
  6284. char *header, *merkle_hash;
  6285. header = bin2hex(work->data, 112);
  6286. merkle_hash = bin2hex((const unsigned char *)merkle_root, 32);
  6287. applog(LOG_DEBUG, "Generated GBT solo merkle %s", merkle_hash);
  6288. applog(LOG_DEBUG, "Generated GBT solo header %s", header);
  6289. applog(LOG_DEBUG, "Work nonce2 %"PRIu64" ntime %s", work->nonce2,
  6290. work->ntime);
  6291. free(header);
  6292. free(merkle_hash);
  6293. }
  6294. calc_midstate(work);
  6295. local_work++;
  6296. work->gbt = true;
  6297. work->pool = pool;
  6298. work->nonce = 0;
  6299. work->longpoll = false;
  6300. work->getwork_mode = GETWORK_MODE_SOLO;
  6301. work->work_block = work_block;
  6302. /* Nominally allow a driver to ntime roll 60 seconds */
  6303. work->drv_rolllimit = 60;
  6304. calc_diff(work, work->sdiff);
  6305. cgtime(&work->tv_staged);
  6306. }
  6307. #endif
  6308. /* The time difference in seconds between when this device last got work via
  6309. * get_work() and generated a valid share. */
  6310. int share_work_tdiff(struct cgpu_info *cgpu)
  6311. {
  6312. return last_getwork - cgpu->last_device_valid_work;
  6313. }
  6314. static void set_benchmark_work(struct cgpu_info *cgpu, struct work *work)
  6315. {
  6316. cgpu->lodiff += cgpu->direction;
  6317. if (cgpu->lodiff < 1)
  6318. cgpu->direction = 1;
  6319. if (cgpu->lodiff > 15) {
  6320. cgpu->direction = -1;
  6321. if (++cgpu->hidiff > 15)
  6322. cgpu->hidiff = 0;
  6323. memcpy(work, &bench_hidiff_bins[cgpu->hidiff][0], 160);
  6324. } else
  6325. memcpy(work, &bench_lodiff_bins[cgpu->lodiff][0], 160);
  6326. }
  6327. struct work *get_work(struct thr_info *thr, const int thr_id)
  6328. {
  6329. struct cgpu_info *cgpu = thr->cgpu;
  6330. struct work *work = NULL;
  6331. time_t diff_t;
  6332. thread_reportout(thr);
  6333. applog(LOG_DEBUG, "Popping work from get queue to get work");
  6334. diff_t = time(NULL);
  6335. while (!work) {
  6336. work = hash_pop(true);
  6337. if (stale_work(work, false)) {
  6338. discard_work(work);
  6339. wake_gws();
  6340. }
  6341. }
  6342. diff_t = time(NULL) - diff_t;
  6343. /* Since this is a blocking function, we need to add grace time to
  6344. * the device's last valid work to not make outages appear to be
  6345. * device failures. */
  6346. if (diff_t > 0) {
  6347. applog(LOG_DEBUG, "Get work blocked for %d seconds", (int)diff_t);
  6348. cgpu->last_device_valid_work += diff_t;
  6349. }
  6350. applog(LOG_DEBUG, "Got work from get queue to get work for thread %d", thr_id);
  6351. work->thr_id = thr_id;
  6352. if (opt_benchmark)
  6353. set_benchmark_work(cgpu, work);
  6354. thread_reportin(thr);
  6355. work->mined = true;
  6356. work->device_diff = MIN(cgpu->drv->max_diff, work->work_difficulty);
  6357. work->device_diff = MAX(cgpu->drv->min_diff, work->device_diff);
  6358. return work;
  6359. }
  6360. /* Submit a copy of the tested, statistic recorded work item asynchronously */
  6361. static void submit_work_async(struct work *work)
  6362. {
  6363. struct pool *pool = work->pool;
  6364. pthread_t submit_thread;
  6365. cgtime(&work->tv_work_found);
  6366. if (opt_benchmark) {
  6367. struct cgpu_info *cgpu = get_thr_cgpu(work->thr_id);
  6368. mutex_lock(&stats_lock);
  6369. cgpu->accepted++;
  6370. total_accepted++;
  6371. pool->accepted++;
  6372. cgpu->diff_accepted += work->work_difficulty;
  6373. total_diff_accepted += work->work_difficulty;
  6374. pool->diff_accepted += work->work_difficulty;
  6375. mutex_unlock(&stats_lock);
  6376. applog(LOG_NOTICE, "Accepted %s %d benchmark share nonce %08x",
  6377. cgpu->drv->name, cgpu->device_id, *(uint32_t *)(work->data + 64 + 12));
  6378. return;
  6379. }
  6380. if (stale_work(work, true)) {
  6381. if (opt_submit_stale)
  6382. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as user requested", pool->pool_no);
  6383. else if (pool->submit_old)
  6384. applog(LOG_NOTICE, "Pool %d stale share detected, submitting as pool requested", pool->pool_no);
  6385. else {
  6386. applog(LOG_NOTICE, "Pool %d stale share detected, discarding", pool->pool_no);
  6387. sharelog("discard", work);
  6388. mutex_lock(&stats_lock);
  6389. total_stale++;
  6390. pool->stale_shares++;
  6391. total_diff_stale += work->work_difficulty;
  6392. pool->diff_stale += work->work_difficulty;
  6393. mutex_unlock(&stats_lock);
  6394. free_work(work);
  6395. return;
  6396. }
  6397. work->stale = true;
  6398. }
  6399. if (work->stratum) {
  6400. applog(LOG_DEBUG, "Pushing pool %d work to stratum queue", pool->pool_no);
  6401. if (unlikely(!tq_push(pool->stratum_q, work))) {
  6402. applog(LOG_DEBUG, "Discarding work from removed pool");
  6403. free_work(work);
  6404. }
  6405. } else {
  6406. applog(LOG_DEBUG, "Pushing submit work to work thread");
  6407. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)work)))
  6408. quit(1, "Failed to create submit_work_thread");
  6409. }
  6410. }
  6411. void inc_hw_errors(struct thr_info *thr)
  6412. {
  6413. applog(LOG_INFO, "%s%d: invalid nonce - HW error", thr->cgpu->drv->name,
  6414. thr->cgpu->device_id);
  6415. mutex_lock(&stats_lock);
  6416. hw_errors++;
  6417. thr->cgpu->hw_errors++;
  6418. mutex_unlock(&stats_lock);
  6419. thr->cgpu->drv->hw_error(thr);
  6420. }
  6421. /* Fills in the work nonce and builds the output data in work->hash */
  6422. static void rebuild_nonce(struct work *work, uint32_t nonce)
  6423. {
  6424. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  6425. *work_nonce = htole32(nonce);
  6426. rebuild_hash(work);
  6427. }
  6428. /* For testing a nonce against diff 1 */
  6429. bool test_nonce(struct work *work, uint32_t nonce)
  6430. {
  6431. uint32_t *hash_32 = (uint32_t *)(work->hash + 28);
  6432. rebuild_nonce(work, nonce);
  6433. return (*hash_32 <= (opt_scrypt ? 0x0000ffffUL : 0));
  6434. }
  6435. /* For testing a nonce against an arbitrary diff */
  6436. bool test_nonce_diff(struct work *work, uint32_t nonce, double diff)
  6437. {
  6438. uint64_t *hash64 = (uint64_t *)(work->hash + 24), diff64;
  6439. rebuild_nonce(work, nonce);
  6440. diff64 = opt_scrypt ? 0x0000ffff00000000ULL : 0x00000000ffff0000ULL;
  6441. diff64 /= diff;
  6442. return (le64toh(*hash64) <= diff64);
  6443. }
  6444. static void update_work_stats(struct thr_info *thr, struct work *work)
  6445. {
  6446. double test_diff = current_diff;
  6447. work->share_diff = share_diff(work);
  6448. if (opt_scrypt)
  6449. test_diff *= (double)65536;
  6450. if (unlikely(work->share_diff >= test_diff)) {
  6451. work->block = true;
  6452. work->pool->solved++;
  6453. found_blocks++;
  6454. work->mandatory = true;
  6455. applog(LOG_NOTICE, "Found block for pool %d!", work->pool->pool_no);
  6456. }
  6457. mutex_lock(&stats_lock);
  6458. total_diff1 += work->device_diff;
  6459. thr->cgpu->diff1 += work->device_diff;
  6460. work->pool->diff1 += work->device_diff;
  6461. thr->cgpu->last_device_valid_work = time(NULL);
  6462. mutex_unlock(&stats_lock);
  6463. }
  6464. /* To be used once the work has been tested to be meet diff1 and has had its
  6465. * nonce adjusted. Returns true if the work target is met. */
  6466. bool submit_tested_work(struct thr_info *thr, struct work *work)
  6467. {
  6468. struct work *work_out;
  6469. update_work_stats(thr, work);
  6470. if (!fulltest(work->hash, work->target)) {
  6471. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6472. thr->cgpu->device_id);
  6473. return false;
  6474. }
  6475. work_out = copy_work(work);
  6476. submit_work_async(work_out);
  6477. return true;
  6478. }
  6479. /* Returns true if nonce for work was a valid share */
  6480. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  6481. {
  6482. if (test_nonce(work, nonce))
  6483. submit_tested_work(thr, work);
  6484. else {
  6485. inc_hw_errors(thr);
  6486. return false;
  6487. }
  6488. if (opt_benchfile && opt_benchfile_display)
  6489. benchfile_dspwork(work, nonce);
  6490. return true;
  6491. }
  6492. /* Allows drivers to submit work items where the driver has changed the ntime
  6493. * value by noffset. Must be only used with a work protocol that does not ntime
  6494. * roll itself intrinsically to generate work (eg stratum). We do not touch
  6495. * the original work struct, but the copy of it only. */
  6496. bool submit_noffset_nonce(struct thr_info *thr, struct work *work_in, uint32_t nonce,
  6497. int noffset)
  6498. {
  6499. struct work *work = make_work();
  6500. bool ret = false;
  6501. _copy_work(work, work_in, noffset);
  6502. if (!test_nonce(work, nonce)) {
  6503. free_work(work);
  6504. inc_hw_errors(thr);
  6505. goto out;
  6506. }
  6507. update_work_stats(thr, work);
  6508. if (opt_benchfile && opt_benchfile_display)
  6509. benchfile_dspwork(work, nonce);
  6510. ret = true;
  6511. if (!fulltest(work->hash, work->target)) {
  6512. free_work(work);
  6513. applog(LOG_INFO, "%s %d: Share above target", thr->cgpu->drv->name,
  6514. thr->cgpu->device_id);
  6515. goto out;
  6516. }
  6517. submit_work_async(work);
  6518. out:
  6519. return ret;
  6520. }
  6521. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  6522. {
  6523. if (wdiff->tv_sec > opt_scantime || hashes >= 0xfffffffe ||
  6524. stale_work(work, false))
  6525. return true;
  6526. return false;
  6527. }
  6528. static void mt_disable(struct thr_info *mythr, const int thr_id,
  6529. struct device_drv *drv)
  6530. {
  6531. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  6532. mythr->cgpu->rolling = 0;
  6533. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6534. cgsem_wait(&mythr->sem);
  6535. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  6536. drv->thread_enable(mythr);
  6537. }
  6538. /* The main hashing loop for devices that are slow enough to work on one work
  6539. * item at a time, without a queue, aborting work before the entire nonce
  6540. * range has been hashed if needed. */
  6541. static void hash_sole_work(struct thr_info *mythr)
  6542. {
  6543. const int thr_id = mythr->id;
  6544. struct cgpu_info *cgpu = mythr->cgpu;
  6545. struct device_drv *drv = cgpu->drv;
  6546. struct timeval getwork_start, tv_start, *tv_end, tv_workstart, tv_lastupdate;
  6547. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  6548. struct cgminer_stats *pool_stats;
  6549. /* Try to cycle approximately 5 times before each log update */
  6550. const long cycle = opt_log_interval / 5 ? : 1;
  6551. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  6552. struct timeval diff, sdiff, wdiff = {0, 0};
  6553. uint32_t max_nonce = drv->can_limit_work(mythr);
  6554. int64_t hashes_done = 0;
  6555. tv_end = &getwork_start;
  6556. cgtime(&getwork_start);
  6557. sdiff.tv_sec = sdiff.tv_usec = 0;
  6558. cgtime(&tv_lastupdate);
  6559. while (likely(!cgpu->shutdown)) {
  6560. struct work *work = get_work(mythr, thr_id);
  6561. int64_t hashes;
  6562. mythr->work_restart = false;
  6563. cgpu->new_work = true;
  6564. cgtime(&tv_workstart);
  6565. work->nonce = 0;
  6566. cgpu->max_hashes = 0;
  6567. if (!drv->prepare_work(mythr, work)) {
  6568. applog(LOG_ERR, "work prepare failed, exiting "
  6569. "mining thread %d", thr_id);
  6570. break;
  6571. }
  6572. work->device_diff = MIN(drv->max_diff, work->work_difficulty);
  6573. work->device_diff = MAX(drv->min_diff, work->device_diff);
  6574. do {
  6575. cgtime(&tv_start);
  6576. subtime(&tv_start, &getwork_start);
  6577. addtime(&getwork_start, &dev_stats->getwork_wait);
  6578. if (time_more(&getwork_start, &dev_stats->getwork_wait_max))
  6579. copy_time(&dev_stats->getwork_wait_max, &getwork_start);
  6580. if (time_less(&getwork_start, &dev_stats->getwork_wait_min))
  6581. copy_time(&dev_stats->getwork_wait_min, &getwork_start);
  6582. dev_stats->getwork_calls++;
  6583. pool_stats = &(work->pool->cgminer_stats);
  6584. addtime(&getwork_start, &pool_stats->getwork_wait);
  6585. if (time_more(&getwork_start, &pool_stats->getwork_wait_max))
  6586. copy_time(&pool_stats->getwork_wait_max, &getwork_start);
  6587. if (time_less(&getwork_start, &pool_stats->getwork_wait_min))
  6588. copy_time(&pool_stats->getwork_wait_min, &getwork_start);
  6589. pool_stats->getwork_calls++;
  6590. cgtime(&(work->tv_work_start));
  6591. /* Only allow the mining thread to be cancelled when
  6592. * it is not in the driver code. */
  6593. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
  6594. thread_reportin(mythr);
  6595. hashes = drv->scanhash(mythr, work, work->nonce + max_nonce);
  6596. thread_reportout(mythr);
  6597. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  6598. pthread_testcancel();
  6599. /* tv_end is == &getwork_start */
  6600. cgtime(&getwork_start);
  6601. if (unlikely(hashes == -1)) {
  6602. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6603. cgpu->deven = DEV_DISABLED;
  6604. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6605. cgpu->shutdown = true;
  6606. break;
  6607. }
  6608. hashes_done += hashes;
  6609. if (hashes > cgpu->max_hashes)
  6610. cgpu->max_hashes = hashes;
  6611. timersub(tv_end, &tv_start, &diff);
  6612. sdiff.tv_sec += diff.tv_sec;
  6613. sdiff.tv_usec += diff.tv_usec;
  6614. if (sdiff.tv_usec > 1000000) {
  6615. ++sdiff.tv_sec;
  6616. sdiff.tv_usec -= 1000000;
  6617. }
  6618. timersub(tv_end, &tv_workstart, &wdiff);
  6619. if (unlikely((long)sdiff.tv_sec < cycle)) {
  6620. int mult;
  6621. if (likely(max_nonce == 0xffffffff))
  6622. continue;
  6623. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  6624. mult *= cycle;
  6625. if (max_nonce > (0xffffffff * 0x400) / mult)
  6626. max_nonce = 0xffffffff;
  6627. else
  6628. max_nonce = (max_nonce * mult) / 0x400;
  6629. } else if (unlikely(sdiff.tv_sec > cycle))
  6630. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  6631. else if (unlikely(sdiff.tv_usec > 100000))
  6632. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  6633. timersub(tv_end, &tv_lastupdate, &diff);
  6634. /* Update the hashmeter at most 5 times per second */
  6635. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6636. diff.tv_sec >= opt_log_interval) {
  6637. hashmeter(thr_id, hashes_done);
  6638. hashes_done = 0;
  6639. copy_time(&tv_lastupdate, tv_end);
  6640. }
  6641. if (unlikely(mythr->work_restart)) {
  6642. /* Apart from device_thread 0, we stagger the
  6643. * starting of every next thread to try and get
  6644. * all devices busy before worrying about
  6645. * getting work for their extra threads */
  6646. if (!primary) {
  6647. struct timespec rgtp;
  6648. rgtp.tv_sec = 0;
  6649. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  6650. nanosleep(&rgtp, NULL);
  6651. }
  6652. break;
  6653. }
  6654. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6655. mt_disable(mythr, thr_id, drv);
  6656. sdiff.tv_sec = sdiff.tv_usec = 0;
  6657. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  6658. free_work(work);
  6659. }
  6660. cgpu->deven = DEV_DISABLED;
  6661. }
  6662. /* Put a new unqueued work item in cgpu->unqueued_work under cgpu->qlock till
  6663. * the driver tells us it's full so that it may extract the work item using
  6664. * the get_queued() function which adds it to the hashtable on
  6665. * cgpu->queued_work. */
  6666. static void fill_queue(struct thr_info *mythr, struct cgpu_info *cgpu, struct device_drv *drv, const int thr_id)
  6667. {
  6668. do {
  6669. bool need_work;
  6670. /* Do this lockless just to know if we need more unqueued work. */
  6671. need_work = (!cgpu->unqueued_work);
  6672. /* get_work is a blocking function so do it outside of lock
  6673. * to prevent deadlocks with other locks. */
  6674. if (need_work) {
  6675. struct work *work = get_work(mythr, thr_id);
  6676. wr_lock(&cgpu->qlock);
  6677. /* Check we haven't grabbed work somehow between
  6678. * checking and picking up the lock. */
  6679. if (likely(!cgpu->unqueued_work))
  6680. cgpu->unqueued_work = work;
  6681. else
  6682. need_work = false;
  6683. wr_unlock(&cgpu->qlock);
  6684. if (unlikely(!need_work))
  6685. discard_work(work);
  6686. }
  6687. /* The queue_full function should be used by the driver to
  6688. * actually place work items on the physical device if it
  6689. * does have a queue. */
  6690. } while (!drv->queue_full(cgpu));
  6691. }
  6692. /* Add a work item to a cgpu's queued hashlist */
  6693. void __add_queued(struct cgpu_info *cgpu, struct work *work)
  6694. {
  6695. cgpu->queued_count++;
  6696. HASH_ADD_INT(cgpu->queued_work, id, work);
  6697. }
  6698. struct work *__get_queued(struct cgpu_info *cgpu)
  6699. {
  6700. struct work *work = NULL;
  6701. if (cgpu->unqueued_work) {
  6702. work = cgpu->unqueued_work;
  6703. if (unlikely(stale_work(work, false))) {
  6704. discard_work(work);
  6705. } else
  6706. __add_queued(cgpu, work);
  6707. cgpu->unqueued_work = NULL;
  6708. wake_gws();
  6709. }
  6710. return work;
  6711. }
  6712. /* This function is for retrieving one work item from the unqueued pointer and
  6713. * adding it to the hashtable of queued work. Code using this function must be
  6714. * able to handle NULL as a return which implies there is no work available. */
  6715. struct work *get_queued(struct cgpu_info *cgpu)
  6716. {
  6717. struct work *work;
  6718. wr_lock(&cgpu->qlock);
  6719. work = __get_queued(cgpu);
  6720. wr_unlock(&cgpu->qlock);
  6721. return work;
  6722. }
  6723. void add_queued(struct cgpu_info *cgpu, struct work *work)
  6724. {
  6725. wr_lock(&cgpu->qlock);
  6726. __add_queued(cgpu, work);
  6727. wr_unlock(&cgpu->qlock);
  6728. }
  6729. /* Get fresh work and add it to cgpu's queued hashlist */
  6730. struct work *get_queue_work(struct thr_info *thr, struct cgpu_info *cgpu, int thr_id)
  6731. {
  6732. struct work *work = get_work(thr, thr_id);
  6733. add_queued(cgpu, work);
  6734. return work;
  6735. }
  6736. /* This function is for finding an already queued work item in the
  6737. * given que hashtable. Code using this function must be able
  6738. * to handle NULL as a return which implies there is no matching work.
  6739. * The calling function must lock access to the que if it is required.
  6740. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6741. struct work *__find_work_bymidstate(struct work *que, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6742. {
  6743. struct work *work, *tmp, *ret = NULL;
  6744. HASH_ITER(hh, que, work, tmp) {
  6745. if (memcmp(work->midstate, midstate, midstatelen) == 0 &&
  6746. memcmp(work->data + offset, data, datalen) == 0) {
  6747. ret = work;
  6748. break;
  6749. }
  6750. }
  6751. return ret;
  6752. }
  6753. /* This function is for finding an already queued work item in the
  6754. * device's queued_work hashtable. Code using this function must be able
  6755. * to handle NULL as a return which implies there is no matching work.
  6756. * The common values for midstatelen, offset, datalen are 32, 64, 12 */
  6757. struct work *find_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6758. {
  6759. struct work *ret;
  6760. rd_lock(&cgpu->qlock);
  6761. ret = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6762. rd_unlock(&cgpu->qlock);
  6763. return ret;
  6764. }
  6765. struct work *clone_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6766. {
  6767. struct work *work, *ret = NULL;
  6768. rd_lock(&cgpu->qlock);
  6769. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6770. if (work)
  6771. ret = copy_work(work);
  6772. rd_unlock(&cgpu->qlock);
  6773. return ret;
  6774. }
  6775. /* This function is for finding an already queued work item in the
  6776. * given que hashtable. Code using this function must be able
  6777. * to handle NULL as a return which implies there is no matching work.
  6778. * The calling function must lock access to the que if it is required. */
  6779. struct work *__find_work_byid(struct work *que, uint32_t id)
  6780. {
  6781. struct work *work, *tmp, *ret = NULL;
  6782. HASH_ITER(hh, que, work, tmp) {
  6783. if (work->id == id) {
  6784. ret = work;
  6785. break;
  6786. }
  6787. }
  6788. return ret;
  6789. }
  6790. struct work *find_queued_work_byid(struct cgpu_info *cgpu, uint32_t id)
  6791. {
  6792. struct work *ret;
  6793. rd_lock(&cgpu->qlock);
  6794. ret = __find_work_byid(cgpu->queued_work, id);
  6795. rd_unlock(&cgpu->qlock);
  6796. return ret;
  6797. }
  6798. void __work_completed(struct cgpu_info *cgpu, struct work *work)
  6799. {
  6800. cgpu->queued_count--;
  6801. HASH_DEL(cgpu->queued_work, work);
  6802. }
  6803. /* This iterates over a queued hashlist finding work started more than secs
  6804. * seconds ago and discards the work as completed. The driver must set the
  6805. * work->tv_work_start value appropriately. Returns the number of items aged. */
  6806. int age_queued_work(struct cgpu_info *cgpu, double secs)
  6807. {
  6808. struct work *work, *tmp;
  6809. struct timeval tv_now;
  6810. int aged = 0;
  6811. cgtime(&tv_now);
  6812. wr_lock(&cgpu->qlock);
  6813. HASH_ITER(hh, cgpu->queued_work, work, tmp) {
  6814. if (tdiff(&tv_now, &work->tv_work_start) > secs) {
  6815. __work_completed(cgpu, work);
  6816. free_work(work);
  6817. aged++;
  6818. }
  6819. }
  6820. wr_unlock(&cgpu->qlock);
  6821. return aged;
  6822. }
  6823. /* This function should be used by queued device drivers when they're sure
  6824. * the work struct is no longer in use. */
  6825. void work_completed(struct cgpu_info *cgpu, struct work *work)
  6826. {
  6827. wr_lock(&cgpu->qlock);
  6828. __work_completed(cgpu, work);
  6829. wr_unlock(&cgpu->qlock);
  6830. free_work(work);
  6831. }
  6832. /* Combines find_queued_work_bymidstate and work_completed in one function
  6833. * withOUT destroying the work so the driver must free it. */
  6834. struct work *take_queued_work_bymidstate(struct cgpu_info *cgpu, char *midstate, size_t midstatelen, char *data, int offset, size_t datalen)
  6835. {
  6836. struct work *work;
  6837. wr_lock(&cgpu->qlock);
  6838. work = __find_work_bymidstate(cgpu->queued_work, midstate, midstatelen, data, offset, datalen);
  6839. if (work)
  6840. __work_completed(cgpu, work);
  6841. wr_unlock(&cgpu->qlock);
  6842. return work;
  6843. }
  6844. void flush_queue(struct cgpu_info *cgpu)
  6845. {
  6846. struct work *work = NULL;
  6847. if (unlikely(!cgpu))
  6848. return;
  6849. /* Use only a trylock in case we get into a deadlock with a queueing
  6850. * function holding the read lock when we're called. */
  6851. if (wr_trylock(&cgpu->qlock))
  6852. return;
  6853. work = cgpu->unqueued_work;
  6854. cgpu->unqueued_work = NULL;
  6855. wr_unlock(&cgpu->qlock);
  6856. if (work) {
  6857. free_work(work);
  6858. applog(LOG_DEBUG, "Discarded queued work item");
  6859. }
  6860. }
  6861. /* This version of hash work is for devices that are fast enough to always
  6862. * perform a full nonce range and need a queue to maintain the device busy.
  6863. * Work creation and destruction is not done from within this function
  6864. * directly. */
  6865. void hash_queued_work(struct thr_info *mythr)
  6866. {
  6867. struct timeval tv_start = {0, 0}, tv_end;
  6868. struct cgpu_info *cgpu = mythr->cgpu;
  6869. struct device_drv *drv = cgpu->drv;
  6870. const int thr_id = mythr->id;
  6871. int64_t hashes_done = 0;
  6872. while (likely(!cgpu->shutdown)) {
  6873. struct timeval diff;
  6874. int64_t hashes;
  6875. mythr->work_update = false;
  6876. fill_queue(mythr, cgpu, drv, thr_id);
  6877. hashes = drv->scanwork(mythr);
  6878. /* Reset the bool here in case the driver looks for it
  6879. * synchronously in the scanwork loop. */
  6880. mythr->work_restart = false;
  6881. if (unlikely(hashes == -1 )) {
  6882. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6883. cgpu->deven = DEV_DISABLED;
  6884. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6885. break;
  6886. }
  6887. hashes_done += hashes;
  6888. cgtime(&tv_end);
  6889. timersub(&tv_end, &tv_start, &diff);
  6890. /* Update the hashmeter at most 5 times per second */
  6891. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6892. diff.tv_sec >= opt_log_interval) {
  6893. hashmeter(thr_id, hashes_done);
  6894. hashes_done = 0;
  6895. copy_time(&tv_start, &tv_end);
  6896. }
  6897. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6898. mt_disable(mythr, thr_id, drv);
  6899. if (mythr->work_update)
  6900. drv->update_work(cgpu);
  6901. }
  6902. cgpu->deven = DEV_DISABLED;
  6903. }
  6904. /* This version of hash_work is for devices drivers that want to do their own
  6905. * work management entirely, usually by using get_work(). Note that get_work
  6906. * is a blocking function and will wait indefinitely if no work is available
  6907. * so this must be taken into consideration in the driver. */
  6908. void hash_driver_work(struct thr_info *mythr)
  6909. {
  6910. struct timeval tv_start = {0, 0}, tv_end;
  6911. struct cgpu_info *cgpu = mythr->cgpu;
  6912. struct device_drv *drv = cgpu->drv;
  6913. const int thr_id = mythr->id;
  6914. int64_t hashes_done = 0;
  6915. while (likely(!cgpu->shutdown)) {
  6916. struct timeval diff;
  6917. int64_t hashes;
  6918. mythr->work_update = false;
  6919. hashes = drv->scanwork(mythr);
  6920. /* Reset the bool here in case the driver looks for it
  6921. * synchronously in the scanwork loop. */
  6922. mythr->work_restart = false;
  6923. if (unlikely(hashes == -1 )) {
  6924. applog(LOG_ERR, "%s %d failure, disabling!", drv->name, cgpu->device_id);
  6925. cgpu->deven = DEV_DISABLED;
  6926. dev_error(cgpu, REASON_THREAD_ZERO_HASH);
  6927. break;
  6928. }
  6929. hashes_done += hashes;
  6930. cgtime(&tv_end);
  6931. timersub(&tv_end, &tv_start, &diff);
  6932. /* Update the hashmeter at most 5 times per second */
  6933. if ((hashes_done && (diff.tv_sec > 0 || diff.tv_usec > 200000)) ||
  6934. diff.tv_sec >= opt_log_interval) {
  6935. hashmeter(thr_id, hashes_done);
  6936. hashes_done = 0;
  6937. copy_time(&tv_start, &tv_end);
  6938. }
  6939. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  6940. mt_disable(mythr, thr_id, drv);
  6941. if (mythr->work_update)
  6942. drv->update_work(cgpu);
  6943. }
  6944. cgpu->deven = DEV_DISABLED;
  6945. }
  6946. void *miner_thread(void *userdata)
  6947. {
  6948. struct thr_info *mythr = userdata;
  6949. const int thr_id = mythr->id;
  6950. struct cgpu_info *cgpu = mythr->cgpu;
  6951. struct device_drv *drv = cgpu->drv;
  6952. char threadname[16];
  6953. snprintf(threadname, sizeof(threadname), "%d/Miner", thr_id);
  6954. RenameThread(threadname);
  6955. thread_reportout(mythr);
  6956. if (!drv->thread_init(mythr)) {
  6957. dev_error(cgpu, REASON_THREAD_FAIL_INIT);
  6958. goto out;
  6959. }
  6960. applog(LOG_DEBUG, "Waiting on sem in miner thread");
  6961. cgsem_wait(&mythr->sem);
  6962. cgpu->last_device_valid_work = time(NULL);
  6963. drv->hash_work(mythr);
  6964. drv->thread_shutdown(mythr);
  6965. out:
  6966. return NULL;
  6967. }
  6968. enum {
  6969. STAT_SLEEP_INTERVAL = 1,
  6970. STAT_CTR_INTERVAL = 10000000,
  6971. FAILURE_INTERVAL = 30,
  6972. };
  6973. #ifdef HAVE_LIBCURL
  6974. /* Stage another work item from the work returned in a longpoll */
  6975. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  6976. {
  6977. struct work *work;
  6978. bool rc;
  6979. work = make_work();
  6980. rc = work_decode(pool, work, val);
  6981. if (unlikely(!rc)) {
  6982. applog(LOG_ERR, "Could not convert longpoll data to work");
  6983. free_work(work);
  6984. return;
  6985. }
  6986. total_getworks++;
  6987. pool->getwork_requested++;
  6988. work->pool = pool;
  6989. work->rolltime = rolltime;
  6990. copy_time(&work->tv_getwork, tv_lp);
  6991. copy_time(&work->tv_getwork_reply, tv_lp_reply);
  6992. calc_diff(work, 0);
  6993. if (pool->enabled == POOL_REJECTING)
  6994. work->mandatory = true;
  6995. if (pool->has_gbt)
  6996. gen_gbt_work(pool, work);
  6997. work->longpoll = true;
  6998. work->getwork_mode = GETWORK_MODE_LP;
  6999. /* We'll be checking this work item twice, but we already know it's
  7000. * from a new block so explicitly force the new block detection now
  7001. * rather than waiting for it to hit the stage thread. This also
  7002. * allows testwork to know whether LP discovered the block or not. */
  7003. test_work_current(work);
  7004. /* Don't use backup LPs as work if we have failover-only enabled. Use
  7005. * the longpoll work from a pool that has been rejecting shares as a
  7006. * way to detect when the pool has recovered.
  7007. */
  7008. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  7009. free_work(work);
  7010. return;
  7011. }
  7012. work = clone_work(work);
  7013. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  7014. stage_work(work);
  7015. applog(LOG_DEBUG, "Converted longpoll data to work");
  7016. }
  7017. /* If we want longpoll, enable it for the chosen default pool, or, if
  7018. * the pool does not support longpoll, find the first one that does
  7019. * and use its longpoll support */
  7020. static struct pool *select_longpoll_pool(struct pool *cp)
  7021. {
  7022. int i;
  7023. if (cp->hdr_path || cp->has_gbt || cp->gbt_solo)
  7024. return cp;
  7025. for (i = 0; i < total_pools; i++) {
  7026. struct pool *pool = pools[i];
  7027. if (pool->has_stratum || pool->hdr_path)
  7028. return pool;
  7029. }
  7030. return NULL;
  7031. }
  7032. #endif /* HAVE_LIBCURL */
  7033. /* This will make the longpoll thread wait till it's the current pool, or it
  7034. * has been flagged as rejecting, before attempting to open any connections.
  7035. */
  7036. static void wait_lpcurrent(struct pool *pool)
  7037. {
  7038. while (!cnx_needed(pool) && (pool->enabled == POOL_DISABLED ||
  7039. (pool != current_pool() && pool_strategy != POOL_LOADBALANCE &&
  7040. pool_strategy != POOL_BALANCE))) {
  7041. mutex_lock(&lp_lock);
  7042. pthread_cond_wait(&lp_cond, &lp_lock);
  7043. mutex_unlock(&lp_lock);
  7044. }
  7045. }
  7046. #ifdef HAVE_LIBCURL
  7047. static void *longpoll_thread(void *userdata)
  7048. {
  7049. struct pool *cp = (struct pool *)userdata;
  7050. /* This *pool is the source of the actual longpoll, not the pool we've
  7051. * tied it to */
  7052. struct timeval start, reply, end;
  7053. struct pool *pool = NULL;
  7054. char threadname[16];
  7055. CURL *curl = NULL;
  7056. int failures = 0;
  7057. char lpreq[1024];
  7058. char *lp_url;
  7059. int rolltime;
  7060. snprintf(threadname, sizeof(threadname), "%d/Longpoll", cp->pool_no);
  7061. RenameThread(threadname);
  7062. retry_pool:
  7063. pool = select_longpoll_pool(cp);
  7064. if (!pool) {
  7065. applog(LOG_WARNING, "No suitable long-poll found for %s", cp->rpc_url);
  7066. while (!pool) {
  7067. cgsleep_ms(60000);
  7068. pool = select_longpoll_pool(cp);
  7069. }
  7070. }
  7071. if (pool->has_stratum) {
  7072. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7073. cp->rpc_url, pool->rpc_url);
  7074. goto out;
  7075. }
  7076. if (pool->gbt_solo) {
  7077. applog(LOG_WARNING, "Block change for %s detection via getblockcount polling",
  7078. cp->rpc_url);
  7079. while (42) {
  7080. json_t *val, *res_val = NULL;
  7081. if (unlikely(pool->removed))
  7082. return NULL;
  7083. cgtime(&start);
  7084. wait_lpcurrent(cp);
  7085. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockcount\"}\n");
  7086. /* We will be making another call immediately after this
  7087. * one to get the height so allow this curl to be reused.*/
  7088. get_gbt_curl(pool, 500);
  7089. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 0);
  7090. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass, lpreq, true,
  7091. false, &rolltime, pool, false);
  7092. release_gbt_curl(pool);
  7093. if (likely(val))
  7094. res_val = json_object_get(val, "result");
  7095. if (likely(res_val)) {
  7096. int height = json_integer_value(res_val);
  7097. const char *prev_hash;
  7098. failures = 0;
  7099. json_decref(val);
  7100. if (height >= cp->height) {
  7101. applog(LOG_WARNING, "Block height change to %d detected on pool %d",
  7102. height, cp->pool_no);
  7103. update_gbt_solo(pool);
  7104. continue;
  7105. }
  7106. sprintf(lpreq, "{\"id\": 0, \"method\": \"getblockhash\", \"params\": [%d]}\n", height);
  7107. get_gbt_curl(pool, 500);
  7108. curl_easy_setopt(pool->gbt_curl, CURLOPT_FORBID_REUSE, 1);
  7109. val = json_rpc_call(pool->gbt_curl, pool->rpc_url, pool->rpc_userpass,
  7110. lpreq, true, false, &rolltime, pool, false);
  7111. release_gbt_curl(pool);
  7112. if (val) {
  7113. /* Do a comparison on a short stretch of
  7114. * the hash to make sure it hasn't changed
  7115. * due to mining on an orphan branch. */
  7116. prev_hash = json_string_value(json_object_get(val, "result"));
  7117. if (unlikely(prev_hash && strncasecmp(prev_hash + 56, pool->prev_hash, 8))) {
  7118. applog(LOG_WARNING, "Mining on orphan branch detected, switching!");
  7119. update_gbt_solo(pool);
  7120. }
  7121. json_decref(val);
  7122. }
  7123. cgsleep_ms(500);
  7124. } else {
  7125. if (val)
  7126. json_decref(val);
  7127. cgtime(&end);
  7128. if (end.tv_sec - start.tv_sec > 30)
  7129. continue;
  7130. if (failures == 1)
  7131. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7132. cgsleep_ms(30000);
  7133. }
  7134. }
  7135. }
  7136. curl = curl_easy_init();
  7137. if (unlikely(!curl))
  7138. quit (1, "Longpoll CURL initialisation failed");
  7139. /* Any longpoll from any pool is enough for this to be true */
  7140. have_longpoll = true;
  7141. wait_lpcurrent(cp);
  7142. if (pool->has_gbt) {
  7143. lp_url = pool->rpc_url;
  7144. applog(LOG_WARNING, "GBT longpoll ID activated for %s", lp_url);
  7145. } else {
  7146. strcpy(lpreq, getwork_req);
  7147. lp_url = pool->lp_url;
  7148. if (cp == pool)
  7149. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  7150. else
  7151. applog(LOG_WARNING, "Long-polling activated for %s via %s", cp->rpc_url, lp_url);
  7152. }
  7153. while (42) {
  7154. json_t *val, *soval;
  7155. wait_lpcurrent(cp);
  7156. cgtime(&start);
  7157. /* Update the longpollid every time, but do it under lock to
  7158. * avoid races */
  7159. if (pool->has_gbt) {
  7160. cg_rlock(&pool->gbt_lock);
  7161. snprintf(lpreq, sizeof(lpreq),
  7162. "{\"id\": 0, \"method\": \"getblocktemplate\", \"params\": "
  7163. "[{\"capabilities\": [\"coinbasetxn\", \"workid\", \"coinbase/append\"], "
  7164. "\"longpollid\": \"%s\"}]}\n", pool->longpollid);
  7165. cg_runlock(&pool->gbt_lock);
  7166. }
  7167. /* Longpoll connections can be persistent for a very long time
  7168. * and any number of issues could have come up in the meantime
  7169. * so always establish a fresh connection instead of relying on
  7170. * a persistent one. */
  7171. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  7172. val = json_rpc_call(curl, lp_url, pool->rpc_userpass,
  7173. lpreq, false, true, &rolltime, pool, false);
  7174. cgtime(&reply);
  7175. if (likely(val)) {
  7176. soval = json_object_get(json_object_get(val, "result"), "submitold");
  7177. if (soval)
  7178. pool->submit_old = json_is_true(soval);
  7179. else
  7180. pool->submit_old = false;
  7181. convert_to_work(val, rolltime, pool, &start, &reply);
  7182. failures = 0;
  7183. json_decref(val);
  7184. } else {
  7185. /* Some pools regularly drop the longpoll request so
  7186. * only see this as longpoll failure if it happens
  7187. * immediately and just restart it the rest of the
  7188. * time. */
  7189. cgtime(&end);
  7190. if (end.tv_sec - start.tv_sec > 30)
  7191. continue;
  7192. if (failures == 1)
  7193. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", lp_url);
  7194. cgsleep_ms(30000);
  7195. }
  7196. if (pool != cp) {
  7197. pool = select_longpoll_pool(cp);
  7198. if (pool->has_stratum) {
  7199. applog(LOG_WARNING, "Block change for %s detection via %s stratum",
  7200. cp->rpc_url, pool->rpc_url);
  7201. break;
  7202. }
  7203. if (unlikely(!pool))
  7204. goto retry_pool;
  7205. }
  7206. if (unlikely(pool->removed))
  7207. break;
  7208. }
  7209. out:
  7210. curl_easy_cleanup(curl);
  7211. return NULL;
  7212. }
  7213. #else /* HAVE_LIBCURL */
  7214. static void *longpoll_thread(void __maybe_unused *userdata)
  7215. {
  7216. pthread_detach(pthread_self());
  7217. return NULL;
  7218. }
  7219. #endif /* HAVE_LIBCURL */
  7220. void reinit_device(struct cgpu_info *cgpu)
  7221. {
  7222. if (cgpu->deven == DEV_DISABLED)
  7223. return;
  7224. #ifdef USE_USBUTILS
  7225. /* Attempt a usb device reset if the device has gone sick */
  7226. if (cgpu->usbdev && cgpu->usbdev->handle)
  7227. libusb_reset_device(cgpu->usbdev->handle);
  7228. #endif
  7229. cgpu->drv->reinit_device(cgpu);
  7230. }
  7231. static struct timeval rotate_tv;
  7232. /* We reap curls if they are unused for over a minute */
  7233. static void reap_curl(struct pool *pool)
  7234. {
  7235. struct curl_ent *ent, *iter;
  7236. struct timeval now;
  7237. int reaped = 0;
  7238. cgtime(&now);
  7239. mutex_lock(&pool->pool_lock);
  7240. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  7241. if (pool->curls < 2)
  7242. break;
  7243. if (now.tv_sec - ent->tv.tv_sec > 300) {
  7244. reaped++;
  7245. pool->curls--;
  7246. list_del(&ent->node);
  7247. curl_easy_cleanup(ent->curl);
  7248. free(ent);
  7249. }
  7250. }
  7251. mutex_unlock(&pool->pool_lock);
  7252. if (reaped)
  7253. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  7254. }
  7255. /* Prune old shares we haven't had a response about for over 2 minutes in case
  7256. * the pool never plans to respond and we're just leaking memory. If we get a
  7257. * response beyond that time they will be seen as untracked shares. */
  7258. static void prune_stratum_shares(struct pool *pool)
  7259. {
  7260. struct stratum_share *sshare, *tmpshare;
  7261. time_t current_time = time(NULL);
  7262. int cleared = 0;
  7263. mutex_lock(&sshare_lock);
  7264. HASH_ITER(hh, stratum_shares, sshare, tmpshare) {
  7265. if (sshare->work->pool == pool && current_time > sshare->sshare_time + 120) {
  7266. HASH_DEL(stratum_shares, sshare);
  7267. free_work(sshare->work);
  7268. free(sshare);
  7269. cleared++;
  7270. }
  7271. }
  7272. mutex_unlock(&sshare_lock);
  7273. if (cleared) {
  7274. applog(LOG_WARNING, "Lost %d shares due to no stratum share response from pool %d",
  7275. cleared, pool->pool_no);
  7276. pool->stale_shares += cleared;
  7277. total_stale += cleared;
  7278. }
  7279. }
  7280. static void *watchpool_thread(void __maybe_unused *userdata)
  7281. {
  7282. int intervals = 0;
  7283. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7284. RenameThread("Watchpool");
  7285. set_lowprio();
  7286. while (42) {
  7287. struct timeval now;
  7288. int i;
  7289. if (++intervals > 20)
  7290. intervals = 0;
  7291. cgtime(&now);
  7292. for (i = 0; i < total_pools; i++) {
  7293. struct pool *pool = pools[i];
  7294. if (!opt_benchmark && !opt_benchfile) {
  7295. reap_curl(pool);
  7296. prune_stratum_shares(pool);
  7297. }
  7298. /* Get a rolling utility per pool over 10 mins */
  7299. if (intervals > 19) {
  7300. double shares = pool->diff1 - pool->last_shares;
  7301. pool->last_shares = pool->diff1;
  7302. pool->utility = (pool->utility + shares * 0.63) / 1.63;
  7303. pool->shares = pool->utility;
  7304. }
  7305. if (pool->enabled == POOL_DISABLED)
  7306. continue;
  7307. /* Don't start testing a pool if its test thread
  7308. * from startup is still doing its first attempt. */
  7309. if (unlikely(pool->testing))
  7310. continue;
  7311. /* Test pool is idle once every minute */
  7312. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 30) {
  7313. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  7314. pool_resus(pool);
  7315. else
  7316. cgtime(&pool->tv_idle);
  7317. }
  7318. /* Only switch pools if the failback pool has been
  7319. * alive for more than 5 minutes to prevent
  7320. * intermittently failing pools from being used. */
  7321. if (!pool->idle && pool_strategy == POOL_FAILOVER && pool->prio < cp_prio() &&
  7322. now.tv_sec - pool->tv_idle.tv_sec > 300) {
  7323. applog(LOG_WARNING, "Pool %d %s stable for 5 mins",
  7324. pool->pool_no, pool->rpc_url);
  7325. switch_pools(NULL);
  7326. }
  7327. }
  7328. if (current_pool()->idle)
  7329. switch_pools(NULL);
  7330. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  7331. cgtime(&rotate_tv);
  7332. switch_pools(NULL);
  7333. }
  7334. cgsleep_ms(30000);
  7335. }
  7336. return NULL;
  7337. }
  7338. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  7339. * the screen at regular intervals, and restarts threads if they appear to have
  7340. * died. */
  7341. #define WATCHDOG_INTERVAL 2
  7342. #define WATCHDOG_SICK_TIME 120
  7343. #define WATCHDOG_DEAD_TIME 600
  7344. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  7345. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  7346. static void *watchdog_thread(void __maybe_unused *userdata)
  7347. {
  7348. const unsigned int interval = WATCHDOG_INTERVAL;
  7349. struct timeval zero_tv;
  7350. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7351. RenameThread("Watchdog");
  7352. set_lowprio();
  7353. memset(&zero_tv, 0, sizeof(struct timeval));
  7354. cgtime(&rotate_tv);
  7355. while (1) {
  7356. int i;
  7357. struct timeval now;
  7358. sleep(interval);
  7359. discard_stale();
  7360. hashmeter(-1, 0);
  7361. #ifdef HAVE_CURSES
  7362. if (curses_active_locked()) {
  7363. struct cgpu_info *cgpu;
  7364. int count;
  7365. change_logwinsize();
  7366. curses_print_status();
  7367. count = 0;
  7368. for (i = 0; i < total_devices; i++) {
  7369. cgpu = get_devices(i);
  7370. #ifndef USE_USBUTILS
  7371. if (cgpu)
  7372. #else
  7373. if (cgpu && !cgpu->usbinfo.nodev)
  7374. #endif
  7375. curses_print_devstatus(cgpu, i, count++);
  7376. }
  7377. #ifdef USE_USBUTILS
  7378. for (i = 0; i < total_devices; i++) {
  7379. cgpu = get_devices(i);
  7380. if (cgpu && cgpu->usbinfo.nodev)
  7381. curses_print_devstatus(cgpu, i, count++);
  7382. }
  7383. #endif
  7384. touchwin(statuswin);
  7385. wrefresh(statuswin);
  7386. touchwin(logwin);
  7387. wrefresh(logwin);
  7388. unlock_curses();
  7389. }
  7390. #endif
  7391. cgtime(&now);
  7392. if (!sched_paused && !should_run()) {
  7393. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  7394. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7395. if (!schedstart.enable) {
  7396. quit(0, "Terminating execution as planned");
  7397. break;
  7398. }
  7399. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  7400. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7401. sched_paused = true;
  7402. rd_lock(&mining_thr_lock);
  7403. for (i = 0; i < mining_threads; i++)
  7404. mining_thr[i]->pause = true;
  7405. rd_unlock(&mining_thr_lock);
  7406. } else if (sched_paused && should_run()) {
  7407. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  7408. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  7409. if (schedstop.enable)
  7410. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  7411. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  7412. sched_paused = false;
  7413. for (i = 0; i < mining_threads; i++) {
  7414. struct thr_info *thr;
  7415. thr = get_thread(i);
  7416. /* Don't touch disabled devices */
  7417. if (thr->cgpu->deven == DEV_DISABLED)
  7418. continue;
  7419. thr->pause = false;
  7420. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  7421. cgsem_post(&thr->sem);
  7422. }
  7423. }
  7424. for (i = 0; i < total_devices; ++i) {
  7425. struct cgpu_info *cgpu = get_devices(i);
  7426. struct thr_info *thr = cgpu->thr[0];
  7427. enum dev_enable *denable;
  7428. char dev_str[8];
  7429. int gpu;
  7430. if (!thr)
  7431. continue;
  7432. cgpu->drv->get_stats(cgpu);
  7433. gpu = cgpu->device_id;
  7434. denable = &cgpu->deven;
  7435. snprintf(dev_str, sizeof(dev_str), "%s%d", cgpu->drv->name, gpu);
  7436. /* Thread is waiting on getwork or disabled */
  7437. if (thr->getwork || *denable == DEV_DISABLED)
  7438. continue;
  7439. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  7440. if (cgpu->status != LIFE_INIT)
  7441. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  7442. cgpu->status = LIFE_WELL;
  7443. cgpu->device_last_well = time(NULL);
  7444. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  7445. cgpu->rolling = 0;
  7446. cgpu->status = LIFE_SICK;
  7447. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  7448. cgtime(&thr->sick);
  7449. dev_error(cgpu, REASON_DEV_SICK_IDLE_60);
  7450. if (opt_restart) {
  7451. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  7452. reinit_device(cgpu);
  7453. }
  7454. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  7455. cgpu->status = LIFE_DEAD;
  7456. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  7457. cgtime(&thr->sick);
  7458. dev_error(cgpu, REASON_DEV_DEAD_IDLE_600);
  7459. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  7460. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  7461. /* Attempt to restart a GPU that's sick or dead once every minute */
  7462. cgtime(&thr->sick);
  7463. if (opt_restart)
  7464. reinit_device(cgpu);
  7465. }
  7466. }
  7467. }
  7468. return NULL;
  7469. }
  7470. static void log_print_status(struct cgpu_info *cgpu)
  7471. {
  7472. char logline[255];
  7473. get_statline(logline, sizeof(logline), cgpu);
  7474. applog(LOG_WARNING, "%s", logline);
  7475. }
  7476. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7477. void blank_get_statline_before(char *buf, size_t bufsiz, struct cgpu_info __maybe_unused *cgpu);
  7478. void print_summary(void)
  7479. {
  7480. struct timeval diff;
  7481. int hours, mins, secs, i;
  7482. double utility, displayed_hashes, work_util;
  7483. timersub(&total_tv_end, &total_tv_start, &diff);
  7484. hours = diff.tv_sec / 3600;
  7485. mins = (diff.tv_sec % 3600) / 60;
  7486. secs = diff.tv_sec % 60;
  7487. utility = total_accepted / total_secs * 60;
  7488. work_util = total_diff1 / total_secs * 60;
  7489. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  7490. applog(LOG_WARNING, "Started at %s", datestamp);
  7491. if (total_pools == 1)
  7492. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  7493. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  7494. displayed_hashes = total_mhashes_done / total_secs;
  7495. applog(LOG_WARNING, "Average hashrate: %.1f Mhash/s", displayed_hashes);
  7496. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  7497. applog(LOG_WARNING, "Best share difficulty: %s", best_share);
  7498. applog(LOG_WARNING, "Share submissions: %"PRId64, total_accepted + total_rejected);
  7499. applog(LOG_WARNING, "Accepted shares: %"PRId64, total_accepted);
  7500. applog(LOG_WARNING, "Rejected shares: %"PRId64, total_rejected);
  7501. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  7502. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  7503. if (total_accepted || total_rejected)
  7504. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  7505. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  7506. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  7507. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  7508. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %"PRId64, total_stale);
  7509. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  7510. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  7511. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  7512. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  7513. if (total_pools > 1) {
  7514. for (i = 0; i < total_pools; i++) {
  7515. struct pool *pool = pools[i];
  7516. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  7517. if (pool->solved)
  7518. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  7519. applog(LOG_WARNING, " Share submissions: %"PRId64, pool->accepted + pool->rejected);
  7520. applog(LOG_WARNING, " Accepted shares: %"PRId64, pool->accepted);
  7521. applog(LOG_WARNING, " Rejected shares: %"PRId64, pool->rejected);
  7522. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  7523. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  7524. if (pool->accepted || pool->rejected)
  7525. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  7526. applog(LOG_WARNING, " Items worked on: %d", pool->works);
  7527. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  7528. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  7529. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  7530. }
  7531. }
  7532. applog(LOG_WARNING, "Summary of per device statistics:\n");
  7533. for (i = 0; i < total_devices; ++i) {
  7534. struct cgpu_info *cgpu = get_devices(i);
  7535. cgpu->drv->get_statline_before = &blank_get_statline_before;
  7536. cgpu->drv->get_statline = &noop_get_statline;
  7537. log_print_status(cgpu);
  7538. }
  7539. if (opt_shares) {
  7540. applog(LOG_WARNING, "Mined %.0f accepted shares of %d requested\n", total_diff_accepted, opt_shares);
  7541. if (opt_shares > total_diff_accepted)
  7542. applog(LOG_WARNING, "WARNING - Mined only %.0f shares of %d requested.", total_diff_accepted, opt_shares);
  7543. }
  7544. applog(LOG_WARNING, " ");
  7545. fflush(stderr);
  7546. fflush(stdout);
  7547. }
  7548. static void clean_up(bool restarting)
  7549. {
  7550. #ifdef USE_USBUTILS
  7551. usb_polling = false;
  7552. pthread_join(usb_poll_thread, NULL);
  7553. libusb_exit(NULL);
  7554. #endif
  7555. cgtime(&total_tv_end);
  7556. #ifdef WIN32
  7557. timeEndPeriod(1);
  7558. #endif
  7559. #ifdef HAVE_CURSES
  7560. disable_curses();
  7561. #endif
  7562. if (!restarting && !opt_realquiet && successful_connect)
  7563. print_summary();
  7564. curl_global_cleanup();
  7565. }
  7566. /* Should all else fail and we're unable to clean up threads due to locking
  7567. * issues etc, just silently exit. */
  7568. static void *killall_thread(void __maybe_unused *arg)
  7569. {
  7570. pthread_detach(pthread_self());
  7571. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  7572. sleep(5);
  7573. exit(1);
  7574. return NULL;
  7575. }
  7576. void __quit(int status, bool clean)
  7577. {
  7578. pthread_t killall_t;
  7579. if (unlikely(pthread_create(&killall_t, NULL, killall_thread, NULL)))
  7580. exit(1);
  7581. if (clean)
  7582. clean_up(false);
  7583. #ifdef HAVE_CURSES
  7584. else
  7585. disable_curses();
  7586. #endif
  7587. #if defined(unix) || defined(__APPLE__)
  7588. if (forkpid > 0) {
  7589. kill(forkpid, SIGTERM);
  7590. forkpid = 0;
  7591. }
  7592. #endif
  7593. pthread_cancel(killall_t);
  7594. exit(status);
  7595. }
  7596. void _quit(int status)
  7597. {
  7598. __quit(status, true);
  7599. }
  7600. #ifdef HAVE_CURSES
  7601. char *curses_input(const char *query)
  7602. {
  7603. char *input;
  7604. echo();
  7605. input = malloc(255);
  7606. if (!input)
  7607. quit(1, "Failed to malloc input");
  7608. leaveok(logwin, false);
  7609. wlogprint("%s:\n", query);
  7610. wgetnstr(logwin, input, 255);
  7611. if (!strlen(input))
  7612. strcpy(input, "-1");
  7613. leaveok(logwin, true);
  7614. noecho();
  7615. return input;
  7616. }
  7617. #endif
  7618. static bool pools_active = false;
  7619. static void *test_pool_thread(void *arg)
  7620. {
  7621. struct pool *pool = (struct pool *)arg;
  7622. if (!pool->blocking)
  7623. pthread_detach(pthread_self());
  7624. retry:
  7625. if (pool_active(pool, false)) {
  7626. pool_tset(pool, &pool->lagging);
  7627. pool_tclear(pool, &pool->idle);
  7628. bool first_pool = false;
  7629. cg_wlock(&control_lock);
  7630. if (!pools_active) {
  7631. currentpool = pool;
  7632. if (pool->pool_no != 0)
  7633. first_pool = true;
  7634. pools_active = true;
  7635. }
  7636. cg_wunlock(&control_lock);
  7637. if (unlikely(first_pool))
  7638. applog(LOG_NOTICE, "Switching to pool %d %s - first alive pool", pool->pool_no, pool->rpc_url);
  7639. pool_resus(pool);
  7640. switch_pools(NULL);
  7641. } else {
  7642. pool_died(pool);
  7643. sleep(5);
  7644. goto retry;
  7645. }
  7646. pool->testing = false;
  7647. return NULL;
  7648. }
  7649. /* Always returns true that the pool details were added unless we are not
  7650. * live, implying this is the only pool being added, so if no pools are
  7651. * active it returns false. */
  7652. bool add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  7653. {
  7654. size_t siz;
  7655. url = get_proxy(url, pool);
  7656. pool->rpc_url = url;
  7657. pool->rpc_user = user;
  7658. pool->rpc_pass = pass;
  7659. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  7660. pool->rpc_userpass = malloc(siz);
  7661. if (!pool->rpc_userpass)
  7662. quit(1, "Failed to malloc userpass");
  7663. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  7664. pool->testing = true;
  7665. pool->idle = true;
  7666. pool->blocking = !live;
  7667. enable_pool(pool);
  7668. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  7669. if (!live) {
  7670. pthread_join(pool->test_thread, NULL);
  7671. return pools_active;
  7672. }
  7673. return true;
  7674. }
  7675. #ifdef HAVE_CURSES
  7676. static bool input_pool(bool live)
  7677. {
  7678. char *url = NULL, *user = NULL, *pass = NULL;
  7679. struct pool *pool;
  7680. bool ret = false;
  7681. immedok(logwin, true);
  7682. wlogprint("Input server details.\n");
  7683. url = curses_input("URL");
  7684. if (!strcmp(url, "-1"))
  7685. goto out;
  7686. user = curses_input("Username");
  7687. if (!strcmp(user, "-1"))
  7688. goto out;
  7689. pass = curses_input("Password");
  7690. if (!strcmp(pass, "-1")) {
  7691. free(pass);
  7692. pass = strdup("");
  7693. }
  7694. pool = add_pool();
  7695. if (!detect_stratum(pool, url) && strncmp(url, "http://", 7) &&
  7696. strncmp(url, "https://", 8)) {
  7697. char *httpinput;
  7698. httpinput = malloc(256);
  7699. if (!httpinput)
  7700. quit(1, "Failed to malloc httpinput");
  7701. strcpy(httpinput, "http://");
  7702. strncat(httpinput, url, 248);
  7703. free(url);
  7704. url = httpinput;
  7705. }
  7706. ret = add_pool_details(pool, live, url, user, pass);
  7707. out:
  7708. immedok(logwin, false);
  7709. if (!ret) {
  7710. free(url);
  7711. free(user);
  7712. free(pass);
  7713. }
  7714. return ret;
  7715. }
  7716. #endif
  7717. #if defined(unix) || defined(__APPLE__)
  7718. static void fork_monitor()
  7719. {
  7720. // Make a pipe: [readFD, writeFD]
  7721. int pfd[2];
  7722. int r = pipe(pfd);
  7723. if (r < 0) {
  7724. perror("pipe - failed to create pipe for --monitor");
  7725. exit(1);
  7726. }
  7727. // Make stderr write end of pipe
  7728. fflush(stderr);
  7729. r = dup2(pfd[1], 2);
  7730. if (r < 0) {
  7731. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  7732. exit(1);
  7733. }
  7734. r = close(pfd[1]);
  7735. if (r < 0) {
  7736. perror("close - failed to close write end of pipe for --monitor");
  7737. exit(1);
  7738. }
  7739. // Don't allow a dying monitor to kill the main process
  7740. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  7741. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  7742. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  7743. perror("signal - failed to edit signal mask for --monitor");
  7744. exit(1);
  7745. }
  7746. // Fork a child process
  7747. forkpid = fork();
  7748. if (forkpid < 0) {
  7749. perror("fork - failed to fork child process for --monitor");
  7750. exit(1);
  7751. }
  7752. // Child: launch monitor command
  7753. if (0 == forkpid) {
  7754. // Make stdin read end of pipe
  7755. r = dup2(pfd[0], 0);
  7756. if (r < 0) {
  7757. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  7758. exit(1);
  7759. }
  7760. close(pfd[0]);
  7761. if (r < 0) {
  7762. perror("close - in child, failed to close read end of pipe for --monitor");
  7763. exit(1);
  7764. }
  7765. // Launch user specified command
  7766. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  7767. perror("execl - in child failed to exec user specified command for --monitor");
  7768. exit(1);
  7769. }
  7770. // Parent: clean up unused fds and bail
  7771. r = close(pfd[0]);
  7772. if (r < 0) {
  7773. perror("close - failed to close read end of pipe for --monitor");
  7774. exit(1);
  7775. }
  7776. }
  7777. #endif // defined(unix)
  7778. #ifdef HAVE_CURSES
  7779. static void enable_curses_windows(void)
  7780. {
  7781. int x,y;
  7782. getmaxyx(mainwin, y, x);
  7783. statuswin = newwin(logstart, x, 0, 0);
  7784. leaveok(statuswin, true);
  7785. logwin = newwin(y - logcursor, 0, logcursor, 0);
  7786. idlok(logwin, true);
  7787. scrollok(logwin, true);
  7788. leaveok(logwin, true);
  7789. cbreak();
  7790. noecho();
  7791. }
  7792. void enable_curses(void) {
  7793. lock_curses();
  7794. if (curses_active) {
  7795. unlock_curses();
  7796. return;
  7797. }
  7798. mainwin = initscr();
  7799. enable_curses_windows();
  7800. curses_active = true;
  7801. statusy = logstart;
  7802. unlock_curses();
  7803. }
  7804. #endif
  7805. static int cgminer_id_count = 0;
  7806. /* Various noop functions for drivers that don't support or need their
  7807. * variants. */
  7808. static void noop_reinit_device(struct cgpu_info __maybe_unused *cgpu)
  7809. {
  7810. }
  7811. void blank_get_statline_before(char __maybe_unused *buf,size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7812. {
  7813. }
  7814. static void noop_get_statline(char __maybe_unused *buf, size_t __maybe_unused bufsiz, struct cgpu_info __maybe_unused *cgpu)
  7815. {
  7816. }
  7817. static bool noop_get_stats(struct cgpu_info __maybe_unused *cgpu)
  7818. {
  7819. return true;
  7820. }
  7821. static bool noop_thread_prepare(struct thr_info __maybe_unused *thr)
  7822. {
  7823. return true;
  7824. }
  7825. static uint64_t noop_can_limit_work(struct thr_info __maybe_unused *thr)
  7826. {
  7827. return 0xffffffff;
  7828. }
  7829. static bool noop_thread_init(struct thr_info __maybe_unused *thr)
  7830. {
  7831. return true;
  7832. }
  7833. static bool noop_prepare_work(struct thr_info __maybe_unused *thr, struct work __maybe_unused *work)
  7834. {
  7835. return true;
  7836. }
  7837. static void noop_hw_error(struct thr_info __maybe_unused *thr)
  7838. {
  7839. }
  7840. static void noop_thread_shutdown(struct thr_info __maybe_unused *thr)
  7841. {
  7842. }
  7843. static void noop_thread_enable(struct thr_info __maybe_unused *thr)
  7844. {
  7845. }
  7846. static void noop_detect(bool __maybe_unused hotplug)
  7847. {
  7848. }
  7849. static struct api_data *noop_get_api_stats(struct cgpu_info __maybe_unused *cgpu)
  7850. {
  7851. return NULL;
  7852. }
  7853. static void noop_hash_work(struct thr_info __maybe_unused *thr)
  7854. {
  7855. }
  7856. #define noop_flush_work noop_reinit_device
  7857. #define noop_update_work noop_reinit_device
  7858. #define noop_queue_full noop_get_stats
  7859. #define noop_zero_stats noop_reinit_device
  7860. #define noop_identify_device noop_reinit_device
  7861. /* Fill missing driver drv functions with noops */
  7862. void fill_device_drv(struct device_drv *drv)
  7863. {
  7864. if (!drv->drv_detect)
  7865. drv->drv_detect = &noop_detect;
  7866. if (!drv->reinit_device)
  7867. drv->reinit_device = &noop_reinit_device;
  7868. if (!drv->get_statline_before)
  7869. drv->get_statline_before = &blank_get_statline_before;
  7870. if (!drv->get_statline)
  7871. drv->get_statline = &noop_get_statline;
  7872. if (!drv->get_stats)
  7873. drv->get_stats = &noop_get_stats;
  7874. if (!drv->thread_prepare)
  7875. drv->thread_prepare = &noop_thread_prepare;
  7876. if (!drv->can_limit_work)
  7877. drv->can_limit_work = &noop_can_limit_work;
  7878. if (!drv->thread_init)
  7879. drv->thread_init = &noop_thread_init;
  7880. if (!drv->prepare_work)
  7881. drv->prepare_work = &noop_prepare_work;
  7882. if (!drv->hw_error)
  7883. drv->hw_error = &noop_hw_error;
  7884. if (!drv->thread_shutdown)
  7885. drv->thread_shutdown = &noop_thread_shutdown;
  7886. if (!drv->thread_enable)
  7887. drv->thread_enable = &noop_thread_enable;
  7888. if (!drv->hash_work)
  7889. drv->hash_work = &hash_sole_work;
  7890. if (!drv->flush_work)
  7891. drv->flush_work = &noop_flush_work;
  7892. if (!drv->update_work)
  7893. drv->update_work = &noop_update_work;
  7894. if (!drv->queue_full)
  7895. drv->queue_full = &noop_queue_full;
  7896. if (!drv->zero_stats)
  7897. drv->zero_stats = &noop_zero_stats;
  7898. /* If drivers support internal diff they should set a max_diff or
  7899. * we will assume they don't and set max to 1. */
  7900. if (!drv->max_diff)
  7901. drv->max_diff = 1;
  7902. }
  7903. void null_device_drv(struct device_drv *drv)
  7904. {
  7905. drv->drv_detect = &noop_detect;
  7906. drv->reinit_device = &noop_reinit_device;
  7907. drv->get_statline_before = &blank_get_statline_before;
  7908. drv->get_statline = &noop_get_statline;
  7909. drv->get_api_stats = &noop_get_api_stats;
  7910. drv->get_stats = &noop_get_stats;
  7911. drv->identify_device = &noop_identify_device;
  7912. drv->set_device = NULL;
  7913. drv->thread_prepare = &noop_thread_prepare;
  7914. drv->can_limit_work = &noop_can_limit_work;
  7915. drv->thread_init = &noop_thread_init;
  7916. drv->prepare_work = &noop_prepare_work;
  7917. /* This should make the miner thread just exit */
  7918. drv->hash_work = &noop_hash_work;
  7919. drv->hw_error = &noop_hw_error;
  7920. drv->thread_shutdown = &noop_thread_shutdown;
  7921. drv->thread_enable = &noop_thread_enable;
  7922. drv->zero_stats = &noop_zero_stats;
  7923. drv->hash_work = &noop_hash_work;
  7924. drv->queue_full = &noop_queue_full;
  7925. drv->flush_work = &noop_flush_work;
  7926. drv->update_work = &noop_update_work;
  7927. drv->zero_stats = &noop_zero_stats;
  7928. drv->max_diff = 1;
  7929. drv->min_diff = 1;
  7930. }
  7931. void enable_device(struct cgpu_info *cgpu)
  7932. {
  7933. cgpu->deven = DEV_ENABLED;
  7934. wr_lock(&devices_lock);
  7935. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  7936. wr_unlock(&devices_lock);
  7937. if (hotplug_mode)
  7938. new_threads += cgpu->threads;
  7939. else
  7940. mining_threads += cgpu->threads;
  7941. rwlock_init(&cgpu->qlock);
  7942. cgpu->queued_work = NULL;
  7943. }
  7944. struct _cgpu_devid_counter {
  7945. char name[4];
  7946. int lastid;
  7947. UT_hash_handle hh;
  7948. };
  7949. static void adjust_mostdevs(void)
  7950. {
  7951. if (total_devices - zombie_devs > most_devices)
  7952. most_devices = total_devices - zombie_devs;
  7953. }
  7954. #ifdef USE_ICARUS
  7955. bool icarus_get_device_id(struct cgpu_info *cgpu)
  7956. {
  7957. static struct _cgpu_devid_counter *devids = NULL;
  7958. struct _cgpu_devid_counter *d;
  7959. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7960. if (d)
  7961. return (d->lastid + 1);
  7962. else
  7963. return 0;
  7964. }
  7965. #endif
  7966. bool add_cgpu(struct cgpu_info *cgpu)
  7967. {
  7968. static struct _cgpu_devid_counter *devids = NULL;
  7969. struct _cgpu_devid_counter *d;
  7970. HASH_FIND_STR(devids, cgpu->drv->name, d);
  7971. if (d)
  7972. cgpu->device_id = ++d->lastid;
  7973. else {
  7974. d = malloc(sizeof(*d));
  7975. memcpy(d->name, cgpu->drv->name, sizeof(d->name));
  7976. cgpu->device_id = d->lastid = 0;
  7977. HASH_ADD_STR(devids, name, d);
  7978. }
  7979. wr_lock(&devices_lock);
  7980. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + new_devices + 2));
  7981. wr_unlock(&devices_lock);
  7982. mutex_lock(&stats_lock);
  7983. cgpu->last_device_valid_work = time(NULL);
  7984. mutex_unlock(&stats_lock);
  7985. if (hotplug_mode)
  7986. devices[total_devices + new_devices++] = cgpu;
  7987. else
  7988. devices[total_devices++] = cgpu;
  7989. adjust_mostdevs();
  7990. #ifdef USE_USBUTILS
  7991. if (cgpu->usbdev && !cgpu->unique_id && cgpu->usbdev->serial_string &&
  7992. strlen(cgpu->usbdev->serial_string) > 4)
  7993. cgpu->unique_id = str_text(cgpu->usbdev->serial_string);
  7994. #endif
  7995. return true;
  7996. }
  7997. struct device_drv *copy_drv(struct device_drv *drv)
  7998. {
  7999. struct device_drv *copy;
  8000. if (unlikely(!(copy = malloc(sizeof(*copy))))) {
  8001. quit(1, "Failed to allocate device_drv copy of %s (%s)",
  8002. drv->name, drv->copy ? "copy" : "original");
  8003. }
  8004. memcpy(copy, drv, sizeof(*copy));
  8005. copy->copy = true;
  8006. return copy;
  8007. }
  8008. #ifdef USE_USBUTILS
  8009. static void hotplug_process(void)
  8010. {
  8011. struct thr_info *thr;
  8012. int i, j;
  8013. for (i = 0; i < new_devices; i++) {
  8014. struct cgpu_info *cgpu;
  8015. int dev_no = total_devices + i;
  8016. cgpu = devices[dev_no];
  8017. enable_device(cgpu);
  8018. cgpu->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8019. cgpu->rolling = cgpu->total_mhashes = 0;
  8020. }
  8021. wr_lock(&mining_thr_lock);
  8022. mining_thr = realloc(mining_thr, sizeof(thr) * (mining_threads + new_threads + 1));
  8023. if (!mining_thr)
  8024. quit(1, "Failed to hotplug realloc mining_thr");
  8025. for (i = 0; i < new_threads; i++) {
  8026. mining_thr[mining_threads + i] = calloc(1, sizeof(*thr));
  8027. if (!mining_thr[mining_threads + i])
  8028. quit(1, "Failed to hotplug calloc mining_thr[%d]", i);
  8029. }
  8030. // Start threads
  8031. for (i = 0; i < new_devices; ++i) {
  8032. struct cgpu_info *cgpu = devices[total_devices];
  8033. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  8034. cgpu->thr[cgpu->threads] = NULL;
  8035. cgpu->status = LIFE_INIT;
  8036. cgtime(&(cgpu->dev_start_tv));
  8037. for (j = 0; j < cgpu->threads; ++j) {
  8038. thr = __get_thread(mining_threads);
  8039. thr->id = mining_threads;
  8040. thr->cgpu = cgpu;
  8041. thr->device_thread = j;
  8042. if (!cgpu->drv->thread_prepare(thr)) {
  8043. null_device_drv(cgpu->drv);
  8044. cgpu->deven = DEV_DISABLED;
  8045. continue;
  8046. }
  8047. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8048. quit(1, "hotplug thread %d create failed", thr->id);
  8049. cgpu->thr[j] = thr;
  8050. /* Enable threads for devices set not to mine but disable
  8051. * their queue in case we wish to enable them later */
  8052. if (cgpu->deven != DEV_DISABLED) {
  8053. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8054. cgsem_post(&thr->sem);
  8055. }
  8056. mining_threads++;
  8057. }
  8058. total_devices++;
  8059. applog(LOG_WARNING, "Hotplug: %s added %s %i", cgpu->drv->dname, cgpu->drv->name, cgpu->device_id);
  8060. }
  8061. wr_unlock(&mining_thr_lock);
  8062. adjust_mostdevs();
  8063. #ifdef HAVE_CURSES
  8064. switch_logsize(true);
  8065. #endif
  8066. }
  8067. #define DRIVER_DRV_DETECT_HOTPLUG(X) X##_drv.drv_detect(true);
  8068. static void *hotplug_thread(void __maybe_unused *userdata)
  8069. {
  8070. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  8071. RenameThread("Hotplug");
  8072. hotplug_mode = true;
  8073. cgsleep_ms(5000);
  8074. while (0x2a) {
  8075. // Version 0.1 just add the devices on - worry about using nodev later
  8076. if (hotplug_time == 0)
  8077. cgsleep_ms(5000);
  8078. else {
  8079. new_devices = 0;
  8080. new_threads = 0;
  8081. /* Use the DRIVER_PARSE_COMMANDS macro to detect all
  8082. * devices */
  8083. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_HOTPLUG)
  8084. if (new_devices)
  8085. hotplug_process();
  8086. // hotplug_time >0 && <=9999
  8087. cgsleep_ms(hotplug_time * 1000);
  8088. }
  8089. }
  8090. return NULL;
  8091. }
  8092. #endif
  8093. static void probe_pools(void)
  8094. {
  8095. int i;
  8096. for (i = 0; i < total_pools; i++) {
  8097. struct pool *pool = pools[i];
  8098. pool->testing = true;
  8099. pthread_create(&pool->test_thread, NULL, test_pool_thread, (void *)pool);
  8100. }
  8101. }
  8102. #define DRIVER_FILL_DEVICE_DRV(X) fill_device_drv(&X##_drv);
  8103. #define DRIVER_DRV_DETECT_ALL(X) X##_drv.drv_detect(false);
  8104. #ifdef USE_USBUTILS
  8105. static void *libusb_poll_thread(void __maybe_unused *arg)
  8106. {
  8107. struct timeval tv_end = {1, 0};
  8108. RenameThread("USBPoll");
  8109. while (usb_polling)
  8110. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8111. /* Cancel any cancellable usb transfers */
  8112. cancel_usb_transfers();
  8113. /* Keep event handling going until there are no async transfers in
  8114. * flight. */
  8115. do {
  8116. libusb_handle_events_timeout_completed(NULL, &tv_end, NULL);
  8117. } while (async_usb_transfers());
  8118. return NULL;
  8119. }
  8120. static void initialise_usb(void) {
  8121. int err = libusb_init(NULL);
  8122. if (err) {
  8123. fprintf(stderr, "libusb_init() failed err %d", err);
  8124. fflush(stderr);
  8125. quit(1, "libusb_init() failed");
  8126. }
  8127. initialise_usblocks();
  8128. usb_polling = true;
  8129. pthread_create(&usb_poll_thread, NULL, libusb_poll_thread, NULL);
  8130. }
  8131. #else
  8132. #define initialise_usb() {}
  8133. #endif
  8134. int main(int argc, char *argv[])
  8135. {
  8136. struct sigaction handler;
  8137. struct work *work = NULL;
  8138. bool pool_msg = false;
  8139. struct thr_info *thr;
  8140. struct block *block;
  8141. int i, j, slept = 0;
  8142. unsigned int k;
  8143. char *s;
  8144. /* This dangerous functions tramples random dynamically allocated
  8145. * variables so do it before anything at all */
  8146. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  8147. early_quit(1, "Failed to curl_global_init");
  8148. # ifdef __linux
  8149. /* If we're on a small lowspec platform with only one CPU, we should
  8150. * yield after dropping a lock to allow a thread waiting for it to be
  8151. * able to get CPU time to grab the lock. */
  8152. if (sysconf(_SC_NPROCESSORS_ONLN) == 1)
  8153. selective_yield = &sched_yield;
  8154. #endif
  8155. #if LOCK_TRACKING
  8156. // Must be first
  8157. if (unlikely(pthread_mutex_init(&lockstat_lock, NULL)))
  8158. quithere(1, "Failed to pthread_mutex_init lockstat_lock errno=%d", errno);
  8159. #endif
  8160. initial_args = malloc(sizeof(char *) * (argc + 1));
  8161. for (i = 0; i < argc; i++)
  8162. initial_args[i] = strdup(argv[i]);
  8163. initial_args[argc] = NULL;
  8164. mutex_init(&hash_lock);
  8165. mutex_init(&console_lock);
  8166. cglock_init(&control_lock);
  8167. mutex_init(&stats_lock);
  8168. mutex_init(&sharelog_lock);
  8169. cglock_init(&ch_lock);
  8170. mutex_init(&sshare_lock);
  8171. rwlock_init(&blk_lock);
  8172. rwlock_init(&netacc_lock);
  8173. rwlock_init(&mining_thr_lock);
  8174. rwlock_init(&devices_lock);
  8175. mutex_init(&lp_lock);
  8176. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  8177. early_quit(1, "Failed to pthread_cond_init lp_cond");
  8178. mutex_init(&restart_lock);
  8179. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  8180. early_quit(1, "Failed to pthread_cond_init restart_cond");
  8181. if (unlikely(pthread_cond_init(&gws_cond, NULL)))
  8182. early_quit(1, "Failed to pthread_cond_init gws_cond");
  8183. /* Create a unique get work queue */
  8184. getq = tq_new();
  8185. if (!getq)
  8186. early_quit(1, "Failed to create getq");
  8187. /* We use the getq mutex as the staged lock */
  8188. stgd_lock = &getq->mutex;
  8189. initialise_usb();
  8190. snprintf(packagename, sizeof(packagename), "%s %s", PACKAGE, VERSION);
  8191. handler.sa_handler = &sighandler;
  8192. handler.sa_flags = 0;
  8193. sigemptyset(&handler.sa_mask);
  8194. sigaction(SIGTERM, &handler, &termhandler);
  8195. sigaction(SIGINT, &handler, &inthandler);
  8196. #ifndef WIN32
  8197. signal(SIGPIPE, SIG_IGN);
  8198. #else
  8199. timeBeginPeriod(1);
  8200. #endif
  8201. opt_kernel_path = alloca(PATH_MAX);
  8202. strcpy(opt_kernel_path, CGMINER_PREFIX);
  8203. cgminer_path = alloca(PATH_MAX);
  8204. s = strdup(argv[0]);
  8205. strcpy(cgminer_path, dirname(s));
  8206. free(s);
  8207. strcat(cgminer_path, "/");
  8208. devcursor = 8;
  8209. logstart = devcursor + 1;
  8210. logcursor = logstart + 1;
  8211. block = calloc(sizeof(struct block), 1);
  8212. if (unlikely(!block))
  8213. quit (1, "main OOM");
  8214. for (i = 0; i < 36; i++)
  8215. strcat(block->hash, "0");
  8216. HASH_ADD_STR(blocks, hash, block);
  8217. strcpy(current_hash, block->hash);
  8218. INIT_LIST_HEAD(&scan_devices);
  8219. /* parse command line */
  8220. opt_register_table(opt_config_table,
  8221. "Options for both config file and command line");
  8222. opt_register_table(opt_cmdline_table,
  8223. "Options for command line only");
  8224. opt_parse(&argc, argv, applog_and_exit);
  8225. if (argc != 1)
  8226. early_quit(1, "Unexpected extra commandline arguments");
  8227. if (!config_loaded)
  8228. load_default_config();
  8229. if (!opt_sha256 && !opt_scrypt)
  8230. early_quit(1, "Must explicitly specify mining algorithm (--sha256 or --scrypt)");
  8231. if (opt_benchmark || opt_benchfile) {
  8232. struct pool *pool;
  8233. if (opt_scrypt)
  8234. early_quit(1, "Cannot use benchmark mode with scrypt");
  8235. pool = add_pool();
  8236. pool->rpc_url = malloc(255);
  8237. if (opt_benchfile)
  8238. strcpy(pool->rpc_url, "Benchfile");
  8239. else
  8240. strcpy(pool->rpc_url, "Benchmark");
  8241. pool->rpc_user = pool->rpc_url;
  8242. pool->rpc_pass = pool->rpc_url;
  8243. pool->rpc_userpass = pool->rpc_url;
  8244. pool->sockaddr_url = pool->rpc_url;
  8245. strncpy(pool->diff, "?", sizeof(pool->diff)-1);
  8246. pool->diff[sizeof(pool->diff)-1] = '\0';
  8247. enable_pool(pool);
  8248. pool->idle = false;
  8249. successful_connect = true;
  8250. for (i = 0; i < 16; i++) {
  8251. hex2bin(&bench_hidiff_bins[i][0], &bench_hidiffs[i][0], 160);
  8252. hex2bin(&bench_lodiff_bins[i][0], &bench_lodiffs[i][0], 160);
  8253. }
  8254. set_target(bench_target, 32);
  8255. }
  8256. #ifdef HAVE_CURSES
  8257. if (opt_realquiet || opt_display_devs)
  8258. use_curses = false;
  8259. if (use_curses)
  8260. enable_curses();
  8261. #endif
  8262. applog(LOG_WARNING, "Started %s", packagename);
  8263. if (cnfbuf) {
  8264. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  8265. switch (fileconf_load) {
  8266. case 0:
  8267. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  8268. applog(LOG_WARNING, "Configuration file could not be used.");
  8269. break;
  8270. case -1:
  8271. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  8272. if (use_curses)
  8273. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  8274. break;
  8275. default:
  8276. break;
  8277. }
  8278. free(cnfbuf);
  8279. cnfbuf = NULL;
  8280. }
  8281. strcat(opt_kernel_path, "/");
  8282. if (want_per_device_stats)
  8283. opt_log_output = true;
  8284. /* Use a shorter scantime for scrypt */
  8285. if (opt_scantime < 0)
  8286. opt_scantime = opt_scrypt ? 30 : 60;
  8287. total_control_threads = 8;
  8288. control_thr = calloc(total_control_threads, sizeof(*thr));
  8289. if (!control_thr)
  8290. early_quit(1, "Failed to calloc control_thr");
  8291. gwsched_thr_id = 0;
  8292. #ifdef USE_USBUTILS
  8293. usb_initialise();
  8294. // before device detection
  8295. cgsem_init(&usb_resource_sem);
  8296. usbres_thr_id = 1;
  8297. thr = &control_thr[usbres_thr_id];
  8298. if (thr_info_create(thr, NULL, usb_resource_thread, thr))
  8299. early_quit(1, "usb resource thread create failed");
  8300. pthread_detach(thr->pth);
  8301. #endif
  8302. /* Use the DRIVER_PARSE_COMMANDS macro to fill all the device_drvs */
  8303. DRIVER_PARSE_COMMANDS(DRIVER_FILL_DEVICE_DRV)
  8304. /* Use the DRIVER_PARSE_COMMANDS macro to detect all devices */
  8305. DRIVER_PARSE_COMMANDS(DRIVER_DRV_DETECT_ALL)
  8306. if (opt_display_devs) {
  8307. applog(LOG_ERR, "Devices detected:");
  8308. for (i = 0; i < total_devices; ++i) {
  8309. struct cgpu_info *cgpu = devices[i];
  8310. if (cgpu->name)
  8311. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->name, cgpu->drv->dname);
  8312. else
  8313. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->drv->name, cgpu->device_id, cgpu->drv->dname);
  8314. }
  8315. early_quit(0, "%d devices listed", total_devices);
  8316. }
  8317. mining_threads = 0;
  8318. for (i = 0; i < total_devices; ++i)
  8319. enable_device(devices[i]);
  8320. #ifdef USE_USBUTILS
  8321. if (!total_devices) {
  8322. applog(LOG_WARNING, "No devices detected!");
  8323. applog(LOG_WARNING, "Waiting for USB hotplug devices or press q to quit");
  8324. }
  8325. #else
  8326. if (!total_devices)
  8327. early_quit(1, "All devices disabled, cannot mine!");
  8328. #endif
  8329. if (opt_queue == -1)
  8330. opt_queue = (opt_scrypt) ? total_devices : 9999;
  8331. most_devices = total_devices;
  8332. load_temp_cutoffs();
  8333. for (i = 0; i < total_devices; ++i)
  8334. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8335. if (!opt_compact) {
  8336. logstart += most_devices;
  8337. logcursor = logstart + 1;
  8338. #ifdef HAVE_CURSES
  8339. check_winsizes();
  8340. #endif
  8341. }
  8342. if (!total_pools) {
  8343. applog(LOG_WARNING, "Need to specify at least one pool server.");
  8344. #ifdef HAVE_CURSES
  8345. if (!use_curses || !input_pool(false))
  8346. #endif
  8347. early_quit(1, "Pool setup failed");
  8348. }
  8349. for (i = 0; i < total_pools; i++) {
  8350. struct pool *pool = pools[i];
  8351. size_t siz;
  8352. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8353. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  8354. if (!pool->rpc_userpass) {
  8355. if (!pool->rpc_pass)
  8356. pool->rpc_pass = strdup("");
  8357. if (!pool->rpc_user)
  8358. early_quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  8359. siz = strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2;
  8360. pool->rpc_userpass = malloc(siz);
  8361. if (!pool->rpc_userpass)
  8362. early_quit(1, "Failed to malloc userpass");
  8363. snprintf(pool->rpc_userpass, siz, "%s:%s", pool->rpc_user, pool->rpc_pass);
  8364. }
  8365. }
  8366. /* Set the currentpool to pool 0 */
  8367. currentpool = pools[0];
  8368. #ifdef HAVE_SYSLOG_H
  8369. if (use_syslog)
  8370. openlog(PACKAGE, LOG_PID, LOG_USER);
  8371. #endif
  8372. #if defined(unix) || defined(__APPLE__)
  8373. if (opt_stderr_cmd)
  8374. fork_monitor();
  8375. #endif // defined(unix)
  8376. mining_thr = calloc(mining_threads, sizeof(thr));
  8377. if (!mining_thr)
  8378. early_quit(1, "Failed to calloc mining_thr");
  8379. for (i = 0; i < mining_threads; i++) {
  8380. mining_thr[i] = calloc(1, sizeof(*thr));
  8381. if (!mining_thr[i])
  8382. early_quit(1, "Failed to calloc mining_thr[%d]", i);
  8383. }
  8384. // Start threads
  8385. k = 0;
  8386. for (i = 0; i < total_devices; ++i) {
  8387. struct cgpu_info *cgpu = devices[i];
  8388. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  8389. cgpu->thr[cgpu->threads] = NULL;
  8390. cgpu->status = LIFE_INIT;
  8391. for (j = 0; j < cgpu->threads; ++j, ++k) {
  8392. thr = get_thread(k);
  8393. thr->id = k;
  8394. thr->cgpu = cgpu;
  8395. thr->device_thread = j;
  8396. if (!cgpu->drv->thread_prepare(thr))
  8397. continue;
  8398. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  8399. early_quit(1, "thread %d create failed", thr->id);
  8400. cgpu->thr[j] = thr;
  8401. /* Enable threads for devices set not to mine but disable
  8402. * their queue in case we wish to enable them later */
  8403. if (cgpu->deven != DEV_DISABLED) {
  8404. applog(LOG_DEBUG, "Pushing sem post to thread %d", thr->id);
  8405. cgsem_post(&thr->sem);
  8406. }
  8407. }
  8408. }
  8409. if (opt_benchmark || opt_benchfile)
  8410. goto begin_bench;
  8411. for (i = 0; i < total_pools; i++) {
  8412. struct pool *pool = pools[i];
  8413. enable_pool(pool);
  8414. pool->idle = true;
  8415. }
  8416. /* Look for at least one active pool before starting */
  8417. applog(LOG_NOTICE, "Probing for an alive pool");
  8418. probe_pools();
  8419. do {
  8420. sleep(1);
  8421. slept++;
  8422. } while (!pools_active && slept < 60);
  8423. while (!pools_active) {
  8424. if (!pool_msg) {
  8425. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  8426. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  8427. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  8428. for (i = 0; i < total_pools; i++) {
  8429. struct pool *pool = pools[i];
  8430. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  8431. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  8432. }
  8433. pool_msg = true;
  8434. if (use_curses)
  8435. applog(LOG_ERR, "Press any key to exit, or cgminer will wait indefinitely for an alive pool.");
  8436. }
  8437. if (!use_curses)
  8438. early_quit(0, "No servers could be used! Exiting.");
  8439. #ifdef HAVE_CURSES
  8440. touchwin(logwin);
  8441. wrefresh(logwin);
  8442. halfdelay(10);
  8443. if (getch() != ERR)
  8444. early_quit(0, "No servers could be used! Exiting.");
  8445. cbreak();
  8446. #endif
  8447. };
  8448. begin_bench:
  8449. total_mhashes_done = 0;
  8450. for (i = 0; i < total_devices; i++) {
  8451. struct cgpu_info *cgpu = devices[i];
  8452. cgpu->rolling = cgpu->total_mhashes = 0;
  8453. }
  8454. cgtime(&total_tv_start);
  8455. cgtime(&total_tv_end);
  8456. cgtime(&tv_hashmeter);
  8457. get_datestamp(datestamp, sizeof(datestamp), &total_tv_start);
  8458. watchpool_thr_id = 2;
  8459. thr = &control_thr[watchpool_thr_id];
  8460. /* start watchpool thread */
  8461. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  8462. early_quit(1, "watchpool thread create failed");
  8463. pthread_detach(thr->pth);
  8464. watchdog_thr_id = 3;
  8465. thr = &control_thr[watchdog_thr_id];
  8466. /* start watchdog thread */
  8467. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  8468. early_quit(1, "watchdog thread create failed");
  8469. pthread_detach(thr->pth);
  8470. /* Create API socket thread */
  8471. api_thr_id = 5;
  8472. thr = &control_thr[api_thr_id];
  8473. if (thr_info_create(thr, NULL, api_thread, thr))
  8474. early_quit(1, "API thread create failed");
  8475. #ifdef USE_USBUTILS
  8476. hotplug_thr_id = 6;
  8477. thr = &control_thr[hotplug_thr_id];
  8478. if (thr_info_create(thr, NULL, hotplug_thread, thr))
  8479. early_quit(1, "hotplug thread create failed");
  8480. pthread_detach(thr->pth);
  8481. #endif
  8482. #ifdef HAVE_CURSES
  8483. /* Create curses input thread for keyboard input. Create this last so
  8484. * that we know all threads are created since this can call kill_work
  8485. * to try and shut down all previous threads. */
  8486. input_thr_id = 7;
  8487. thr = &control_thr[input_thr_id];
  8488. if (thr_info_create(thr, NULL, input_thread, thr))
  8489. early_quit(1, "input thread create failed");
  8490. pthread_detach(thr->pth);
  8491. #endif
  8492. /* Just to be sure */
  8493. if (total_control_threads != 8)
  8494. early_quit(1, "incorrect total_control_threads (%d) should be 8", total_control_threads);
  8495. set_highprio();
  8496. /* Once everything is set up, main() becomes the getwork scheduler */
  8497. while (42) {
  8498. int ts, max_staged = max_queue;
  8499. struct pool *pool, *cp;
  8500. bool lagging = false;
  8501. if (opt_work_update)
  8502. signal_work_update();
  8503. opt_work_update = false;
  8504. cp = current_pool();
  8505. /* If the primary pool is a getwork pool and cannot roll work,
  8506. * try to stage one extra work per mining thread */
  8507. if (!pool_localgen(cp) && !staged_rollable)
  8508. max_staged += mining_threads;
  8509. mutex_lock(stgd_lock);
  8510. ts = __total_staged();
  8511. if (!pool_localgen(cp) && !ts && !opt_fail_only)
  8512. lagging = true;
  8513. /* Wait until hash_pop tells us we need to create more work */
  8514. if (ts > max_staged) {
  8515. if (work_emptied && max_queue < opt_queue) {
  8516. max_queue++;
  8517. work_emptied = false;
  8518. }
  8519. work_filled = true;
  8520. pthread_cond_wait(&gws_cond, stgd_lock);
  8521. ts = __total_staged();
  8522. }
  8523. mutex_unlock(stgd_lock);
  8524. if (ts > max_staged) {
  8525. /* Keeps slowly generating work even if it's not being
  8526. * used to keep last_getwork incrementing and to see
  8527. * if pools are still alive. */
  8528. if (work_emptied && max_queue < opt_queue) {
  8529. max_queue++;
  8530. work_emptied = false;
  8531. }
  8532. work_filled = true;
  8533. work = hash_pop(false);
  8534. if (work)
  8535. discard_work(work);
  8536. continue;
  8537. }
  8538. if (work)
  8539. discard_work(work);
  8540. work = make_work();
  8541. if (lagging && !pool_tset(cp, &cp->lagging)) {
  8542. applog(LOG_WARNING, "Pool %d not providing work fast enough", cp->pool_no);
  8543. cp->getfail_occasions++;
  8544. total_go++;
  8545. if (!pool_localgen(cp) && max_queue < opt_queue)
  8546. applog(LOG_INFO, "Increasing queue to %d", ++max_queue);
  8547. }
  8548. pool = select_pool(lagging);
  8549. retry:
  8550. if (pool->has_stratum) {
  8551. while (!pool->stratum_active || !pool->stratum_notify) {
  8552. struct pool *altpool = select_pool(true);
  8553. cgsleep_ms(5000);
  8554. if (altpool != pool) {
  8555. pool = altpool;
  8556. goto retry;
  8557. }
  8558. }
  8559. gen_stratum_work(pool, work);
  8560. applog(LOG_DEBUG, "Generated stratum work");
  8561. stage_work(work);
  8562. continue;
  8563. }
  8564. if (opt_benchfile) {
  8565. get_benchfile_work(work);
  8566. applog(LOG_DEBUG, "Generated benchfile work");
  8567. stage_work(work);
  8568. continue;
  8569. } else if (opt_benchmark) {
  8570. get_benchmark_work(work);
  8571. applog(LOG_DEBUG, "Generated benchmark work");
  8572. stage_work(work);
  8573. continue;
  8574. }
  8575. #ifdef HAVE_LIBCURL
  8576. struct curl_ent *ce;
  8577. if (pool->gbt_solo) {
  8578. while (pool->idle) {
  8579. struct pool *altpool = select_pool(true);
  8580. cgsleep_ms(5000);
  8581. if (altpool != pool) {
  8582. pool = altpool;
  8583. goto retry;
  8584. }
  8585. }
  8586. gen_solo_work(pool, work);
  8587. applog(LOG_DEBUG, "Generated GBT SOLO work");
  8588. stage_work(work);
  8589. continue;
  8590. }
  8591. if (pool->has_gbt) {
  8592. while (pool->idle) {
  8593. struct pool *altpool = select_pool(true);
  8594. cgsleep_ms(5000);
  8595. if (altpool != pool) {
  8596. pool = altpool;
  8597. goto retry;
  8598. }
  8599. }
  8600. gen_gbt_work(pool, work);
  8601. applog(LOG_DEBUG, "Generated GBT work");
  8602. stage_work(work);
  8603. continue;
  8604. }
  8605. if (clone_available()) {
  8606. applog(LOG_DEBUG, "Cloned getwork work");
  8607. free_work(work);
  8608. continue;
  8609. }
  8610. work->pool = pool;
  8611. ce = pop_curl_entry(pool);
  8612. /* obtain new work from bitcoin via JSON-RPC */
  8613. if (!get_upstream_work(work, ce->curl)) {
  8614. applog(LOG_DEBUG, "Pool %d json_rpc_call failed on get work, retrying in 5s", pool->pool_no);
  8615. /* Make sure the pool just hasn't stopped serving
  8616. * requests but is up as we'll keep hammering it */
  8617. if (++pool->seq_getfails > mining_threads + opt_queue)
  8618. pool_died(pool);
  8619. cgsleep_ms(5000);
  8620. push_curl_entry(ce, pool);
  8621. pool = select_pool(!opt_fail_only);
  8622. free_work(work);
  8623. goto retry;
  8624. }
  8625. if (ts >= max_staged)
  8626. pool_tclear(pool, &pool->lagging);
  8627. if (pool_tclear(pool, &pool->idle))
  8628. pool_resus(pool);
  8629. applog(LOG_DEBUG, "Generated getwork work");
  8630. stage_work(work);
  8631. push_curl_entry(ce, pool);
  8632. #endif
  8633. }
  8634. return 0;
  8635. }