cgminer.c 197 KB

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