cgminer.c 185 KB

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