cgminer.c 185 KB

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