cgminer.c 199 KB

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