cgminer.c 167 KB

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