cgminer.c 222 KB

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