cgminer.c 181 KB

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