cgminer.c 185 KB

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