cgminer.c 184 KB

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