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