cgminer.c 198 KB

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