cgminer.c 199 KB

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