cgminer.c 200 KB

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