cgminer.c 165 KB

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