cgminer.c 200 KB

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