cgminer.c 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373
  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, const struct work *work, char *hashshow,
  1573. 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. if (total_pools > 1)
  1628. sprintf(where, "pool %d", work->pool->pool_no);
  1629. else
  1630. strcpy(where, "");
  1631. res = json_object_get(val, "reject-reason");
  1632. if (res) {
  1633. const char *reasontmp = json_string_value(res);
  1634. size_t reasonLen = strlen(reasontmp);
  1635. if (reasonLen > 28)
  1636. reasonLen = 28;
  1637. reason[0] = ' '; reason[1] = '(';
  1638. memcpy(2 + reason, reasontmp, reasonLen);
  1639. reason[reasonLen + 2] = ')'; reason[reasonLen + 3] = '\0';
  1640. memcpy(disposition + 7, reasontmp, reasonLen);
  1641. disposition[6] = ':'; disposition[reasonLen + 7] = '\0';
  1642. } else
  1643. strcpy(reason, "");
  1644. applog(LOG_NOTICE, "Rejected %s %s %d %s%s %s%s",
  1645. hashshow, cgpu->api->name, cgpu->device_id, where, reason, resubmit ? "(resubmit)" : "", worktime);
  1646. sharelog(disposition, work);
  1647. }
  1648. /* Once we have more than a nominal amount of sequential rejects,
  1649. * at least 10 and more than 3 mins at the current utility,
  1650. * disable the pool because some pool error is likely to have
  1651. * ensued. Do not do this if we know the share just happened to
  1652. * be stale due to networking delays.
  1653. */
  1654. if (pool->seq_rejects > 10 && !work->stale && opt_disable_pool && enabled_pools > 1) {
  1655. double utility = total_accepted / total_secs * 60;
  1656. if (pool->seq_rejects > utility * 3) {
  1657. applog(LOG_WARNING, "Pool %d rejected %d sequential shares, disabling!",
  1658. pool->pool_no, pool->seq_rejects);
  1659. reject_pool(pool);
  1660. if (pool == current_pool())
  1661. switch_pools(NULL);
  1662. pool->seq_rejects = 0;
  1663. }
  1664. }
  1665. }
  1666. }
  1667. static bool submit_upstream_work(const struct work *work, CURL *curl, bool resubmit)
  1668. {
  1669. char *hexstr = NULL;
  1670. json_t *val, *res;
  1671. char s[345], sd[345];
  1672. bool rc = false;
  1673. int thr_id = work->thr_id;
  1674. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1675. struct pool *pool = work->pool;
  1676. int rolltime;
  1677. uint32_t *hash32;
  1678. struct timeval tv_submit, tv_submit_reply;
  1679. char hashshow[64 + 1] = "";
  1680. char worktime[200] = "";
  1681. #ifdef __BIG_ENDIAN__
  1682. int swapcounter = 0;
  1683. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  1684. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  1685. #endif
  1686. /* build hex string */
  1687. hexstr = bin2hex(work->data, sizeof(work->data));
  1688. if (unlikely(!hexstr)) {
  1689. applog(LOG_ERR, "submit_upstream_work OOM");
  1690. goto out_nofree;
  1691. }
  1692. /* build JSON-RPC request */
  1693. sprintf(s,
  1694. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1695. hexstr);
  1696. sprintf(sd,
  1697. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1698. hexstr);
  1699. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1700. gettimeofday(&tv_submit, NULL);
  1701. /* issue JSON-RPC request */
  1702. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool, true);
  1703. gettimeofday(&tv_submit_reply, NULL);
  1704. if (unlikely(!val)) {
  1705. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1706. if (!pool_tset(pool, &pool->submit_fail)) {
  1707. total_ro++;
  1708. pool->remotefail_occasions++;
  1709. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1710. }
  1711. goto out;
  1712. } else if (pool_tclear(pool, &pool->submit_fail))
  1713. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1714. res = json_object_get(val, "result");
  1715. if (!QUIET) {
  1716. hash32 = (uint32_t *)(work->hash);
  1717. if (opt_scrypt)
  1718. sprintf(hashshow, "%08lx.%08lx", (unsigned long)(hash32[7]), (unsigned long)(hash32[6]));
  1719. else {
  1720. int intdiff = round(work->work_difficulty);
  1721. sprintf(hashshow, "%08lx Diff %d%s", (unsigned long)(hash32[6]), intdiff,
  1722. work->block? " BLOCK!" : "");
  1723. }
  1724. if (opt_worktime) {
  1725. char workclone[20];
  1726. struct tm *tm, tm_getwork, tm_submit_reply;
  1727. double getwork_time = tdiff((struct timeval *)&(work->tv_getwork_reply),
  1728. (struct timeval *)&(work->tv_getwork));
  1729. double getwork_to_work = tdiff((struct timeval *)&(work->tv_work_start),
  1730. (struct timeval *)&(work->tv_getwork_reply));
  1731. double work_time = tdiff((struct timeval *)&(work->tv_work_found),
  1732. (struct timeval *)&(work->tv_work_start));
  1733. double work_to_submit = tdiff(&tv_submit,
  1734. (struct timeval *)&(work->tv_work_found));
  1735. double submit_time = tdiff(&tv_submit_reply, &tv_submit);
  1736. int diffplaces = 3;
  1737. tm = localtime(&(work->tv_getwork.tv_sec));
  1738. memcpy(&tm_getwork, tm, sizeof(struct tm));
  1739. tm = localtime(&(tv_submit_reply.tv_sec));
  1740. memcpy(&tm_submit_reply, tm, sizeof(struct tm));
  1741. if (work->clone) {
  1742. sprintf(workclone, "C:%1.3f",
  1743. tdiff((struct timeval *)&(work->tv_cloned),
  1744. (struct timeval *)&(work->tv_getwork_reply)));
  1745. }
  1746. else
  1747. strcpy(workclone, "O");
  1748. if (work->work_difficulty < 1)
  1749. diffplaces = 6;
  1750. 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",
  1751. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 32 : 28])),
  1752. (unsigned long)swab32(*(uint32_t *)&(work->data[opt_scrypt ? 28 : 24])),
  1753. work->getwork_mode, diffplaces, work->work_difficulty,
  1754. tm_getwork.tm_hour, tm_getwork.tm_min,
  1755. tm_getwork.tm_sec, getwork_time, workclone,
  1756. getwork_to_work, work_time, work_to_submit, submit_time,
  1757. tm_submit_reply.tm_hour, tm_submit_reply.tm_min,
  1758. tm_submit_reply.tm_sec);
  1759. }
  1760. }
  1761. share_result(val, res, work, hashshow, resubmit, worktime);
  1762. cgpu->utility = cgpu->accepted / total_secs * 60;
  1763. if (!opt_realquiet)
  1764. print_status(thr_id);
  1765. if (!want_per_device_stats) {
  1766. char logline[255];
  1767. get_statline(logline, cgpu);
  1768. applog(LOG_INFO, "%s", logline);
  1769. }
  1770. json_decref(val);
  1771. rc = true;
  1772. out:
  1773. free(hexstr);
  1774. out_nofree:
  1775. return rc;
  1776. }
  1777. static const char *rpc_req =
  1778. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1779. /* In balanced mode, the amount of diff1 solutions per pool is monitored as a
  1780. * rolling average per 10 minutes and if pools start getting more, it biases
  1781. * away from them to distribute work evenly. The share count is reset to the
  1782. * rolling average every 10 minutes to not send all work to one pool after it
  1783. * has been disabled/out for an extended period. */
  1784. static struct pool *select_balanced(struct pool *cp)
  1785. {
  1786. int i, lowest = cp->shares;
  1787. struct pool *ret = cp;
  1788. for (i = 0; i < total_pools; i++) {
  1789. struct pool *pool = pools[i];
  1790. if (pool->idle || pool->enabled != POOL_ENABLED)
  1791. continue;
  1792. if (pool->shares < lowest) {
  1793. lowest = pool->shares;
  1794. ret = pool;
  1795. }
  1796. }
  1797. ret->shares++;
  1798. return ret;
  1799. }
  1800. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1801. static inline struct pool *select_pool(bool lagging)
  1802. {
  1803. static int rotating_pool = 0;
  1804. struct pool *pool, *cp;
  1805. cp = current_pool();
  1806. if (pool_strategy == POOL_BALANCE)
  1807. return select_balanced(cp);
  1808. if (pool_strategy != POOL_LOADBALANCE && (!lagging || opt_fail_only))
  1809. pool = cp;
  1810. else
  1811. pool = NULL;
  1812. while (!pool) {
  1813. if (++rotating_pool >= total_pools)
  1814. rotating_pool = 0;
  1815. pool = pools[rotating_pool];
  1816. if ((!pool->idle && pool->enabled == POOL_ENABLED) || pool == cp)
  1817. break;
  1818. pool = NULL;
  1819. }
  1820. return pool;
  1821. }
  1822. static double DIFFEXACTONE = 26959946667150639794667015087019630673637144422540572481103610249216.0;
  1823. /*
  1824. * Calculate the work share difficulty
  1825. */
  1826. static void calc_diff(struct work *work, int known)
  1827. {
  1828. struct cgminer_pool_stats *pool_stats = &(work->pool->cgminer_pool_stats);
  1829. double targ;
  1830. int i;
  1831. if (!known) {
  1832. targ = 0;
  1833. for (i = 31; i >= 0; i--) {
  1834. targ *= 256;
  1835. targ += work->target[i];
  1836. }
  1837. work->work_difficulty = DIFFEXACTONE / (targ ? : DIFFEXACTONE);
  1838. } else
  1839. work->work_difficulty = known;
  1840. pool_stats->last_diff = work->work_difficulty;
  1841. if (work->work_difficulty == pool_stats->min_diff)
  1842. pool_stats->min_diff_count++;
  1843. else if (work->work_difficulty < pool_stats->min_diff || pool_stats->min_diff == 0) {
  1844. pool_stats->min_diff = work->work_difficulty;
  1845. pool_stats->min_diff_count = 1;
  1846. }
  1847. if (work->work_difficulty == pool_stats->max_diff)
  1848. pool_stats->max_diff_count++;
  1849. else if (work->work_difficulty > pool_stats->max_diff) {
  1850. pool_stats->max_diff = work->work_difficulty;
  1851. pool_stats->max_diff_count = 1;
  1852. }
  1853. }
  1854. static void get_benchmark_work(struct work *work)
  1855. {
  1856. // Use a random work block pulled from a pool
  1857. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  1858. size_t bench_size = sizeof(work);
  1859. size_t work_size = sizeof(bench_block);
  1860. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  1861. memset(work, 0, sizeof(work));
  1862. memcpy(work, &bench_block, min_size);
  1863. work->mandatory = true;
  1864. work->pool = pools[0];
  1865. gettimeofday(&(work->tv_getwork), NULL);
  1866. memcpy(&(work->tv_getwork_reply), &(work->tv_getwork), sizeof(struct timeval));
  1867. work->getwork_mode = GETWORK_MODE_BENCHMARK;
  1868. calc_diff(work, 0);
  1869. }
  1870. static bool get_upstream_work(struct work *work, CURL *curl)
  1871. {
  1872. struct pool *pool = work->pool;
  1873. struct cgminer_pool_stats *pool_stats = &(pool->cgminer_pool_stats);
  1874. struct timeval tv_elapsed;
  1875. json_t *val = NULL;
  1876. bool rc = false;
  1877. char *url;
  1878. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1879. url = pool->rpc_url;
  1880. gettimeofday(&(work->tv_getwork), NULL);
  1881. val = json_rpc_call(curl, url, pool->rpc_userpass, rpc_req, false,
  1882. false, &work->rolltime, pool, false);
  1883. pool_stats->getwork_attempts++;
  1884. if (likely(val)) {
  1885. rc = work_decode(json_object_get(val, "result"), work);
  1886. if (unlikely(!rc))
  1887. applog(LOG_DEBUG, "Failed to decode work in get_upstream_work");
  1888. } else
  1889. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1890. gettimeofday(&(work->tv_getwork_reply), NULL);
  1891. timersub(&(work->tv_getwork_reply), &(work->tv_getwork), &tv_elapsed);
  1892. pool_stats->getwork_wait_rolling += ((double)tv_elapsed.tv_sec + ((double)tv_elapsed.tv_usec / 1000000)) * 0.63;
  1893. pool_stats->getwork_wait_rolling /= 1.63;
  1894. timeradd(&tv_elapsed, &(pool_stats->getwork_wait), &(pool_stats->getwork_wait));
  1895. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_max), >)) {
  1896. pool_stats->getwork_wait_max.tv_sec = tv_elapsed.tv_sec;
  1897. pool_stats->getwork_wait_max.tv_usec = tv_elapsed.tv_usec;
  1898. }
  1899. if (timercmp(&tv_elapsed, &(pool_stats->getwork_wait_min), <)) {
  1900. pool_stats->getwork_wait_min.tv_sec = tv_elapsed.tv_sec;
  1901. pool_stats->getwork_wait_min.tv_usec = tv_elapsed.tv_usec;
  1902. }
  1903. pool_stats->getwork_calls++;
  1904. work->pool = pool;
  1905. work->longpoll = false;
  1906. work->getwork_mode = GETWORK_MODE_POOL;
  1907. calc_diff(work, 0);
  1908. total_getworks++;
  1909. pool->getwork_requested++;
  1910. if (likely(val))
  1911. json_decref(val);
  1912. return rc;
  1913. }
  1914. static struct work *make_work(void)
  1915. {
  1916. struct work *work = calloc(1, sizeof(struct work));
  1917. if (unlikely(!work))
  1918. quit(1, "Failed to calloc work in make_work");
  1919. mutex_lock(&control_lock);
  1920. work->id = total_work++;
  1921. mutex_unlock(&control_lock);
  1922. return work;
  1923. }
  1924. static void free_work(struct work *work)
  1925. {
  1926. free(work);
  1927. }
  1928. static void workio_cmd_free(struct workio_cmd *wc)
  1929. {
  1930. if (!wc)
  1931. return;
  1932. switch (wc->cmd) {
  1933. case WC_SUBMIT_WORK:
  1934. free_work(wc->work);
  1935. break;
  1936. default: /* do nothing */
  1937. break;
  1938. }
  1939. memset(wc, 0, sizeof(*wc)); /* poison */
  1940. free(wc);
  1941. }
  1942. #ifdef HAVE_CURSES
  1943. static void disable_curses(void)
  1944. {
  1945. if (curses_active_locked()) {
  1946. curses_active = false;
  1947. leaveok(logwin, false);
  1948. leaveok(statuswin, false);
  1949. leaveok(mainwin, false);
  1950. nocbreak();
  1951. echo();
  1952. delwin(logwin);
  1953. delwin(statuswin);
  1954. delwin(mainwin);
  1955. endwin();
  1956. #ifdef WIN32
  1957. // Move the cursor to after curses output.
  1958. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1959. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1960. COORD coord;
  1961. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1962. coord.X = 0;
  1963. coord.Y = csbi.dwSize.Y - 1;
  1964. SetConsoleCursorPosition(hout, coord);
  1965. }
  1966. #endif
  1967. unlock_curses();
  1968. }
  1969. }
  1970. #endif
  1971. static void print_summary(void);
  1972. static void __kill_work(void)
  1973. {
  1974. struct thr_info *thr;
  1975. int i;
  1976. if (!successful_connect)
  1977. return;
  1978. applog(LOG_INFO, "Received kill message");
  1979. applog(LOG_DEBUG, "Killing off watchpool thread");
  1980. /* Kill the watchpool thread */
  1981. thr = &thr_info[watchpool_thr_id];
  1982. thr_info_cancel(thr);
  1983. applog(LOG_DEBUG, "Killing off watchdog thread");
  1984. /* Kill the watchdog thread */
  1985. thr = &thr_info[watchdog_thr_id];
  1986. thr_info_cancel(thr);
  1987. applog(LOG_DEBUG, "Stopping mining threads");
  1988. /* Stop the mining threads*/
  1989. for (i = 0; i < mining_threads; i++) {
  1990. thr = &thr_info[i];
  1991. thr_info_freeze(thr);
  1992. thr->pause = true;
  1993. }
  1994. sleep(1);
  1995. applog(LOG_DEBUG, "Killing off mining threads");
  1996. /* Kill the mining threads*/
  1997. for (i = 0; i < mining_threads; i++) {
  1998. thr = &thr_info[i];
  1999. thr_info_cancel(thr);
  2000. }
  2001. applog(LOG_DEBUG, "Killing off stage thread");
  2002. /* Stop the others */
  2003. thr = &thr_info[stage_thr_id];
  2004. thr_info_cancel(thr);
  2005. applog(LOG_DEBUG, "Killing off API thread");
  2006. thr = &thr_info[api_thr_id];
  2007. thr_info_cancel(thr);
  2008. }
  2009. /* This should be the common exit path */
  2010. void kill_work(void)
  2011. {
  2012. __kill_work();
  2013. quit(0, "Shutdown signal received.");
  2014. }
  2015. static
  2016. #ifdef WIN32
  2017. const
  2018. #endif
  2019. char **initial_args;
  2020. static void clean_up(void);
  2021. void app_restart(void)
  2022. {
  2023. applog(LOG_WARNING, "Attempting to restart %s", packagename);
  2024. __kill_work();
  2025. clean_up();
  2026. #if defined(unix)
  2027. if (forkpid > 0) {
  2028. kill(forkpid, SIGTERM);
  2029. forkpid = 0;
  2030. }
  2031. #endif
  2032. execv(initial_args[0], initial_args);
  2033. applog(LOG_WARNING, "Failed to restart application");
  2034. }
  2035. static void sighandler(int __maybe_unused sig)
  2036. {
  2037. /* Restore signal handlers so we can still quit if kill_work fails */
  2038. sigaction(SIGTERM, &termhandler, NULL);
  2039. sigaction(SIGINT, &inthandler, NULL);
  2040. kill_work();
  2041. }
  2042. /* Called with pool_lock held. Recruit an extra curl if none are available for
  2043. * this pool. */
  2044. static void recruit_curl(struct pool *pool)
  2045. {
  2046. struct curl_ent *ce = calloc(sizeof(struct curl_ent), 1);
  2047. ce->curl = curl_easy_init();
  2048. if (unlikely(!ce->curl || !ce))
  2049. quit(1, "Failed to init in recruit_curl");
  2050. list_add(&ce->node, &pool->curlring);
  2051. pool->curls++;
  2052. applog(LOG_DEBUG, "Recruited curl %d for pool %d", pool->curls, pool->pool_no);
  2053. }
  2054. /* Grab an available curl if there is one. If not, then recruit extra curls
  2055. * unless we are in a submit_fail situation, or we have opt_delaynet enabled
  2056. * and there are already 5 curls in circulation. Limit total number to the
  2057. * number of mining threads per pool as well to prevent blasting a pool during
  2058. * network delays/outages. */
  2059. static struct curl_ent *pop_curl_entry(struct pool *pool)
  2060. {
  2061. int curl_limit = opt_delaynet ? 5 : (mining_threads + opt_queue) * 2;
  2062. struct curl_ent *ce;
  2063. mutex_lock(&pool->pool_lock);
  2064. retry:
  2065. if (!pool->curls)
  2066. recruit_curl(pool);
  2067. else if (list_empty(&pool->curlring)) {
  2068. if (pool->curls >= curl_limit) {
  2069. pthread_cond_wait(&pool->cr_cond, &pool->pool_lock);
  2070. goto retry;
  2071. } else
  2072. recruit_curl(pool);
  2073. }
  2074. ce = list_entry(pool->curlring.next, struct curl_ent, node);
  2075. list_del(&ce->node);
  2076. mutex_unlock(&pool->pool_lock);
  2077. return ce;
  2078. }
  2079. static void push_curl_entry(struct curl_ent *ce, struct pool *pool)
  2080. {
  2081. mutex_lock(&pool->pool_lock);
  2082. list_add_tail(&ce->node, &pool->curlring);
  2083. gettimeofday(&ce->tv, NULL);
  2084. pthread_cond_signal(&pool->cr_cond);
  2085. mutex_unlock(&pool->pool_lock);
  2086. }
  2087. /* This is overkill, but at least we'll know accurately how much work is
  2088. * queued to prevent ever being left without work */
  2089. static void inc_queued(struct pool *pool)
  2090. {
  2091. mutex_lock(&qd_lock);
  2092. total_queued++;
  2093. pool->queued++;
  2094. mutex_unlock(&qd_lock);
  2095. }
  2096. static void dec_queued(struct pool *pool)
  2097. {
  2098. mutex_lock(&qd_lock);
  2099. total_queued--;
  2100. pool->queued--;
  2101. mutex_unlock(&qd_lock);
  2102. }
  2103. static int __global_queued(void)
  2104. {
  2105. return total_queued;
  2106. }
  2107. static int global_queued(void)
  2108. {
  2109. int ret;
  2110. mutex_lock(&qd_lock);
  2111. ret = __global_queued();
  2112. mutex_unlock(&qd_lock);
  2113. return ret;
  2114. }
  2115. static bool stale_work(struct work *work, bool share);
  2116. static inline bool should_roll(struct work *work)
  2117. {
  2118. struct timeval now;
  2119. time_t expiry;
  2120. if (work->pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE)
  2121. return false;
  2122. if (work->rolltime > opt_scantime)
  2123. expiry = work->rolltime;
  2124. else
  2125. expiry = opt_scantime;
  2126. expiry = expiry * 2 / 3;
  2127. /* We shouldn't roll if we're unlikely to get one shares' duration
  2128. * work out of doing so */
  2129. gettimeofday(&now, NULL);
  2130. if (now.tv_sec - work->tv_staged.tv_sec > expiry)
  2131. return false;
  2132. return true;
  2133. }
  2134. /* Limit rolls to 7000 to not beyond 2 hours in the future where bitcoind will
  2135. * reject blocks as invalid. */
  2136. static inline bool can_roll(struct work *work)
  2137. {
  2138. return (!work->stratum && work->pool && work->rolltime && !work->clone &&
  2139. work->rolls < 7000 && !stale_work(work, false));
  2140. }
  2141. static void roll_work(struct work *work)
  2142. {
  2143. uint32_t *work_ntime;
  2144. uint32_t ntime;
  2145. work_ntime = (uint32_t *)(work->data + 68);
  2146. ntime = be32toh(*work_ntime);
  2147. ntime++;
  2148. *work_ntime = htobe32(ntime);
  2149. local_work++;
  2150. work->rolls++;
  2151. work->blk.nonce = 0;
  2152. applog(LOG_DEBUG, "Successfully rolled work");
  2153. /* This is now a different work item so it needs a different ID for the
  2154. * hashtable */
  2155. work->id = total_work++;
  2156. }
  2157. static struct work *make_clone(struct work *work)
  2158. {
  2159. struct work *work_clone = make_work();
  2160. memcpy(work_clone, work, sizeof(struct work));
  2161. work_clone->clone = true;
  2162. gettimeofday((struct timeval *)&(work_clone->tv_cloned), NULL);
  2163. work_clone->longpoll = false;
  2164. work_clone->mandatory = false;
  2165. /* Make cloned work appear slightly older to bias towards keeping the
  2166. * master work item which can be further rolled */
  2167. work_clone->tv_staged.tv_sec -= 1;
  2168. return work_clone;
  2169. }
  2170. static bool stage_work(struct work *work);
  2171. static bool clone_available(void)
  2172. {
  2173. struct work *work, *tmp;
  2174. bool cloned = false;
  2175. if (!staged_rollable)
  2176. goto out;
  2177. mutex_lock(stgd_lock);
  2178. HASH_ITER(hh, staged_work, work, tmp) {
  2179. if (can_roll(work) && should_roll(work)) {
  2180. struct work *work_clone;
  2181. roll_work(work);
  2182. work_clone = make_clone(work);
  2183. roll_work(work);
  2184. applog(LOG_DEBUG, "Pushing cloned available work to stage thread");
  2185. if (unlikely(!stage_work(work_clone))) {
  2186. free(work_clone);
  2187. break;
  2188. }
  2189. cloned = true;
  2190. break;
  2191. }
  2192. }
  2193. mutex_unlock(stgd_lock);
  2194. out:
  2195. return cloned;
  2196. }
  2197. static bool queue_request(void);
  2198. static void pool_died(struct pool *pool)
  2199. {
  2200. if (!pool_tset(pool, &pool->idle)) {
  2201. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2202. gettimeofday(&pool->tv_idle, NULL);
  2203. switch_pools(NULL);
  2204. }
  2205. }
  2206. static void gen_stratum_work(struct pool *pool, struct work *work);
  2207. static void *get_work_thread(void *userdata)
  2208. {
  2209. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2210. struct pool *pool = current_pool();
  2211. struct work *ret_work= NULL;
  2212. struct curl_ent *ce = NULL;
  2213. pthread_detach(pthread_self());
  2214. applog(LOG_DEBUG, "Creating extra get work thread");
  2215. pool = wc->pool;
  2216. if (pool->has_stratum) {
  2217. ret_work = make_work();
  2218. gen_stratum_work(pool, ret_work);
  2219. if (unlikely(!stage_work(ret_work))) {
  2220. applog(LOG_ERR, "Failed to stage stratum work in get_work_thread");
  2221. kill_work();
  2222. free(ret_work);
  2223. }
  2224. dec_queued(pool);
  2225. goto out;
  2226. }
  2227. if (clone_available()) {
  2228. dec_queued(pool);
  2229. goto out;
  2230. }
  2231. ret_work = make_work();
  2232. ret_work->thr = NULL;
  2233. if (opt_benchmark) {
  2234. get_benchmark_work(ret_work);
  2235. ret_work->queued = true;
  2236. } else {
  2237. ret_work->pool = wc->pool;
  2238. if (!ce)
  2239. ce = pop_curl_entry(pool);
  2240. /* obtain new work from bitcoin via JSON-RPC */
  2241. if (!get_upstream_work(ret_work, ce->curl)) {
  2242. applog(LOG_DEBUG, "json_rpc_call failed on get work, retrying");
  2243. dec_queued(pool);
  2244. /* Make sure the pool just hasn't stopped serving
  2245. * requests but is up as we'll keep hammering it */
  2246. if (++pool->seq_getfails > mining_threads + opt_queue)
  2247. pool_died(pool);
  2248. queue_request();
  2249. free_work(ret_work);
  2250. goto out;
  2251. }
  2252. pool->seq_getfails = 0;
  2253. ret_work->queued = true;
  2254. }
  2255. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2256. /* send work to requesting thread */
  2257. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2258. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2259. kill_work();
  2260. free_work(ret_work);
  2261. }
  2262. out:
  2263. workio_cmd_free(wc);
  2264. if (ce)
  2265. push_curl_entry(ce, pool);
  2266. return NULL;
  2267. }
  2268. /* As per the submit work system, we try to reuse the existing curl handles,
  2269. * but start recruiting extra connections if we start accumulating queued
  2270. * requests */
  2271. static bool workio_get_work(struct workio_cmd *wc)
  2272. {
  2273. pthread_t get_thread;
  2274. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2275. applog(LOG_ERR, "Failed to create get_work_thread");
  2276. return false;
  2277. }
  2278. return true;
  2279. }
  2280. static bool stale_work(struct work *work, bool share)
  2281. {
  2282. struct timeval now;
  2283. time_t work_expiry;
  2284. struct pool *pool;
  2285. int getwork_delay;
  2286. if (work->work_block != work_block) {
  2287. applog(LOG_DEBUG, "Work stale due to block mismatch");
  2288. return true;
  2289. }
  2290. /* Technically the rolltime should be correct but some pools
  2291. * advertise a broken expire= that is lower than a meaningful
  2292. * scantime */
  2293. if (work->rolltime > opt_scantime)
  2294. work_expiry = work->rolltime;
  2295. else
  2296. work_expiry = opt_expiry;
  2297. pool = work->pool;
  2298. /* Factor in the average getwork delay of this pool, rounding it up to
  2299. * the nearest second */
  2300. getwork_delay = pool->cgminer_pool_stats.getwork_wait_rolling * 5 + 1;
  2301. work_expiry -= getwork_delay;
  2302. if (unlikely(work_expiry < 5))
  2303. work_expiry = 5;
  2304. gettimeofday(&now, NULL);
  2305. if ((now.tv_sec - work->tv_staged.tv_sec) >= work_expiry) {
  2306. applog(LOG_DEBUG, "Work stale due to expiry");
  2307. return true;
  2308. }
  2309. if (opt_fail_only && !share && pool != current_pool() && !work->mandatory &&
  2310. pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  2311. applog(LOG_DEBUG, "Work stale due to fail only pool mismatch");
  2312. return true;
  2313. }
  2314. return false;
  2315. }
  2316. static void check_solve(struct work *work)
  2317. {
  2318. #ifndef MIPSEB
  2319. /* This segfaults on openwrt */
  2320. work->block = regeneratehash(work);
  2321. if (unlikely(work->block)) {
  2322. work->pool->solved++;
  2323. found_blocks++;
  2324. work->mandatory = true;
  2325. applog(LOG_NOTICE, "Found block for pool %d!", work->pool);
  2326. }
  2327. #endif
  2328. }
  2329. static void *submit_work_thread(void *userdata)
  2330. {
  2331. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2332. struct work *work = wc->work;
  2333. struct pool *pool = work->pool;
  2334. bool resubmit = false;
  2335. struct curl_ent *ce;
  2336. pthread_detach(pthread_self());
  2337. applog(LOG_DEBUG, "Creating extra submit work thread");
  2338. check_solve(work);
  2339. if (stale_work(work, true)) {
  2340. if (opt_submit_stale)
  2341. applog(LOG_NOTICE, "Stale share detected, submitting as user requested");
  2342. else if (pool->submit_old)
  2343. applog(LOG_NOTICE, "Stale share detected, submitting as pool requested");
  2344. else {
  2345. applog(LOG_NOTICE, "Stale share detected, discarding");
  2346. sharelog("discard", work);
  2347. total_stale++;
  2348. pool->stale_shares++;
  2349. total_diff_stale += work->work_difficulty;
  2350. pool->diff_stale += work->work_difficulty;
  2351. goto out;
  2352. }
  2353. work->stale = true;
  2354. }
  2355. if (work->stratum) {
  2356. struct stratum_share *sshare = calloc(sizeof(struct stratum_share), 1);
  2357. uint32_t *hash32 = (uint32_t *)work->hash, nonce;
  2358. char *s = alloca(1024);
  2359. char *noncehex;
  2360. memcpy(&sshare->work, work, sizeof(struct work));
  2361. /* Give the stratum share a unique id */
  2362. mutex_lock(&sshare_lock);
  2363. sshare->id = swork_id++;
  2364. HASH_ADD_INT(stratum_shares, id, sshare);
  2365. mutex_unlock(&sshare_lock);
  2366. nonce = *((uint32_t *)(work->data + 76));
  2367. noncehex = bin2hex((const unsigned char *)&nonce, 4);
  2368. sprintf(s, "{\"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\": %d, \"method\": \"mining.submit\"}",
  2369. pool->rpc_user, work->job_id, work->nonce2, work->ntime, noncehex, sshare->id);
  2370. free(noncehex);
  2371. applog(LOG_INFO, "Submitting share %08lx to pool %d", (unsigned long)(hash32[6]), pool->pool_no);
  2372. if (unlikely(!stratum_send(pool, s, strlen(s)))) {
  2373. mutex_lock(&sshare_lock);
  2374. HASH_DEL(stratum_shares, sshare);
  2375. mutex_unlock(&sshare_lock);
  2376. free(sshare);
  2377. }
  2378. goto out;
  2379. }
  2380. ce = pop_curl_entry(pool);
  2381. /* submit solution to bitcoin via JSON-RPC */
  2382. while (!submit_upstream_work(work, ce->curl, resubmit)) {
  2383. resubmit = true;
  2384. if (stale_work(work, true)) {
  2385. applog(LOG_NOTICE, "Share became stale while retrying submit, discarding");
  2386. total_stale++;
  2387. pool->stale_shares++;
  2388. total_diff_stale += work->work_difficulty;
  2389. pool->diff_stale += work->work_difficulty;
  2390. break;
  2391. }
  2392. /* pause, then restart work-request loop */
  2393. applog(LOG_INFO, "json_rpc_call failed on submit_work, retrying");
  2394. }
  2395. push_curl_entry(ce, pool);
  2396. out:
  2397. workio_cmd_free(wc);
  2398. return NULL;
  2399. }
  2400. /* We try to reuse curl handles as much as possible, but if there is already
  2401. * work queued to be submitted, we start generating extra handles to submit
  2402. * the shares to avoid ever increasing backlogs. This allows us to scale to
  2403. * any size hardware */
  2404. static bool workio_submit_work(struct workio_cmd *wc)
  2405. {
  2406. pthread_t submit_thread;
  2407. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2408. applog(LOG_ERR, "Failed to create submit_work_thread");
  2409. return false;
  2410. }
  2411. return true;
  2412. }
  2413. /* Find the pool that currently has the highest priority */
  2414. static struct pool *priority_pool(int choice)
  2415. {
  2416. struct pool *ret = NULL;
  2417. int i;
  2418. for (i = 0; i < total_pools; i++) {
  2419. struct pool *pool = pools[i];
  2420. if (pool->prio == choice) {
  2421. ret = pool;
  2422. break;
  2423. }
  2424. }
  2425. if (unlikely(!ret)) {
  2426. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2427. return pools[choice];
  2428. }
  2429. return ret;
  2430. }
  2431. void switch_pools(struct pool *selected)
  2432. {
  2433. struct pool *pool, *last_pool;
  2434. int i, pool_no, next_pool;
  2435. mutex_lock(&control_lock);
  2436. last_pool = currentpool;
  2437. pool_no = currentpool->pool_no;
  2438. /* Switch selected to pool number 0 and move the rest down */
  2439. if (selected) {
  2440. if (selected->prio != 0) {
  2441. for (i = 0; i < total_pools; i++) {
  2442. pool = pools[i];
  2443. if (pool->prio < selected->prio)
  2444. pool->prio++;
  2445. }
  2446. selected->prio = 0;
  2447. }
  2448. }
  2449. switch (pool_strategy) {
  2450. /* Both of these set to the master pool */
  2451. case POOL_BALANCE:
  2452. case POOL_FAILOVER:
  2453. case POOL_LOADBALANCE:
  2454. for (i = 0; i < total_pools; i++) {
  2455. pool = priority_pool(i);
  2456. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2457. pool_no = pool->pool_no;
  2458. break;
  2459. }
  2460. }
  2461. break;
  2462. /* Both of these simply increment and cycle */
  2463. case POOL_ROUNDROBIN:
  2464. case POOL_ROTATE:
  2465. if (selected && !selected->idle) {
  2466. pool_no = selected->pool_no;
  2467. break;
  2468. }
  2469. next_pool = pool_no;
  2470. /* Select the next alive pool */
  2471. for (i = 1; i < total_pools; i++) {
  2472. next_pool++;
  2473. if (next_pool >= total_pools)
  2474. next_pool = 0;
  2475. pool = pools[next_pool];
  2476. if (!pool->idle && pool->enabled == POOL_ENABLED) {
  2477. pool_no = next_pool;
  2478. break;
  2479. }
  2480. }
  2481. break;
  2482. default:
  2483. break;
  2484. }
  2485. currentpool = pools[pool_no];
  2486. pool = currentpool;
  2487. mutex_unlock(&control_lock);
  2488. /* Set the lagging flag to avoid pool not providing work fast enough
  2489. * messages in failover only mode since we have to get all fresh work
  2490. * as in restart_threads */
  2491. if (opt_fail_only)
  2492. pool_tset(pool, &pool->lagging);
  2493. if (pool != last_pool)
  2494. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2495. mutex_lock(&lp_lock);
  2496. pthread_cond_broadcast(&lp_cond);
  2497. mutex_unlock(&lp_lock);
  2498. }
  2499. static void discard_work(struct work *work)
  2500. {
  2501. if (!work->clone && !work->rolls && !work->mined) {
  2502. if (work->pool)
  2503. work->pool->discarded_work++;
  2504. total_discarded++;
  2505. applog(LOG_DEBUG, "Discarded work");
  2506. } else
  2507. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2508. free_work(work);
  2509. }
  2510. static void discard_stale(void)
  2511. {
  2512. struct work *work, *tmp;
  2513. int stale = 0;
  2514. mutex_lock(stgd_lock);
  2515. HASH_ITER(hh, staged_work, work, tmp) {
  2516. if (stale_work(work, false)) {
  2517. HASH_DEL(staged_work, work);
  2518. work->pool->staged--;
  2519. discard_work(work);
  2520. stale++;
  2521. }
  2522. }
  2523. mutex_unlock(stgd_lock);
  2524. if (stale) {
  2525. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2526. while (stale-- > 0)
  2527. queue_request();
  2528. }
  2529. }
  2530. /* A generic wait function for threads that poll that will wait a specified
  2531. * time tdiff waiting on the pthread conditional that is broadcast when a
  2532. * work restart is required. Returns the value of pthread_cond_timedwait
  2533. * which is zero if the condition was met or ETIMEDOUT if not.
  2534. */
  2535. int restart_wait(unsigned int mstime)
  2536. {
  2537. struct timeval now, then, tdiff;
  2538. struct timespec abstime;
  2539. int rc;
  2540. tdiff.tv_sec = mstime / 1000;
  2541. tdiff.tv_usec = mstime * 1000 - (tdiff.tv_sec * 1000000);
  2542. gettimeofday(&now, NULL);
  2543. timeradd(&now, &tdiff, &then);
  2544. abstime.tv_sec = then.tv_sec;
  2545. abstime.tv_nsec = then.tv_usec * 1000;
  2546. mutex_lock(&restart_lock);
  2547. rc = pthread_cond_timedwait(&restart_cond, &restart_lock, &abstime);
  2548. mutex_unlock(&restart_lock);
  2549. return rc;
  2550. }
  2551. static void restart_threads(void)
  2552. {
  2553. struct pool *cp = current_pool();
  2554. int i;
  2555. /* Artificially set the lagging flag to avoid pool not providing work
  2556. * fast enough messages after every long poll */
  2557. pool_tset(cp, &cp->lagging);
  2558. /* Discard staged work that is now stale */
  2559. discard_stale();
  2560. for (i = 0; i < mining_threads; i++)
  2561. thr_info[i].work_restart = true;
  2562. mutex_lock(&restart_lock);
  2563. pthread_cond_broadcast(&restart_cond);
  2564. mutex_unlock(&restart_lock);
  2565. }
  2566. static void set_curblock(char *hexstr, unsigned char *hash)
  2567. {
  2568. unsigned char hash_swap[32];
  2569. unsigned char block_hash_swap[32];
  2570. char *old_hash;
  2571. strcpy(current_block, hexstr);
  2572. swap256(hash_swap, hash);
  2573. swap256(block_hash_swap, hash+4);
  2574. /* Don't free current_hash directly to avoid dereferencing when read
  2575. * elsewhere - and update block_timeval inside the same lock */
  2576. mutex_lock(&ch_lock);
  2577. gettimeofday(&block_timeval, NULL);
  2578. old_hash = current_hash;
  2579. current_hash = bin2hex(hash_swap, 16);
  2580. free(old_hash);
  2581. old_hash = current_fullhash;
  2582. current_fullhash = bin2hex(block_hash_swap, 32);
  2583. free(old_hash);
  2584. mutex_unlock(&ch_lock);
  2585. get_timestamp(blocktime, &block_timeval);
  2586. if (unlikely(!current_hash))
  2587. quit (1, "set_curblock OOM");
  2588. applog(LOG_INFO, "New block: %s...", current_hash);
  2589. }
  2590. /* Search to see if this string is from a block that has been seen before */
  2591. static bool block_exists(char *hexstr)
  2592. {
  2593. struct block *s;
  2594. rd_lock(&blk_lock);
  2595. HASH_FIND_STR(blocks, hexstr, s);
  2596. rd_unlock(&blk_lock);
  2597. if (s)
  2598. return true;
  2599. return false;
  2600. }
  2601. /* Tests if this work is from a block that has been seen before */
  2602. static inline bool from_existing_block(struct work *work)
  2603. {
  2604. char *hexstr = bin2hex(work->data + 8, 18);
  2605. bool ret;
  2606. if (unlikely(!hexstr)) {
  2607. applog(LOG_ERR, "from_existing_block OOM");
  2608. return true;
  2609. }
  2610. ret = block_exists(hexstr);
  2611. free(hexstr);
  2612. return ret;
  2613. }
  2614. static int block_sort(struct block *blocka, struct block *blockb)
  2615. {
  2616. return blocka->block_no - blockb->block_no;
  2617. }
  2618. static bool test_work_current(struct work *work)
  2619. {
  2620. bool ret = true;
  2621. char *hexstr;
  2622. if (work->mandatory)
  2623. return ret;
  2624. hexstr = bin2hex(work->data + 8, 18);
  2625. if (unlikely(!hexstr)) {
  2626. applog(LOG_ERR, "stage_thread OOM");
  2627. return ret;
  2628. }
  2629. /* Search to see if this block exists yet and if not, consider it a
  2630. * new block and set the current block details to this one */
  2631. if (!block_exists(hexstr)) {
  2632. struct block *s = calloc(sizeof(struct block), 1);
  2633. int deleted_block = 0;
  2634. ret = false;
  2635. if (unlikely(!s))
  2636. quit (1, "test_work_current OOM");
  2637. strcpy(s->hash, hexstr);
  2638. s->block_no = new_blocks++;
  2639. wr_lock(&blk_lock);
  2640. /* Only keep the last hour's worth of blocks in memory since
  2641. * work from blocks before this is virtually impossible and we
  2642. * want to prevent memory usage from continually rising */
  2643. if (HASH_COUNT(blocks) > 6) {
  2644. struct block *oldblock;
  2645. HASH_SORT(blocks, block_sort);
  2646. oldblock = blocks;
  2647. deleted_block = oldblock->block_no;
  2648. HASH_DEL(blocks, oldblock);
  2649. free(oldblock);
  2650. }
  2651. HASH_ADD_STR(blocks, hash, s);
  2652. wr_unlock(&blk_lock);
  2653. if (deleted_block)
  2654. applog(LOG_DEBUG, "Deleted block %d from database", deleted_block);
  2655. set_curblock(hexstr, work->data);
  2656. if (unlikely(new_blocks == 1))
  2657. goto out_free;
  2658. work_block++;
  2659. if (!work->stratum) {
  2660. if (work->longpoll) {
  2661. applog(LOG_NOTICE, "LONGPOLL from pool %d detected new block",
  2662. work->pool->pool_no);
  2663. work->longpoll = false;
  2664. } else if (have_longpoll)
  2665. applog(LOG_NOTICE, "New block detected on network before longpoll");
  2666. else
  2667. applog(LOG_NOTICE, "New block detected on network");
  2668. }
  2669. restart_threads();
  2670. } else if (work->longpoll) {
  2671. work->longpoll = false;
  2672. if (work->pool == current_pool()) {
  2673. applog(LOG_NOTICE, "LONGPOLL from pool %d requested work restart",
  2674. work->pool->pool_no);
  2675. work_block++;
  2676. restart_threads();
  2677. }
  2678. }
  2679. out_free:
  2680. free(hexstr);
  2681. return ret;
  2682. }
  2683. static int tv_sort(struct work *worka, struct work *workb)
  2684. {
  2685. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2686. }
  2687. static bool work_rollable(struct work *work)
  2688. {
  2689. return (!work->clone && work->rolltime);
  2690. }
  2691. static bool hash_push(struct work *work)
  2692. {
  2693. bool rc = true;
  2694. mutex_lock(stgd_lock);
  2695. if (work_rollable(work))
  2696. staged_rollable++;
  2697. if (likely(!getq->frozen)) {
  2698. HASH_ADD_INT(staged_work, id, work);
  2699. HASH_SORT(staged_work, tv_sort);
  2700. } else
  2701. rc = false;
  2702. pthread_cond_signal(&getq->cond);
  2703. mutex_unlock(stgd_lock);
  2704. work->pool->staged++;
  2705. if (work->queued) {
  2706. work->queued = false;
  2707. dec_queued(work->pool);
  2708. }
  2709. return rc;
  2710. }
  2711. static void *stage_thread(void *userdata)
  2712. {
  2713. struct thr_info *mythr = userdata;
  2714. bool ok = true;
  2715. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2716. while (ok) {
  2717. struct work *work = NULL;
  2718. applog(LOG_DEBUG, "Popping work to stage thread");
  2719. work = tq_pop(mythr->q, NULL);
  2720. if (unlikely(!work)) {
  2721. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2722. ok = false;
  2723. break;
  2724. }
  2725. work->work_block = work_block;
  2726. test_work_current(work);
  2727. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2728. if (unlikely(!hash_push(work))) {
  2729. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2730. continue;
  2731. }
  2732. }
  2733. tq_freeze(mythr->q);
  2734. return NULL;
  2735. }
  2736. static bool stage_work(struct work *work)
  2737. {
  2738. applog(LOG_DEBUG, "Pushing work to stage thread");
  2739. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  2740. applog(LOG_ERR, "Could not tq_push work in stage_work");
  2741. return false;
  2742. }
  2743. return true;
  2744. }
  2745. #ifdef HAVE_CURSES
  2746. int curses_int(const char *query)
  2747. {
  2748. int ret;
  2749. char *cvar;
  2750. cvar = curses_input(query);
  2751. ret = atoi(cvar);
  2752. free(cvar);
  2753. return ret;
  2754. }
  2755. #endif
  2756. #ifdef HAVE_CURSES
  2757. static bool input_pool(bool live);
  2758. #endif
  2759. #ifdef HAVE_CURSES
  2760. static void display_pool_summary(struct pool *pool)
  2761. {
  2762. double efficiency = 0.0;
  2763. if (curses_active_locked()) {
  2764. wlog("Pool: %s\n", pool->rpc_url);
  2765. if (pool->solved)
  2766. wlog("SOLVED %d BLOCK%s!\n", pool->solved, pool->solved > 1 ? "S" : "");
  2767. wlog("%s own long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2768. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2769. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2770. wlog(" Accepted shares: %d\n", pool->accepted);
  2771. wlog(" Rejected shares: %d\n", pool->rejected);
  2772. wlog(" Accepted difficulty shares: %1.f\n", pool->diff_accepted);
  2773. wlog(" Rejected difficulty shares: %1.f\n", pool->diff_rejected);
  2774. if (pool->accepted || pool->rejected)
  2775. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2776. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2777. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2778. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2779. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2780. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2781. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2782. unlock_curses();
  2783. }
  2784. }
  2785. #endif
  2786. /* We can't remove the memory used for this struct pool because there may
  2787. * still be work referencing it. We just remove it from the pools list */
  2788. void remove_pool(struct pool *pool)
  2789. {
  2790. int i, last_pool = total_pools - 1;
  2791. struct pool *other;
  2792. /* Boost priority of any lower prio than this one */
  2793. for (i = 0; i < total_pools; i++) {
  2794. other = pools[i];
  2795. if (other->prio > pool->prio)
  2796. other->prio--;
  2797. }
  2798. if (pool->pool_no < last_pool) {
  2799. /* Swap the last pool for this one */
  2800. (pools[last_pool])->pool_no = pool->pool_no;
  2801. pools[pool->pool_no] = pools[last_pool];
  2802. }
  2803. /* Give it an invalid number */
  2804. pool->pool_no = total_pools;
  2805. pool->removed = true;
  2806. total_pools--;
  2807. }
  2808. /* add a mutex if this needs to be thread safe in the future */
  2809. static struct JE {
  2810. char *buf;
  2811. struct JE *next;
  2812. } *jedata = NULL;
  2813. static void json_escape_free()
  2814. {
  2815. struct JE *jeptr = jedata;
  2816. struct JE *jenext;
  2817. jedata = NULL;
  2818. while (jeptr) {
  2819. jenext = jeptr->next;
  2820. free(jeptr->buf);
  2821. free(jeptr);
  2822. jeptr = jenext;
  2823. }
  2824. }
  2825. static char *json_escape(char *str)
  2826. {
  2827. struct JE *jeptr;
  2828. char *buf, *ptr;
  2829. /* 2x is the max, may as well just allocate that */
  2830. ptr = buf = malloc(strlen(str) * 2 + 1);
  2831. jeptr = malloc(sizeof(*jeptr));
  2832. jeptr->buf = buf;
  2833. jeptr->next = jedata;
  2834. jedata = jeptr;
  2835. while (*str) {
  2836. if (*str == '\\' || *str == '"')
  2837. *(ptr++) = '\\';
  2838. *(ptr++) = *(str++);
  2839. }
  2840. *ptr = '\0';
  2841. return buf;
  2842. }
  2843. void write_config(FILE *fcfg)
  2844. {
  2845. int i;
  2846. /* Write pool values */
  2847. fputs("{\n\"pools\" : [", fcfg);
  2848. for(i = 0; i < total_pools; i++) {
  2849. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s%s%s%s\",", i > 0 ? "," : "",
  2850. pools[i]->rpc_proxy ? json_escape((char *)proxytype(pools[i]->rpc_proxytype)) : "",
  2851. pools[i]->rpc_proxy ? json_escape(pools[i]->rpc_proxy) : "",
  2852. pools[i]->rpc_proxy ? "|" : "",
  2853. json_escape(pools[i]->rpc_url));
  2854. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", json_escape(pools[i]->rpc_user));
  2855. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", json_escape(pools[i]->rpc_pass));
  2856. }
  2857. fputs("\n]\n", fcfg);
  2858. #ifdef HAVE_OPENCL
  2859. if (nDevs) {
  2860. /* Write GPU device values */
  2861. fputs(",\n\"intensity\" : \"", fcfg);
  2862. for(i = 0; i < nDevs; i++)
  2863. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  2864. fputs("\",\n\"vectors\" : \"", fcfg);
  2865. for(i = 0; i < nDevs; i++)
  2866. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2867. gpus[i].vwidth);
  2868. fputs("\",\n\"worksize\" : \"", fcfg);
  2869. for(i = 0; i < nDevs; i++)
  2870. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2871. (int)gpus[i].work_size);
  2872. fputs("\",\n\"kernel\" : \"", fcfg);
  2873. for(i = 0; i < nDevs; i++) {
  2874. fprintf(fcfg, "%s", i > 0 ? "," : "");
  2875. switch (gpus[i].kernel) {
  2876. case KL_NONE: // Shouldn't happen
  2877. break;
  2878. case KL_POCLBM:
  2879. fprintf(fcfg, "poclbm");
  2880. break;
  2881. case KL_PHATK:
  2882. fprintf(fcfg, "phatk");
  2883. break;
  2884. case KL_DIAKGCN:
  2885. fprintf(fcfg, "diakgcn");
  2886. break;
  2887. case KL_DIABLO:
  2888. fprintf(fcfg, "diablo");
  2889. break;
  2890. case KL_SCRYPT:
  2891. fprintf(fcfg, "scrypt");
  2892. break;
  2893. }
  2894. }
  2895. #ifdef USE_SCRYPT
  2896. fputs("\",\n\"lookup-gap\" : \"", fcfg);
  2897. for(i = 0; i < nDevs; i++)
  2898. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2899. (int)gpus[i].opt_lg);
  2900. fputs("\",\n\"thread-concurrency\" : \"", fcfg);
  2901. for(i = 0; i < nDevs; i++)
  2902. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2903. (int)gpus[i].opt_tc);
  2904. fputs("\",\n\"shaders\" : \"", fcfg);
  2905. for(i = 0; i < nDevs; i++)
  2906. fprintf(fcfg, "%s%d", i > 0 ? "," : "",
  2907. (int)gpus[i].shaders);
  2908. #endif
  2909. #ifdef HAVE_ADL
  2910. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  2911. for(i = 0; i < nDevs; i++)
  2912. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  2913. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  2914. for(i = 0; i < nDevs; i++)
  2915. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  2916. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  2917. for(i = 0; i < nDevs; i++)
  2918. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  2919. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  2920. for(i = 0; i < nDevs; i++)
  2921. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  2922. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  2923. for(i = 0; i < nDevs; i++)
  2924. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  2925. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  2926. for(i = 0; i < nDevs; i++)
  2927. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  2928. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  2929. for(i = 0; i < nDevs; i++)
  2930. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].cutofftemp);
  2931. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  2932. for(i = 0; i < nDevs; i++)
  2933. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  2934. fputs("\",\n\"temp-target\" : \"", fcfg);
  2935. for(i = 0; i < nDevs; i++)
  2936. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  2937. #endif
  2938. fputs("\"", fcfg);
  2939. }
  2940. #endif
  2941. #ifdef HAVE_ADL
  2942. if (opt_reorder)
  2943. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  2944. #endif
  2945. #ifdef WANT_CPUMINE
  2946. fprintf(fcfg, ",\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  2947. #endif
  2948. /* Simple bool and int options */
  2949. struct opt_table *opt;
  2950. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2951. char *p, *name = strdup(opt->names);
  2952. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  2953. if (p[1] != '-')
  2954. continue;
  2955. if (opt->type & OPT_NOARG &&
  2956. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  2957. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  2958. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  2959. if (opt->type & OPT_HASARG &&
  2960. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  2961. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2962. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2963. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  2964. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2965. }
  2966. }
  2967. /* Special case options */
  2968. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2969. if (pool_strategy == POOL_BALANCE)
  2970. fputs(",\n\"balance\" : true", fcfg);
  2971. if (pool_strategy == POOL_LOADBALANCE)
  2972. fputs(",\n\"load-balance\" : true", fcfg);
  2973. if (pool_strategy == POOL_ROUNDROBIN)
  2974. fputs(",\n\"round-robin\" : true", fcfg);
  2975. if (pool_strategy == POOL_ROTATE)
  2976. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2977. #if defined(unix)
  2978. if (opt_stderr_cmd && *opt_stderr_cmd)
  2979. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", json_escape(opt_stderr_cmd));
  2980. #endif // defined(unix)
  2981. if (opt_kernel_path && *opt_kernel_path) {
  2982. char *kpath = strdup(opt_kernel_path);
  2983. if (kpath[strlen(kpath)-1] == '/')
  2984. kpath[strlen(kpath)-1] = 0;
  2985. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", json_escape(kpath));
  2986. }
  2987. if (schedstart.enable)
  2988. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2989. if (schedstop.enable)
  2990. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2991. if (opt_socks_proxy && *opt_socks_proxy)
  2992. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", json_escape(opt_socks_proxy));
  2993. #ifdef HAVE_OPENCL
  2994. for(i = 0; i < nDevs; i++)
  2995. if (gpus[i].deven == DEV_DISABLED)
  2996. break;
  2997. if (i < nDevs)
  2998. for (i = 0; i < nDevs; i++)
  2999. if (gpus[i].deven != DEV_DISABLED)
  3000. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  3001. #endif
  3002. if (opt_api_allow)
  3003. fprintf(fcfg, ",\n\"api-allow\" : \"%s\"", json_escape(opt_api_allow));
  3004. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  3005. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", json_escape(opt_api_description));
  3006. if (opt_api_groups)
  3007. fprintf(fcfg, ",\n\"api-groups\" : \"%s\"", json_escape(opt_api_groups));
  3008. if (opt_icarus_options)
  3009. fprintf(fcfg, ",\n\"icarus-options\" : \"%s\"", json_escape(opt_icarus_options));
  3010. if (opt_icarus_timing)
  3011. fprintf(fcfg, ",\n\"icarus-timing\" : \"%s\"", json_escape(opt_icarus_timing));
  3012. fputs("\n}\n", fcfg);
  3013. json_escape_free();
  3014. }
  3015. #ifdef HAVE_CURSES
  3016. static void display_pools(void)
  3017. {
  3018. struct pool *pool;
  3019. int selected, i;
  3020. char input;
  3021. opt_loginput = true;
  3022. immedok(logwin, true);
  3023. clear_logwin();
  3024. updated:
  3025. for (i = 0; i < total_pools; i++) {
  3026. pool = pools[i];
  3027. if (pool == current_pool())
  3028. wattron(logwin, A_BOLD);
  3029. if (pool->enabled != POOL_ENABLED)
  3030. wattron(logwin, A_DIM);
  3031. wlogprint("%d: ", pool->pool_no);
  3032. switch (pool->enabled) {
  3033. case POOL_ENABLED:
  3034. wlogprint("Enabled ");
  3035. break;
  3036. case POOL_DISABLED:
  3037. wlogprint("Disabled ");
  3038. break;
  3039. case POOL_REJECTING:
  3040. wlogprint("Rejecting ");
  3041. break;
  3042. }
  3043. wlogprint("%s Priority %d: %s User:%s\n",
  3044. pool->idle? "Dead" : "Alive",
  3045. pool->prio,
  3046. pool->rpc_url, pool->rpc_user);
  3047. wattroff(logwin, A_BOLD | A_DIM);
  3048. }
  3049. retry:
  3050. wlogprint("\nCurrent pool management strategy: %s\n",
  3051. strategies[pool_strategy]);
  3052. if (pool_strategy == POOL_ROTATE)
  3053. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  3054. wlogprint("[F]ailover only %s\n", opt_fail_only ? "enabled" : "disabled");
  3055. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  3056. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  3057. wlogprint("Or press any other key to continue\n");
  3058. input = getch();
  3059. if (!strncasecmp(&input, "a", 1)) {
  3060. input_pool(true);
  3061. goto updated;
  3062. } else if (!strncasecmp(&input, "r", 1)) {
  3063. if (total_pools <= 1) {
  3064. wlogprint("Cannot remove last pool");
  3065. goto retry;
  3066. }
  3067. selected = curses_int("Select pool number");
  3068. if (selected < 0 || selected >= total_pools) {
  3069. wlogprint("Invalid selection\n");
  3070. goto retry;
  3071. }
  3072. pool = pools[selected];
  3073. if (pool == current_pool())
  3074. switch_pools(NULL);
  3075. if (pool == current_pool()) {
  3076. wlogprint("Unable to remove pool due to activity\n");
  3077. goto retry;
  3078. }
  3079. disable_pool(pool);
  3080. remove_pool(pool);
  3081. goto updated;
  3082. } else if (!strncasecmp(&input, "s", 1)) {
  3083. selected = curses_int("Select pool number");
  3084. if (selected < 0 || selected >= total_pools) {
  3085. wlogprint("Invalid selection\n");
  3086. goto retry;
  3087. }
  3088. pool = pools[selected];
  3089. enable_pool(pool);
  3090. switch_pools(pool);
  3091. goto updated;
  3092. } else if (!strncasecmp(&input, "d", 1)) {
  3093. if (enabled_pools <= 1) {
  3094. wlogprint("Cannot disable last pool");
  3095. goto retry;
  3096. }
  3097. selected = curses_int("Select pool number");
  3098. if (selected < 0 || selected >= total_pools) {
  3099. wlogprint("Invalid selection\n");
  3100. goto retry;
  3101. }
  3102. pool = pools[selected];
  3103. disable_pool(pool);
  3104. if (pool == current_pool())
  3105. switch_pools(NULL);
  3106. goto updated;
  3107. } else if (!strncasecmp(&input, "e", 1)) {
  3108. selected = curses_int("Select pool number");
  3109. if (selected < 0 || selected >= total_pools) {
  3110. wlogprint("Invalid selection\n");
  3111. goto retry;
  3112. }
  3113. pool = pools[selected];
  3114. enable_pool(pool);
  3115. if (pool->prio < current_pool()->prio)
  3116. switch_pools(pool);
  3117. goto updated;
  3118. } else if (!strncasecmp(&input, "c", 1)) {
  3119. for (i = 0; i <= TOP_STRATEGY; i++)
  3120. wlogprint("%d: %s\n", i, strategies[i]);
  3121. selected = curses_int("Select strategy number type");
  3122. if (selected < 0 || selected > TOP_STRATEGY) {
  3123. wlogprint("Invalid selection\n");
  3124. goto retry;
  3125. }
  3126. if (selected == POOL_ROTATE) {
  3127. opt_rotate_period = curses_int("Select interval in minutes");
  3128. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  3129. opt_rotate_period = 0;
  3130. wlogprint("Invalid selection\n");
  3131. goto retry;
  3132. }
  3133. }
  3134. pool_strategy = selected;
  3135. switch_pools(NULL);
  3136. goto updated;
  3137. } else if (!strncasecmp(&input, "i", 1)) {
  3138. selected = curses_int("Select pool number");
  3139. if (selected < 0 || selected >= total_pools) {
  3140. wlogprint("Invalid selection\n");
  3141. goto retry;
  3142. }
  3143. pool = pools[selected];
  3144. display_pool_summary(pool);
  3145. goto retry;
  3146. } else if (!strncasecmp(&input, "f", 1)) {
  3147. opt_fail_only ^= true;
  3148. goto updated;
  3149. } else
  3150. clear_logwin();
  3151. immedok(logwin, false);
  3152. opt_loginput = false;
  3153. }
  3154. static void display_options(void)
  3155. {
  3156. int selected;
  3157. char input;
  3158. opt_loginput = true;
  3159. immedok(logwin, true);
  3160. clear_logwin();
  3161. retry:
  3162. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  3163. 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",
  3164. opt_debug ? "on" : "off",
  3165. want_per_device_stats? "on" : "off",
  3166. opt_quiet ? "on" : "off",
  3167. opt_log_output ? "on" : "off",
  3168. opt_protocol ? "on" : "off",
  3169. opt_worktime ? "on" : "off",
  3170. opt_log_interval);
  3171. wlogprint("Select an option or any other key to return\n");
  3172. input = getch();
  3173. if (!strncasecmp(&input, "q", 1)) {
  3174. opt_quiet ^= true;
  3175. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  3176. goto retry;
  3177. } else if (!strncasecmp(&input, "v", 1)) {
  3178. opt_log_output ^= true;
  3179. if (opt_log_output)
  3180. opt_quiet = false;
  3181. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  3182. goto retry;
  3183. } else if (!strncasecmp(&input, "n", 1)) {
  3184. opt_log_output = false;
  3185. opt_debug = false;
  3186. opt_quiet = false;
  3187. opt_protocol = false;
  3188. want_per_device_stats = false;
  3189. wlogprint("Output mode reset to normal\n");
  3190. goto retry;
  3191. } else if (!strncasecmp(&input, "d", 1)) {
  3192. opt_debug ^= true;
  3193. opt_log_output = opt_debug;
  3194. if (opt_debug)
  3195. opt_quiet = false;
  3196. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  3197. goto retry;
  3198. } else if (!strncasecmp(&input, "p", 1)) {
  3199. want_per_device_stats ^= true;
  3200. opt_log_output = want_per_device_stats;
  3201. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  3202. goto retry;
  3203. } else if (!strncasecmp(&input, "r", 1)) {
  3204. opt_protocol ^= true;
  3205. if (opt_protocol)
  3206. opt_quiet = false;
  3207. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  3208. goto retry;
  3209. } else if (!strncasecmp(&input, "c", 1))
  3210. clear_logwin();
  3211. else if (!strncasecmp(&input, "l", 1)) {
  3212. selected = curses_int("Interval in seconds");
  3213. if (selected < 0 || selected > 9999) {
  3214. wlogprint("Invalid selection\n");
  3215. goto retry;
  3216. }
  3217. opt_log_interval = selected;
  3218. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  3219. goto retry;
  3220. } else if (!strncasecmp(&input, "s", 1)) {
  3221. opt_realquiet = true;
  3222. } else if (!strncasecmp(&input, "w", 1)) {
  3223. opt_worktime ^= true;
  3224. wlogprint("WorkTime details %s\n", opt_worktime ? "enabled" : "disabled");
  3225. goto retry;
  3226. } else
  3227. clear_logwin();
  3228. immedok(logwin, false);
  3229. opt_loginput = false;
  3230. }
  3231. #endif
  3232. void default_save_file(char *filename)
  3233. {
  3234. if (default_config && *default_config) {
  3235. strcpy(filename, default_config);
  3236. return;
  3237. }
  3238. #if defined(unix)
  3239. if (getenv("HOME") && *getenv("HOME")) {
  3240. strcpy(filename, getenv("HOME"));
  3241. strcat(filename, "/");
  3242. }
  3243. else
  3244. strcpy(filename, "");
  3245. strcat(filename, ".cgminer/");
  3246. mkdir(filename, 0777);
  3247. #else
  3248. strcpy(filename, "");
  3249. #endif
  3250. strcat(filename, def_conf);
  3251. }
  3252. #ifdef HAVE_CURSES
  3253. static void set_options(void)
  3254. {
  3255. int selected;
  3256. char input;
  3257. opt_loginput = true;
  3258. immedok(logwin, true);
  3259. clear_logwin();
  3260. retry:
  3261. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[E]xpiry: %d\n"
  3262. "[W]rite config file\n[C]gminer restart\n",
  3263. opt_queue, opt_scantime, opt_expiry);
  3264. wlogprint("Select an option or any other key to return\n");
  3265. input = getch();
  3266. if (!strncasecmp(&input, "q", 1)) {
  3267. selected = curses_int("Extra work items to queue");
  3268. if (selected < 0 || selected > 9999) {
  3269. wlogprint("Invalid selection\n");
  3270. goto retry;
  3271. }
  3272. opt_queue = selected;
  3273. goto retry;
  3274. } else if (!strncasecmp(&input, "s", 1)) {
  3275. selected = curses_int("Set scantime in seconds");
  3276. if (selected < 0 || selected > 9999) {
  3277. wlogprint("Invalid selection\n");
  3278. goto retry;
  3279. }
  3280. opt_scantime = selected;
  3281. goto retry;
  3282. } else if (!strncasecmp(&input, "e", 1)) {
  3283. selected = curses_int("Set expiry time in seconds");
  3284. if (selected < 0 || selected > 9999) {
  3285. wlogprint("Invalid selection\n");
  3286. goto retry;
  3287. }
  3288. opt_expiry = selected;
  3289. goto retry;
  3290. } else if (!strncasecmp(&input, "w", 1)) {
  3291. FILE *fcfg;
  3292. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3293. default_save_file(filename);
  3294. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3295. str = curses_input(prompt);
  3296. if (strcmp(str, "-1")) {
  3297. struct stat statbuf;
  3298. strcpy(filename, str);
  3299. if (!stat(filename, &statbuf)) {
  3300. wlogprint("File exists, overwrite?\n");
  3301. input = getch();
  3302. if (strncasecmp(&input, "y", 1))
  3303. goto retry;
  3304. }
  3305. }
  3306. fcfg = fopen(filename, "w");
  3307. if (!fcfg) {
  3308. wlogprint("Cannot open or create file\n");
  3309. goto retry;
  3310. }
  3311. write_config(fcfg);
  3312. fclose(fcfg);
  3313. goto retry;
  3314. } else if (!strncasecmp(&input, "c", 1)) {
  3315. wlogprint("Are you sure?\n");
  3316. input = getch();
  3317. if (!strncasecmp(&input, "y", 1))
  3318. app_restart();
  3319. else
  3320. clear_logwin();
  3321. } else
  3322. clear_logwin();
  3323. immedok(logwin, false);
  3324. opt_loginput = false;
  3325. }
  3326. static void *input_thread(void __maybe_unused *userdata)
  3327. {
  3328. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3329. if (!curses_active)
  3330. return NULL;
  3331. while (1) {
  3332. char input;
  3333. input = getch();
  3334. if (!strncasecmp(&input, "q", 1)) {
  3335. kill_work();
  3336. return NULL;
  3337. } else if (!strncasecmp(&input, "d", 1))
  3338. display_options();
  3339. else if (!strncasecmp(&input, "p", 1))
  3340. display_pools();
  3341. else if (!strncasecmp(&input, "s", 1))
  3342. set_options();
  3343. else if (have_opencl && !strncasecmp(&input, "g", 1))
  3344. manage_gpu();
  3345. if (opt_realquiet) {
  3346. disable_curses();
  3347. break;
  3348. }
  3349. }
  3350. return NULL;
  3351. }
  3352. #endif
  3353. /* This thread should not be shut down unless a problem occurs */
  3354. static void *workio_thread(void *userdata)
  3355. {
  3356. struct thr_info *mythr = userdata;
  3357. bool ok = true;
  3358. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3359. while (ok) {
  3360. struct workio_cmd *wc;
  3361. applog(LOG_DEBUG, "Popping work to work thread");
  3362. /* wait for workio_cmd sent to us, on our queue */
  3363. wc = tq_pop(mythr->q, NULL);
  3364. if (unlikely(!wc)) {
  3365. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  3366. ok = false;
  3367. break;
  3368. }
  3369. /* process workio_cmd */
  3370. switch (wc->cmd) {
  3371. case WC_GET_WORK:
  3372. ok = workio_get_work(wc);
  3373. break;
  3374. case WC_SUBMIT_WORK:
  3375. ok = workio_submit_work(wc);
  3376. break;
  3377. default:
  3378. ok = false;
  3379. break;
  3380. }
  3381. }
  3382. tq_freeze(mythr->q);
  3383. return NULL;
  3384. }
  3385. static void *api_thread(void *userdata)
  3386. {
  3387. struct thr_info *mythr = userdata;
  3388. pthread_detach(pthread_self());
  3389. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3390. api(api_thr_id);
  3391. PTH(mythr) = 0L;
  3392. return NULL;
  3393. }
  3394. void thread_reportin(struct thr_info *thr)
  3395. {
  3396. gettimeofday(&thr->last, NULL);
  3397. thr->cgpu->status = LIFE_WELL;
  3398. thr->getwork = false;
  3399. thr->cgpu->device_last_well = time(NULL);
  3400. }
  3401. static inline void thread_reportout(struct thr_info *thr)
  3402. {
  3403. thr->getwork = true;
  3404. }
  3405. static void hashmeter(int thr_id, struct timeval *diff,
  3406. unsigned long long hashes_done)
  3407. {
  3408. struct timeval temp_tv_end, total_diff;
  3409. double secs;
  3410. double local_secs;
  3411. double utility, efficiency = 0.0;
  3412. static double local_mhashes_done = 0;
  3413. static double rolling = 0;
  3414. double local_mhashes, displayed_hashes, displayed_rolling;
  3415. bool mhash_base = true;
  3416. bool showlog = false;
  3417. local_mhashes = (double)hashes_done / 1000000.0;
  3418. /* Update the last time this thread reported in */
  3419. if (thr_id >= 0) {
  3420. gettimeofday(&thr_info[thr_id].last, NULL);
  3421. thr_info[thr_id].cgpu->device_last_well = time(NULL);
  3422. }
  3423. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3424. /* So we can call hashmeter from a non worker thread */
  3425. if (thr_id >= 0) {
  3426. struct thr_info *thr = &thr_info[thr_id];
  3427. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3428. double thread_rolling = 0.0;
  3429. int i;
  3430. applog(LOG_DEBUG, "[thread %d: %llu hashes, %.1f khash/sec]",
  3431. thr_id, hashes_done, hashes_done / 1000 / secs);
  3432. /* Rolling average for each thread and each device */
  3433. decay_time(&thr->rolling, local_mhashes / secs);
  3434. for (i = 0; i < cgpu->threads; i++)
  3435. thread_rolling += cgpu->thr[i]->rolling;
  3436. mutex_lock(&hash_lock);
  3437. decay_time(&cgpu->rolling, thread_rolling);
  3438. cgpu->total_mhashes += local_mhashes;
  3439. mutex_unlock(&hash_lock);
  3440. // If needed, output detailed, per-device stats
  3441. if (want_per_device_stats) {
  3442. struct timeval now;
  3443. struct timeval elapsed;
  3444. gettimeofday(&now, NULL);
  3445. timersub(&now, &thr->cgpu->last_message_tv, &elapsed);
  3446. if (opt_log_interval <= elapsed.tv_sec) {
  3447. struct cgpu_info *cgpu = thr->cgpu;
  3448. char logline[255];
  3449. cgpu->last_message_tv = now;
  3450. get_statline(logline, cgpu);
  3451. if (!curses_active) {
  3452. printf("%s \r", logline);
  3453. fflush(stdout);
  3454. } else
  3455. applog(LOG_INFO, "%s", logline);
  3456. }
  3457. }
  3458. }
  3459. /* Totals are updated by all threads so can race without locking */
  3460. mutex_lock(&hash_lock);
  3461. gettimeofday(&temp_tv_end, NULL);
  3462. timersub(&temp_tv_end, &total_tv_end, &total_diff);
  3463. total_mhashes_done += local_mhashes;
  3464. local_mhashes_done += local_mhashes;
  3465. if (total_diff.tv_sec < opt_log_interval)
  3466. /* Only update the total every opt_log_interval seconds */
  3467. goto out_unlock;
  3468. showlog = true;
  3469. gettimeofday(&total_tv_end, NULL);
  3470. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3471. decay_time(&rolling, local_mhashes_done / local_secs);
  3472. global_hashrate = roundl(rolling) * 1000000;
  3473. timersub(&total_tv_end, &total_tv_start, &total_diff);
  3474. total_secs = (double)total_diff.tv_sec +
  3475. ((double)total_diff.tv_usec / 1000000.0);
  3476. utility = total_accepted / total_secs * 60;
  3477. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3478. displayed_hashes = total_mhashes_done / total_secs;
  3479. displayed_rolling = rolling;
  3480. if (displayed_hashes < 1) {
  3481. displayed_hashes *= 1000;
  3482. displayed_rolling *= 1000;
  3483. mhash_base = false;
  3484. }
  3485. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f %sh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.1f/m",
  3486. want_per_device_stats ? "ALL " : "",
  3487. opt_log_interval, displayed_rolling, displayed_hashes, mhash_base ? "M" : "K",
  3488. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  3489. local_mhashes_done = 0;
  3490. out_unlock:
  3491. mutex_unlock(&hash_lock);
  3492. if (showlog) {
  3493. if (!curses_active) {
  3494. printf("%s \r", statusline);
  3495. fflush(stdout);
  3496. } else
  3497. applog(LOG_INFO, "%s", statusline);
  3498. }
  3499. }
  3500. static void stratum_share_result(json_t *val, json_t *res_val,
  3501. struct stratum_share *sshare)
  3502. {
  3503. struct work *work = &sshare->work;
  3504. char hashshow[65];
  3505. uint32_t *hash32;
  3506. int intdiff;
  3507. hash32 = (uint32_t *)(work->hash);
  3508. intdiff = round(work->work_difficulty);
  3509. sprintf(hashshow, "%08lx Diff %d%s", (unsigned long)(hash32[6]), intdiff,
  3510. work->block? " BLOCK!" : "");
  3511. share_result(val, res_val, work, hashshow, false, "");
  3512. }
  3513. /* Parses stratum json responses and tries to find the id that the request
  3514. * matched to and treat it accordingly. */
  3515. static bool parse_stratum_response(char *s)
  3516. {
  3517. json_t *val = NULL, *err_val, *res_val, *id_val;
  3518. struct stratum_share *sshare;
  3519. json_error_t err;
  3520. bool ret = false;
  3521. int id;
  3522. val = JSON_LOADS(s, &err);
  3523. if (!val) {
  3524. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  3525. goto out;
  3526. }
  3527. res_val = json_object_get(val, "result");
  3528. err_val = json_object_get(val, "error");
  3529. id_val = json_object_get(val, "id");
  3530. if ((!res_val || !id_val) || (json_is_null(res_val) || json_is_null(id_val)) ||
  3531. (err_val && !json_is_null(err_val) && !id_val)) {
  3532. char *ss;
  3533. if (err_val)
  3534. ss = json_dumps(err_val, JSON_INDENT(3));
  3535. else
  3536. ss = strdup("(unknown reason)");
  3537. applog(LOG_INFO, "JSON-RPC non method decode failed: %s", ss);
  3538. free(ss);
  3539. goto out;
  3540. }
  3541. id = json_integer_value(id_val);
  3542. mutex_lock(&sshare_lock);
  3543. HASH_FIND_INT(stratum_shares, &id, sshare);
  3544. if (sshare)
  3545. HASH_DEL(stratum_shares, sshare);
  3546. mutex_unlock(&sshare_lock);
  3547. if (!sshare) {
  3548. if (json_is_true(res_val))
  3549. applog(LOG_NOTICE, "Accepted untracked stratum share");
  3550. else
  3551. applog(LOG_NOTICE, "Rejected untracked stratum share");
  3552. goto out;
  3553. }
  3554. stratum_share_result(val, res_val, sshare);
  3555. free(sshare);
  3556. ret = true;
  3557. out:
  3558. if (val)
  3559. json_decref(val);
  3560. return ret;
  3561. }
  3562. /* One stratum thread per pool that has stratum waits on the socket checking
  3563. * for new messages and for the integrity of the socket connection. We reset
  3564. * the connection based on the integrity of the receive side only as the send
  3565. * side will eventually expire data it fails to send. */
  3566. static void *stratum_thread(void *userdata)
  3567. {
  3568. struct pool *pool = (struct pool *)userdata;
  3569. pthread_detach(pthread_self());
  3570. while (42) {
  3571. fd_set rd;
  3572. char *s;
  3573. FD_ZERO(&rd);
  3574. FD_SET(pool->sock, &rd);
  3575. if (select(pool->sock + 1, &rd, NULL, NULL, NULL) < 0) {
  3576. pool->stratum_active = pool->stratum_auth = false;
  3577. applog(LOG_WARNING, "Stratum connection to pool %d interrupted", pool->pool_no);
  3578. pool->getfail_occasions++;
  3579. total_go++;
  3580. while (!initiate_stratum(pool) || !auth_stratum(pool)) {
  3581. if (!pool->idle)
  3582. pool_died(pool);
  3583. if (pool->removed)
  3584. goto out;
  3585. sleep(5);
  3586. }
  3587. }
  3588. s = recv_line(pool->sock);
  3589. if (unlikely(!s))
  3590. continue;
  3591. if (!parse_method(pool, s) && !parse_stratum_response(s))
  3592. applog(LOG_INFO, "Unknown stratum msg: %s", s);
  3593. free(s);
  3594. if (pool->swork.clean) {
  3595. struct work work;
  3596. /* Generate a single work item to update the current
  3597. * block database */
  3598. pool->swork.clean = false;
  3599. gen_stratum_work(pool, &work);
  3600. if (test_work_current(&work)) {
  3601. /* Only accept a work restart if this stratum
  3602. * connection is from the current pool */
  3603. if (pool == current_pool()) {
  3604. restart_threads();
  3605. applog(LOG_NOTICE, "Stratum from pool %d requested work restart", pool->pool_no);
  3606. }
  3607. } else
  3608. applog(LOG_NOTICE, "Stratum from pool %d detected new block", pool->pool_no);
  3609. }
  3610. if (unlikely(pool->removed)) {
  3611. CLOSESOCKET(pool->sock);
  3612. goto out;
  3613. }
  3614. }
  3615. out:
  3616. return NULL;
  3617. }
  3618. static void init_stratum_thread(struct pool *pool)
  3619. {
  3620. if (unlikely(pthread_create(&pool->stratum_thread, NULL, stratum_thread, (void *)pool)))
  3621. quit(1, "Failed to create stratum thread");
  3622. }
  3623. static void *longpoll_thread(void *userdata);
  3624. static bool pool_active(struct pool *pool, bool pinging)
  3625. {
  3626. struct timeval tv_getwork, tv_getwork_reply;
  3627. bool ret = false;
  3628. json_t *val;
  3629. CURL *curl;
  3630. int rolltime;
  3631. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3632. /* This is the central point we activate stratum when we can */
  3633. retry_stratum:
  3634. if (pool->has_stratum) {
  3635. if ((!pool->stratum_active || pinging) && !initiate_stratum(pool))
  3636. return false;
  3637. if (!pool->stratum_auth) {
  3638. if (!auth_stratum(pool))
  3639. return false;
  3640. /* We create the stratum thread for each pool just
  3641. * after successful authorisation */
  3642. init_stratum_thread(pool);
  3643. return true;
  3644. }
  3645. return true;
  3646. }
  3647. curl = curl_easy_init();
  3648. if (unlikely(!curl)) {
  3649. applog(LOG_ERR, "CURL initialisation failed");
  3650. return false;
  3651. }
  3652. gettimeofday(&tv_getwork, NULL);
  3653. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3654. true, false, &rolltime, pool, false);
  3655. gettimeofday(&tv_getwork_reply, NULL);
  3656. /* Detect if a http getwork pool has an X-Stratum header at startup,
  3657. * and if so, switch to that in preference to getwork */
  3658. if (unlikely(pool->stratum_url)) {
  3659. applog(LOG_NOTICE, "Switching pool %d %s to %s", pool->pool_no, pool->rpc_url, pool->stratum_url);
  3660. pool->has_stratum = true;
  3661. pool->rpc_url = pool->stratum_url;
  3662. /* pool->stratum_url will be set again in extract_sockaddr */
  3663. pool->stratum_url = NULL;
  3664. extract_sockaddr(pool, pool->rpc_url);
  3665. curl_easy_cleanup(curl);
  3666. goto retry_stratum;
  3667. }
  3668. if (val) {
  3669. struct work *work = make_work();
  3670. bool rc;
  3671. rc = work_decode(json_object_get(val, "result"), work);
  3672. if (rc) {
  3673. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3674. pool->pool_no, pool->rpc_url);
  3675. work->pool = pool;
  3676. work->rolltime = rolltime;
  3677. memcpy(&(work->tv_getwork), &tv_getwork, sizeof(struct timeval));
  3678. memcpy(&(work->tv_getwork_reply), &tv_getwork_reply, sizeof(struct timeval));
  3679. work->getwork_mode = GETWORK_MODE_TESTPOOL;
  3680. calc_diff(work, 0);
  3681. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3682. tq_push(thr_info[stage_thr_id].q, work);
  3683. total_getworks++;
  3684. pool->getwork_requested++;
  3685. ret = true;
  3686. gettimeofday(&pool->tv_idle, NULL);
  3687. } else {
  3688. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3689. pool->pool_no, pool->rpc_url);
  3690. free_work(work);
  3691. }
  3692. json_decref(val);
  3693. if (pool->lp_url)
  3694. goto out;
  3695. /* Decipher the longpoll URL, if any, and store it in ->lp_url */
  3696. if (pool->hdr_path) {
  3697. char *copy_start, *hdr_path;
  3698. bool need_slash = false;
  3699. hdr_path = pool->hdr_path;
  3700. if (strstr(hdr_path, "://")) {
  3701. pool->lp_url = hdr_path;
  3702. hdr_path = NULL;
  3703. } else {
  3704. /* absolute path, on current server */
  3705. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3706. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3707. need_slash = true;
  3708. pool->lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3709. if (!pool->lp_url) {
  3710. applog(LOG_ERR, "Malloc failure in pool_active");
  3711. return false;
  3712. }
  3713. sprintf(pool->lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3714. }
  3715. } else
  3716. pool->lp_url = NULL;
  3717. if (!pool->lp_started) {
  3718. pool->lp_started = true;
  3719. if (unlikely(pthread_create(&pool->longpoll_thread, NULL, longpoll_thread, (void *)pool)))
  3720. quit(1, "Failed to create pool longpoll thread");
  3721. }
  3722. } else {
  3723. /* If we failed to parse a getwork, this could be a stratum
  3724. * url without the prefix stratum+tcp:// so let's check it */
  3725. if (initiate_stratum(pool)) {
  3726. pool->has_stratum = true;
  3727. goto retry_stratum;
  3728. }
  3729. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3730. pool->pool_no, pool->rpc_url);
  3731. if (!pinging)
  3732. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  3733. }
  3734. out:
  3735. curl_easy_cleanup(curl);
  3736. return ret;
  3737. }
  3738. static inline int cp_prio(void)
  3739. {
  3740. int prio;
  3741. mutex_lock(&control_lock);
  3742. prio = currentpool->prio;
  3743. mutex_unlock(&control_lock);
  3744. return prio;
  3745. }
  3746. static void pool_resus(struct pool *pool)
  3747. {
  3748. applog(LOG_WARNING, "Pool %d %s alive", pool->pool_no, pool->rpc_url);
  3749. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3750. switch_pools(NULL);
  3751. }
  3752. static bool queue_request(void)
  3753. {
  3754. int ts, tq, maxq = opt_queue + mining_threads;
  3755. struct pool *pool, *cp;
  3756. struct workio_cmd *wc;
  3757. bool lagging;
  3758. ts = total_staged();
  3759. tq = global_queued();
  3760. if (ts && ts + tq >= maxq)
  3761. return true;
  3762. cp = current_pool();
  3763. lagging = !opt_fail_only && cp->lagging && !ts && cp->queued >= maxq;
  3764. if (!lagging && cp->staged + cp->queued >= maxq)
  3765. return true;
  3766. pool = select_pool(lagging);
  3767. if (pool->staged + pool->queued >= maxq)
  3768. return true;
  3769. inc_queued(pool);
  3770. /* fill out work request message */
  3771. wc = calloc(1, sizeof(*wc));
  3772. if (unlikely(!wc)) {
  3773. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3774. return false;
  3775. }
  3776. wc->cmd = WC_GET_WORK;
  3777. wc->pool = pool;
  3778. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3779. /* send work request to workio thread */
  3780. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3781. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3782. workio_cmd_free(wc);
  3783. return false;
  3784. }
  3785. return true;
  3786. }
  3787. static struct work *hash_pop(const struct timespec *abstime)
  3788. {
  3789. struct work *work = NULL, *tmp;
  3790. int rc = 0, hc;
  3791. mutex_lock(stgd_lock);
  3792. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  3793. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3794. hc = HASH_COUNT(staged_work);
  3795. if (likely(hc)) {
  3796. /* Find clone work if possible, to allow masters to be reused */
  3797. if (hc > staged_rollable) {
  3798. HASH_ITER(hh, staged_work, work, tmp) {
  3799. if (!work_rollable(work))
  3800. break;
  3801. }
  3802. } else
  3803. work = staged_work;
  3804. HASH_DEL(staged_work, work);
  3805. work->pool->staged--;
  3806. if (work_rollable(work))
  3807. staged_rollable--;
  3808. }
  3809. mutex_unlock(stgd_lock);
  3810. queue_request();
  3811. return work;
  3812. }
  3813. static bool reuse_work(struct work *work, struct pool *pool)
  3814. {
  3815. if (pool->has_stratum) {
  3816. applog(LOG_DEBUG, "Reusing stratum work");
  3817. gen_stratum_work(pool, work);;
  3818. return true;
  3819. }
  3820. if (can_roll(work) && should_roll(work)) {
  3821. roll_work(work);
  3822. return true;
  3823. }
  3824. return false;
  3825. }
  3826. /* Clones work by rolling it if possible, and returning a clone instead of the
  3827. * original work item which gets staged again to possibly be rolled again in
  3828. * the future */
  3829. static struct work *clone_work(struct work *work)
  3830. {
  3831. int mrs = mining_threads + opt_queue - total_staged();
  3832. struct work *work_clone;
  3833. bool cloned;
  3834. if (mrs < 1)
  3835. return work;
  3836. cloned = false;
  3837. work_clone = make_clone(work);
  3838. while (mrs-- > 0 && can_roll(work) && should_roll(work)) {
  3839. applog(LOG_DEBUG, "Pushing rolled converted work to stage thread");
  3840. if (unlikely(!stage_work(work_clone))) {
  3841. cloned = false;
  3842. break;
  3843. }
  3844. roll_work(work);
  3845. work_clone = make_clone(work);
  3846. /* Roll it again to prevent duplicates should this be used
  3847. * directly later on */
  3848. roll_work(work);
  3849. cloned = true;
  3850. }
  3851. if (cloned) {
  3852. stage_work(work);
  3853. return work_clone;
  3854. }
  3855. free_work(work_clone);
  3856. return work;
  3857. }
  3858. static void gen_hash(unsigned char *data, unsigned char *hash, int len)
  3859. {
  3860. unsigned char hash1[33];
  3861. sha2(data, len, hash1, false);
  3862. sha2(hash1, 32, hash, false);
  3863. }
  3864. static void set_work_target(struct work *work, int diff)
  3865. {
  3866. unsigned char rtarget[33], target[33];
  3867. uint8_t *data8;
  3868. int i, j;
  3869. /* Scale to any diff by setting number of bits according to diff */
  3870. hex2bin(rtarget, "00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 32);
  3871. data8 = (uint8_t *)(rtarget + 4);
  3872. for (i = 1, j = 0; i < diff; i++, j++) {
  3873. int byte = j / 8;
  3874. int bit = j % 8;
  3875. data8[byte] &= ~(128 >> bit);
  3876. }
  3877. swab256(target, rtarget);
  3878. if (opt_debug) {
  3879. char *htarget = bin2hex(target, 32);
  3880. if (likely(htarget)) {
  3881. applog(LOG_DEBUG, "Generated target %s", htarget);
  3882. free(htarget);
  3883. }
  3884. }
  3885. memcpy(work->target, target, 256);
  3886. }
  3887. static void gen_stratum_work(struct pool *pool, struct work *work)
  3888. {
  3889. unsigned char *coinbase, merkle_root[33], merkle_sha[65], *merkle_hash;
  3890. char header[257], hash1[129], *nonce2;
  3891. int len, cb1_len, n1_len, cb2_len, i;
  3892. uint32_t *data32, *swap32;
  3893. mutex_lock(&pool->pool_lock);
  3894. /* Generate coinbase */
  3895. nonce2 = bin2hex((const unsigned char *)&pool->nonce2, pool->n2size);
  3896. if (unlikely(!nonce2))
  3897. quit(1, "Failed to convert nonce2 in gen_stratum_work");
  3898. pool->nonce2++;
  3899. cb1_len = strlen(pool->swork.coinbase1) / 2;
  3900. n1_len = strlen(pool->nonce1) / 2;
  3901. cb2_len = strlen(pool->swork.coinbase2) / 2;
  3902. len = cb1_len + n1_len + pool->n2size + cb2_len;
  3903. coinbase = alloca(len + 1);
  3904. hex2bin(coinbase, pool->swork.coinbase1, cb1_len);
  3905. hex2bin(coinbase + cb1_len, pool->nonce1, n1_len);
  3906. hex2bin(coinbase + cb1_len + n1_len, nonce2, pool->n2size);
  3907. hex2bin(coinbase + cb1_len + n1_len + pool->n2size, pool->swork.coinbase2, cb2_len);
  3908. /* Generate merkle root */
  3909. gen_hash(coinbase, merkle_root, len);
  3910. memcpy(merkle_sha, merkle_root, 32);
  3911. for (i = 0; i < pool->swork.merkles; i++) {
  3912. unsigned char merkle_bin[33];
  3913. hex2bin(merkle_bin, pool->swork.merkle[i], 32);
  3914. memcpy(merkle_sha + 32, merkle_bin, 32);
  3915. gen_hash(merkle_sha, merkle_root, 64);
  3916. memcpy(merkle_sha, merkle_root, 32);
  3917. }
  3918. data32 = (uint32_t *)merkle_sha;
  3919. swap32 = (uint32_t *)merkle_root;
  3920. for (i = 0; i < 32 / 4; i++)
  3921. swap32[i] = swab32(data32[i]);
  3922. merkle_hash = (unsigned char *)bin2hex((const unsigned char *)merkle_root, 32);
  3923. if (unlikely(!merkle_hash))
  3924. quit(1, "Failed to conver merkle_hash in gen_stratum_work");
  3925. sprintf(header, "%s", pool->swork.bbversion);
  3926. strcat(header, pool->swork.prev_hash);
  3927. strcat(header, (char *)merkle_hash);
  3928. strcat(header, pool->swork.ntime);
  3929. strcat(header, pool->swork.nbit);
  3930. strcat(header, "00000000"); /* nonce */
  3931. strcat(header, "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000");
  3932. /* Store the stratum work diff to check it still matches the pool's
  3933. * stratum diff when submitting shares */
  3934. work->sdiff = pool->swork.diff;
  3935. /* Copy parameters required for share submission */
  3936. sprintf(work->job_id, "%s", pool->swork.job_id);
  3937. sprintf(work->nonce2, "%s", nonce2);
  3938. sprintf(work->ntime, "%s", pool->swork.ntime);
  3939. free(nonce2);
  3940. mutex_unlock(&pool->pool_lock);
  3941. applog(LOG_DEBUG, "Generated stratum merkle %s", merkle_hash);
  3942. applog(LOG_DEBUG, "Generated stratum header %s", header);
  3943. free(merkle_hash);
  3944. /* Convert hex data to binary data for work */
  3945. if (unlikely(!hex2bin(work->data, header, 128)))
  3946. quit(1, "Failed to convert header to data in gen_stratum_work");
  3947. calc_midstate(work);
  3948. sprintf(hash1, "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000");
  3949. if (unlikely(!hex2bin(work->hash1, hash1, 64)))
  3950. quit(1, "Failed to convert hash1 in gen_stratum_work");
  3951. set_work_target(work, work->sdiff);
  3952. work->pool = pool;
  3953. work->stratum = true;
  3954. work->blk.nonce = 0;
  3955. work->id = total_work++;
  3956. work->longpoll = false;
  3957. work->getwork_mode = GETWORK_MODE_STRATUM;
  3958. work->work_block = work_block;
  3959. calc_diff(work, work->sdiff);
  3960. gettimeofday(&work->tv_staged, NULL);
  3961. }
  3962. static void get_work(struct work *work, struct thr_info *thr, const int thr_id)
  3963. {
  3964. struct timespec abstime = {0, 0};
  3965. struct work *work_heap;
  3966. struct timeval now;
  3967. struct pool *pool;
  3968. /* Tell the watchdog thread this thread is waiting on getwork and
  3969. * should not be restarted */
  3970. thread_reportout(thr);
  3971. if (opt_benchmark) {
  3972. get_benchmark_work(work);
  3973. goto out;
  3974. }
  3975. retry:
  3976. pool = current_pool();
  3977. if (reuse_work(work, pool))
  3978. goto out;
  3979. if (!pool->lagging && !total_staged() && global_queued() >= mining_threads + opt_queue) {
  3980. struct cgpu_info *cgpu = thr->cgpu;
  3981. bool stalled = true;
  3982. int i;
  3983. /* Check to see if all the threads on the device that called
  3984. * get_work are waiting on work and only consider the pool
  3985. * lagging if true */
  3986. for (i = 0; i < cgpu->threads; i++) {
  3987. if (!cgpu->thr[i]->getwork) {
  3988. stalled = false;
  3989. break;
  3990. }
  3991. }
  3992. if (stalled && !pool_tset(pool, &pool->lagging)) {
  3993. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  3994. pool->getfail_occasions++;
  3995. total_go++;
  3996. }
  3997. }
  3998. gettimeofday(&now, NULL);
  3999. abstime.tv_sec = now.tv_sec + 60;
  4000. applog(LOG_DEBUG, "Popping work from get queue to get work");
  4001. /* wait for 1st response, or get cached response */
  4002. work_heap = hash_pop(&abstime);
  4003. if (unlikely(!work_heap)) {
  4004. /* Attempt to switch pools if this one times out */
  4005. pool_died(pool);
  4006. goto retry;
  4007. }
  4008. if (stale_work(work_heap, false)) {
  4009. discard_work(work_heap);
  4010. goto retry;
  4011. }
  4012. pool = work_heap->pool;
  4013. /* If we make it here we have succeeded in getting fresh work */
  4014. if (!work_heap->mined) {
  4015. /* Only clear the lagging flag if we are staging them at a
  4016. * rate faster then we're using them */
  4017. if (pool->lagging && total_staged())
  4018. pool_tclear(pool, &pool->lagging);
  4019. if (pool_tclear(pool, &pool->idle))
  4020. pool_resus(pool);
  4021. }
  4022. memcpy(work, work_heap, sizeof(struct work));
  4023. free_work(work_heap);
  4024. out:
  4025. work->thr_id = thr_id;
  4026. thread_reportin(thr);
  4027. work->mined = true;
  4028. }
  4029. bool submit_work_sync(struct thr_info *thr, const struct work *work_in, struct timeval *tv_work_found)
  4030. {
  4031. struct workio_cmd *wc;
  4032. /* fill out work request message */
  4033. wc = calloc(1, sizeof(*wc));
  4034. if (unlikely(!wc)) {
  4035. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  4036. return false;
  4037. }
  4038. wc->work = make_work();
  4039. wc->cmd = WC_SUBMIT_WORK;
  4040. wc->thr = thr;
  4041. memcpy(wc->work, work_in, sizeof(*work_in));
  4042. if (tv_work_found)
  4043. memcpy(&(wc->work->tv_work_found), tv_work_found, sizeof(struct timeval));
  4044. applog(LOG_DEBUG, "Pushing submit work to work thread");
  4045. /* send solution to workio thread */
  4046. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  4047. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  4048. goto err_out;
  4049. }
  4050. return true;
  4051. err_out:
  4052. workio_cmd_free(wc);
  4053. return false;
  4054. }
  4055. static bool hashtest(struct thr_info *thr, struct work *work)
  4056. {
  4057. uint32_t *data32 = (uint32_t *)(work->data);
  4058. unsigned char swap[128];
  4059. uint32_t *swap32 = (uint32_t *)swap;
  4060. unsigned char hash1[32];
  4061. unsigned char hash2[32];
  4062. uint32_t *hash2_32 = (uint32_t *)hash2;
  4063. struct pool *pool = work->pool;
  4064. int i, diff;
  4065. for (i = 0; i < 80 / 4; i++)
  4066. swap32[i] = swab32(data32[i]);
  4067. sha2(swap, 80, hash1, false);
  4068. sha2(hash1, 32, hash2, false);
  4069. for (i = 0; i < 32 / 4; i++)
  4070. hash2_32[i] = swab32(hash2_32[i]);
  4071. memcpy((void*)work->hash, hash2, 32);
  4072. if (hash2_32[7] != 0) {
  4073. applog(LOG_WARNING, "%s%d: invalid nonce - HW error",
  4074. thr->cgpu->api->name, thr->cgpu->device_id);
  4075. hw_errors++;
  4076. thr->cgpu->hw_errors++;
  4077. return false;
  4078. }
  4079. if (work->stratum) {
  4080. mutex_lock(&pool->pool_lock);
  4081. diff = pool->swork.diff;
  4082. mutex_unlock(&pool->pool_lock);
  4083. if (unlikely(work->sdiff != diff)) {
  4084. applog(LOG_DEBUG, "Share needs retargetting to match pool");
  4085. set_work_target(work, diff);
  4086. }
  4087. }
  4088. bool test = fulltest(work->hash, work->target);
  4089. if (!test)
  4090. applog(LOG_INFO, "Share below target");
  4091. return test;
  4092. }
  4093. static bool test_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4094. {
  4095. if (opt_scrypt) {
  4096. uint32_t *work_nonce = (uint32_t *)(work->data + 64 + 12);
  4097. *work_nonce = nonce;
  4098. return true;
  4099. }
  4100. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  4101. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  4102. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  4103. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  4104. return hashtest(thr, work);
  4105. }
  4106. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  4107. {
  4108. struct timeval tv_work_found;
  4109. gettimeofday(&tv_work_found, NULL);
  4110. total_diff1++;
  4111. thr->cgpu->diff1++;
  4112. work->pool->diff1++;
  4113. /* Do one last check before attempting to submit the work */
  4114. /* Side effect: sets work->data for us */
  4115. if (!test_nonce(thr, work, nonce))
  4116. return true;
  4117. return submit_work_sync(thr, work, &tv_work_found);
  4118. }
  4119. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  4120. {
  4121. if (wdiff->tv_sec > opt_scantime ||
  4122. work->blk.nonce >= MAXTHREADS - hashes ||
  4123. hashes >= 0xfffffffe ||
  4124. stale_work(work, false))
  4125. return true;
  4126. return false;
  4127. }
  4128. static void mt_disable(struct thr_info *mythr, const int thr_id,
  4129. struct device_api *api)
  4130. {
  4131. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4132. mythr->rolling = mythr->cgpu->rolling = 0;
  4133. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  4134. thread_reportout(mythr);
  4135. do {
  4136. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4137. } while (mythr->pause);
  4138. thread_reportin(mythr);
  4139. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4140. if (api->thread_enable)
  4141. api->thread_enable(mythr);
  4142. }
  4143. void *miner_thread(void *userdata)
  4144. {
  4145. struct thr_info *mythr = userdata;
  4146. const int thr_id = mythr->id;
  4147. struct cgpu_info *cgpu = mythr->cgpu;
  4148. struct device_api *api = cgpu->api;
  4149. struct cgminer_stats *dev_stats = &(cgpu->cgminer_stats);
  4150. struct cgminer_stats *pool_stats;
  4151. struct timeval getwork_start;
  4152. /* Try to cycle approximately 5 times before each log update */
  4153. const long cycle = opt_log_interval / 5 ? : 1;
  4154. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  4155. struct timeval diff, sdiff, wdiff = {0, 0};
  4156. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  4157. int64_t hashes_done = 0;
  4158. int64_t hashes;
  4159. struct work *work = make_work();
  4160. const bool primary = (!mythr->device_thread) || mythr->primary_thread;
  4161. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4162. gettimeofday(&getwork_start, NULL);
  4163. if (api->thread_init && !api->thread_init(mythr)) {
  4164. cgpu->device_last_not_well = time(NULL);
  4165. cgpu->device_not_well_reason = REASON_THREAD_FAIL_INIT;
  4166. cgpu->thread_fail_init_count++;
  4167. goto out;
  4168. }
  4169. thread_reportout(mythr);
  4170. applog(LOG_DEBUG, "Popping ping in miner thread");
  4171. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  4172. sdiff.tv_sec = sdiff.tv_usec = 0;
  4173. gettimeofday(&tv_lastupdate, NULL);
  4174. while (1) {
  4175. mythr->work_restart = false;
  4176. if (api->free_work && likely(work->pool))
  4177. api->free_work(mythr, work);
  4178. get_work(work, mythr, thr_id);
  4179. cgpu->new_work = true;
  4180. gettimeofday(&tv_workstart, NULL);
  4181. work->blk.nonce = 0;
  4182. cgpu->max_hashes = 0;
  4183. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  4184. applog(LOG_ERR, "work prepare failed, exiting "
  4185. "mining thread %d", thr_id);
  4186. break;
  4187. }
  4188. do {
  4189. gettimeofday(&tv_start, NULL);
  4190. timersub(&tv_start, &getwork_start, &getwork_start);
  4191. timeradd(&getwork_start,
  4192. &(dev_stats->getwork_wait),
  4193. &(dev_stats->getwork_wait));
  4194. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_max), >)) {
  4195. dev_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4196. dev_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4197. }
  4198. if (timercmp(&getwork_start, &(dev_stats->getwork_wait_min), <)) {
  4199. dev_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4200. dev_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4201. }
  4202. dev_stats->getwork_calls++;
  4203. pool_stats = &(work->pool->cgminer_stats);
  4204. timeradd(&getwork_start,
  4205. &(pool_stats->getwork_wait),
  4206. &(pool_stats->getwork_wait));
  4207. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_max), >)) {
  4208. pool_stats->getwork_wait_max.tv_sec = getwork_start.tv_sec;
  4209. pool_stats->getwork_wait_max.tv_usec = getwork_start.tv_usec;
  4210. }
  4211. if (timercmp(&getwork_start, &(pool_stats->getwork_wait_min), <)) {
  4212. pool_stats->getwork_wait_min.tv_sec = getwork_start.tv_sec;
  4213. pool_stats->getwork_wait_min.tv_usec = getwork_start.tv_usec;
  4214. }
  4215. pool_stats->getwork_calls++;
  4216. gettimeofday(&(work->tv_work_start), NULL);
  4217. thread_reportin(mythr);
  4218. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  4219. thread_reportin(mythr);
  4220. gettimeofday(&getwork_start, NULL);
  4221. if (unlikely(hashes == -1)) {
  4222. applog(LOG_ERR, "%s %d failure, disabling!", api->name, cgpu->device_id);
  4223. cgpu->deven = DEV_DISABLED;
  4224. cgpu->device_last_not_well = time(NULL);
  4225. cgpu->device_not_well_reason = REASON_THREAD_ZERO_HASH;
  4226. cgpu->thread_zero_hash_count++;
  4227. mt_disable(mythr, thr_id, api);
  4228. }
  4229. hashes_done += hashes;
  4230. if (hashes > cgpu->max_hashes)
  4231. cgpu->max_hashes = hashes;
  4232. gettimeofday(&tv_end, NULL);
  4233. timersub(&tv_end, &tv_start, &diff);
  4234. sdiff.tv_sec += diff.tv_sec;
  4235. sdiff.tv_usec += diff.tv_usec;
  4236. if (sdiff.tv_usec > 1000000) {
  4237. ++sdiff.tv_sec;
  4238. sdiff.tv_usec -= 1000000;
  4239. }
  4240. timersub(&tv_end, &tv_workstart, &wdiff);
  4241. if (unlikely((long)sdiff.tv_sec < cycle)) {
  4242. int mult;
  4243. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  4244. continue;
  4245. mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  4246. mult *= cycle;
  4247. if (max_nonce > (0xffffffff * 0x400) / mult)
  4248. max_nonce = 0xffffffff;
  4249. else
  4250. max_nonce = (max_nonce * mult) / 0x400;
  4251. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work)
  4252. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  4253. else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work)
  4254. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  4255. timersub(&tv_end, &tv_lastupdate, &diff);
  4256. if (diff.tv_sec >= opt_log_interval) {
  4257. hashmeter(thr_id, &diff, hashes_done);
  4258. hashes_done = 0;
  4259. tv_lastupdate = tv_end;
  4260. }
  4261. if (unlikely(mythr->work_restart)) {
  4262. /* Apart from device_thread 0, we stagger the
  4263. * starting of every next thread to try and get
  4264. * all devices busy before worrying about
  4265. * getting work for their extra threads */
  4266. if (!primary) {
  4267. struct timespec rgtp;
  4268. rgtp.tv_sec = 0;
  4269. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  4270. nanosleep(&rgtp, NULL);
  4271. }
  4272. break;
  4273. }
  4274. if (unlikely(mythr->pause || cgpu->deven != DEV_ENABLED))
  4275. mt_disable(mythr, thr_id, api);
  4276. sdiff.tv_sec = sdiff.tv_usec = 0;
  4277. } while (!abandon_work(work, &wdiff, cgpu->max_hashes));
  4278. }
  4279. out:
  4280. if (api->thread_shutdown)
  4281. api->thread_shutdown(mythr);
  4282. thread_reportin(mythr);
  4283. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  4284. tq_freeze(mythr->q);
  4285. return NULL;
  4286. }
  4287. enum {
  4288. STAT_SLEEP_INTERVAL = 1,
  4289. STAT_CTR_INTERVAL = 10000000,
  4290. FAILURE_INTERVAL = 30,
  4291. };
  4292. /* Stage another work item from the work returned in a longpoll */
  4293. static void convert_to_work(json_t *val, int rolltime, struct pool *pool, struct timeval *tv_lp, struct timeval *tv_lp_reply)
  4294. {
  4295. struct work *work;
  4296. bool rc;
  4297. work = make_work();
  4298. rc = work_decode(json_object_get(val, "result"), work);
  4299. if (unlikely(!rc)) {
  4300. applog(LOG_ERR, "Could not convert longpoll data to work");
  4301. free_work(work);
  4302. return;
  4303. }
  4304. work->pool = pool;
  4305. work->rolltime = rolltime;
  4306. work->longpoll = true;
  4307. memcpy(&(work->tv_getwork), tv_lp, sizeof(struct timeval));
  4308. memcpy(&(work->tv_getwork_reply), tv_lp_reply, sizeof(struct timeval));
  4309. work->getwork_mode = GETWORK_MODE_LP;
  4310. calc_diff(work, 0);
  4311. if (pool->enabled == POOL_REJECTING)
  4312. work->mandatory = true;
  4313. /* We'll be checking this work item twice, but we already know it's
  4314. * from a new block so explicitly force the new block detection now
  4315. * rather than waiting for it to hit the stage thread. This also
  4316. * allows testwork to know whether LP discovered the block or not. */
  4317. test_work_current(work);
  4318. /* Don't use backup LPs as work if we have failover-only enabled. Use
  4319. * the longpoll work from a pool that has been rejecting shares as a
  4320. * way to detect when the pool has recovered.
  4321. */
  4322. if (pool != current_pool() && opt_fail_only && pool->enabled != POOL_REJECTING) {
  4323. free_work(work);
  4324. return;
  4325. }
  4326. work = clone_work(work);
  4327. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  4328. if (unlikely(!stage_work(work)))
  4329. free_work(work);
  4330. else
  4331. applog(LOG_DEBUG, "Converted longpoll data to work");
  4332. }
  4333. /* If we want longpoll, enable it for the chosen default pool, or, if
  4334. * the pool does not support longpoll, find the first one that does
  4335. * and use its longpoll support */
  4336. static struct pool *select_longpoll_pool(struct pool *cp)
  4337. {
  4338. int i;
  4339. if (cp->hdr_path)
  4340. return cp;
  4341. for (i = 0; i < total_pools; i++) {
  4342. struct pool *pool = pools[i];
  4343. if (pool->hdr_path)
  4344. return pool;
  4345. }
  4346. return NULL;
  4347. }
  4348. /* This will make the longpoll thread wait till it's the current pool, or it
  4349. * has been flagged as rejecting, before attempting to open any connections.
  4350. */
  4351. static void wait_lpcurrent(struct pool *pool)
  4352. {
  4353. if (pool->enabled == POOL_REJECTING || pool_strategy == POOL_LOADBALANCE || pool_strategy == POOL_BALANCE)
  4354. return;
  4355. while (pool != current_pool() && pool_strategy != POOL_LOADBALANCE && pool_strategy != POOL_BALANCE) {
  4356. mutex_lock(&lp_lock);
  4357. pthread_cond_wait(&lp_cond, &lp_lock);
  4358. mutex_unlock(&lp_lock);
  4359. }
  4360. }
  4361. static void *longpoll_thread(void *userdata)
  4362. {
  4363. struct pool *cp = (struct pool *)userdata;
  4364. /* This *pool is the source of the actual longpoll, not the pool we've
  4365. * tied it to */
  4366. struct pool *pool = NULL;
  4367. struct timeval start, reply, end;
  4368. CURL *curl = NULL;
  4369. int failures = 0;
  4370. int rolltime;
  4371. curl = curl_easy_init();
  4372. if (unlikely(!curl)) {
  4373. applog(LOG_ERR, "CURL initialisation failed");
  4374. goto out;
  4375. }
  4376. retry_pool:
  4377. pool = select_longpoll_pool(cp);
  4378. if (!pool) {
  4379. applog(LOG_WARNING, "No suitable long-poll found for pool %s", cp->rpc_url);
  4380. while (!pool) {
  4381. sleep(60);
  4382. pool = select_longpoll_pool(cp);
  4383. }
  4384. }
  4385. /* Any longpoll from any pool is enough for this to be true */
  4386. have_longpoll = true;
  4387. wait_lpcurrent(cp);
  4388. if (cp == pool)
  4389. applog(LOG_WARNING, "Long-polling activated for %s", pool->lp_url);
  4390. else
  4391. applog(LOG_WARNING, "Long-polling activated for pool %s via %s", cp->rpc_url, pool->lp_url);
  4392. while (42) {
  4393. json_t *val, *soval;
  4394. wait_lpcurrent(cp);
  4395. gettimeofday(&start, NULL);
  4396. /* Longpoll connections can be persistent for a very long time
  4397. * and any number of issues could have come up in the meantime
  4398. * so always establish a fresh connection instead of relying on
  4399. * a persistent one. */
  4400. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  4401. val = json_rpc_call(curl, pool->lp_url, pool->rpc_userpass, rpc_req,
  4402. false, true, &rolltime, pool, false);
  4403. gettimeofday(&reply, NULL);
  4404. if (likely(val)) {
  4405. soval = json_object_get(json_object_get(val, "result"), "submitold");
  4406. if (soval)
  4407. pool->submit_old = json_is_true(soval);
  4408. else
  4409. pool->submit_old = false;
  4410. convert_to_work(val, rolltime, pool, &start, &reply);
  4411. failures = 0;
  4412. json_decref(val);
  4413. } else {
  4414. /* Some pools regularly drop the longpoll request so
  4415. * only see this as longpoll failure if it happens
  4416. * immediately and just restart it the rest of the
  4417. * time. */
  4418. gettimeofday(&end, NULL);
  4419. if (end.tv_sec - start.tv_sec > 30)
  4420. continue;
  4421. if (failures == 1)
  4422. applog(LOG_WARNING, "longpoll failed for %s, retrying every 30s", pool->lp_url);
  4423. sleep(30);
  4424. }
  4425. if (pool != cp) {
  4426. pool = select_longpoll_pool(cp);
  4427. if (unlikely(!pool))
  4428. goto retry_pool;
  4429. }
  4430. if (unlikely(pool->removed))
  4431. break;
  4432. }
  4433. out:
  4434. if (curl)
  4435. curl_easy_cleanup(curl);
  4436. return NULL;
  4437. }
  4438. void reinit_device(struct cgpu_info *cgpu)
  4439. {
  4440. if (cgpu->api->reinit_device)
  4441. cgpu->api->reinit_device(cgpu);
  4442. }
  4443. static struct timeval rotate_tv;
  4444. /* We reap curls if they are unused for over a minute */
  4445. static void reap_curl(struct pool *pool)
  4446. {
  4447. struct curl_ent *ent, *iter;
  4448. struct timeval now;
  4449. int reaped = 0;
  4450. gettimeofday(&now, NULL);
  4451. mutex_lock(&pool->pool_lock);
  4452. list_for_each_entry_safe(ent, iter, &pool->curlring, node) {
  4453. if (pool->curls < 2)
  4454. break;
  4455. if (now.tv_sec - ent->tv.tv_sec > 300) {
  4456. reaped++;
  4457. pool->curls--;
  4458. list_del(&ent->node);
  4459. curl_easy_cleanup(ent->curl);
  4460. free(ent);
  4461. }
  4462. }
  4463. mutex_unlock(&pool->pool_lock);
  4464. if (reaped)
  4465. applog(LOG_DEBUG, "Reaped %d curl%s from pool %d", reaped, reaped > 1 ? "s" : "", pool->pool_no);
  4466. }
  4467. static void *watchpool_thread(void __maybe_unused *userdata)
  4468. {
  4469. int intervals = 0;
  4470. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4471. while (42) {
  4472. struct timeval now;
  4473. int i;
  4474. if (++intervals > 20)
  4475. intervals = 0;
  4476. gettimeofday(&now, NULL);
  4477. for (i = 0; i < total_pools; i++) {
  4478. struct pool *pool = pools[i];
  4479. if (!opt_benchmark)
  4480. reap_curl(pool);
  4481. if (pool->enabled == POOL_DISABLED)
  4482. continue;
  4483. /* Test pool is idle once every minute */
  4484. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4485. gettimeofday(&pool->tv_idle, NULL);
  4486. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4487. pool_resus(pool);
  4488. }
  4489. /* Get a rolling utility per pool over 10 mins */
  4490. if (intervals > 19) {
  4491. int shares = pool->diff1 - pool->last_shares;
  4492. pool->last_shares = pool->diff1;
  4493. pool->utility = (pool->utility + (double)shares * 0.63) / 1.63;
  4494. pool->shares = pool->utility;
  4495. }
  4496. }
  4497. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4498. gettimeofday(&rotate_tv, NULL);
  4499. switch_pools(NULL);
  4500. }
  4501. sleep(30);
  4502. }
  4503. return NULL;
  4504. }
  4505. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4506. * the screen at regular intervals, and restarts threads if they appear to have
  4507. * died. */
  4508. #define WATCHDOG_INTERVAL 3
  4509. #define WATCHDOG_SICK_TIME 60
  4510. #define WATCHDOG_DEAD_TIME 600
  4511. #define WATCHDOG_SICK_COUNT (WATCHDOG_SICK_TIME/WATCHDOG_INTERVAL)
  4512. #define WATCHDOG_DEAD_COUNT (WATCHDOG_DEAD_TIME/WATCHDOG_INTERVAL)
  4513. static void *watchdog_thread(void __maybe_unused *userdata)
  4514. {
  4515. const unsigned int interval = WATCHDOG_INTERVAL;
  4516. struct timeval zero_tv;
  4517. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4518. memset(&zero_tv, 0, sizeof(struct timeval));
  4519. gettimeofday(&rotate_tv, NULL);
  4520. while (1) {
  4521. int i;
  4522. struct timeval now;
  4523. sleep(interval);
  4524. discard_stale();
  4525. hashmeter(-1, &zero_tv, 0);
  4526. #ifdef HAVE_CURSES
  4527. if (curses_active_locked()) {
  4528. change_logwinsize();
  4529. curses_print_status();
  4530. for (i = 0; i < mining_threads; i++)
  4531. curses_print_devstatus(i);
  4532. touchwin(statuswin);
  4533. wrefresh(statuswin);
  4534. touchwin(logwin);
  4535. wrefresh(logwin);
  4536. unlock_curses();
  4537. }
  4538. #endif
  4539. gettimeofday(&now, NULL);
  4540. if (!sched_paused && !should_run()) {
  4541. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4542. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4543. if (!schedstart.enable) {
  4544. quit(0, "Terminating execution as planned");
  4545. break;
  4546. }
  4547. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4548. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4549. sched_paused = true;
  4550. for (i = 0; i < mining_threads; i++) {
  4551. struct thr_info *thr;
  4552. thr = &thr_info[i];
  4553. thr->pause = true;
  4554. }
  4555. } else if (sched_paused && should_run()) {
  4556. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4557. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4558. if (schedstop.enable)
  4559. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4560. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4561. sched_paused = false;
  4562. for (i = 0; i < mining_threads; i++) {
  4563. struct thr_info *thr;
  4564. thr = &thr_info[i];
  4565. /* Don't touch disabled devices */
  4566. if (thr->cgpu->deven == DEV_DISABLED)
  4567. continue;
  4568. thr->pause = false;
  4569. tq_push(thr->q, &ping);
  4570. }
  4571. }
  4572. for (i = 0; i < total_devices; ++i) {
  4573. struct cgpu_info *cgpu = devices[i];
  4574. struct thr_info *thr = cgpu->thr[0];
  4575. enum dev_enable *denable;
  4576. char dev_str[8];
  4577. int gpu;
  4578. if (cgpu->api->get_stats)
  4579. cgpu->api->get_stats(cgpu);
  4580. gpu = cgpu->device_id;
  4581. denable = &cgpu->deven;
  4582. sprintf(dev_str, "%s%d", cgpu->api->name, gpu);
  4583. #ifdef HAVE_ADL
  4584. if (adl_active && cgpu->has_adl)
  4585. gpu_autotune(gpu, denable);
  4586. if (opt_debug && cgpu->has_adl) {
  4587. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4588. float temp = 0, vddc = 0;
  4589. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4590. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4591. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4592. }
  4593. #endif
  4594. /* Thread is waiting on getwork or disabled */
  4595. if (thr->getwork || *denable == DEV_DISABLED)
  4596. continue;
  4597. #ifdef WANT_CPUMINE
  4598. if (!strcmp(cgpu->api->dname, "cpu"))
  4599. continue;
  4600. #endif
  4601. if (cgpu->status != LIFE_WELL && (now.tv_sec - thr->last.tv_sec < WATCHDOG_SICK_TIME)) {
  4602. if (cgpu->status != LIFE_INIT)
  4603. applog(LOG_ERR, "%s: Recovered, declaring WELL!", dev_str);
  4604. cgpu->status = LIFE_WELL;
  4605. cgpu->device_last_well = time(NULL);
  4606. } else if (cgpu->status == LIFE_WELL && (now.tv_sec - thr->last.tv_sec > WATCHDOG_SICK_TIME)) {
  4607. thr->rolling = cgpu->rolling = 0;
  4608. cgpu->status = LIFE_SICK;
  4609. applog(LOG_ERR, "%s: Idle for more than 60 seconds, declaring SICK!", dev_str);
  4610. gettimeofday(&thr->sick, NULL);
  4611. cgpu->device_last_not_well = time(NULL);
  4612. cgpu->device_not_well_reason = REASON_DEV_SICK_IDLE_60;
  4613. cgpu->dev_sick_idle_60_count++;
  4614. #ifdef HAVE_ADL
  4615. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4616. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  4617. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  4618. } else
  4619. #endif
  4620. if (opt_restart) {
  4621. applog(LOG_ERR, "%s: Attempting to restart", dev_str);
  4622. reinit_device(cgpu);
  4623. }
  4624. } else if (cgpu->status == LIFE_SICK && (now.tv_sec - thr->last.tv_sec > WATCHDOG_DEAD_TIME)) {
  4625. cgpu->status = LIFE_DEAD;
  4626. applog(LOG_ERR, "%s: Not responded for more than 10 minutes, declaring DEAD!", dev_str);
  4627. gettimeofday(&thr->sick, NULL);
  4628. cgpu->device_last_not_well = time(NULL);
  4629. cgpu->device_not_well_reason = REASON_DEV_DEAD_IDLE_600;
  4630. cgpu->dev_dead_idle_600_count++;
  4631. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  4632. (cgpu->status == LIFE_SICK || cgpu->status == LIFE_DEAD)) {
  4633. /* Attempt to restart a GPU that's sick or dead once every minute */
  4634. gettimeofday(&thr->sick, NULL);
  4635. #ifdef HAVE_ADL
  4636. if (adl_active && cgpu->has_adl && gpu_activity(gpu) > 50) {
  4637. /* Again do not attempt to restart a device that may have hard hung */
  4638. } else
  4639. #endif
  4640. if (opt_restart)
  4641. reinit_device(cgpu);
  4642. }
  4643. }
  4644. }
  4645. return NULL;
  4646. }
  4647. static void log_print_status(struct cgpu_info *cgpu)
  4648. {
  4649. char logline[255];
  4650. get_statline(logline, cgpu);
  4651. applog(LOG_WARNING, "%s", logline);
  4652. }
  4653. static void print_summary(void)
  4654. {
  4655. struct timeval diff;
  4656. int hours, mins, secs, i;
  4657. double utility, efficiency = 0.0, displayed_hashes, work_util;
  4658. bool mhash_base = true;
  4659. timersub(&total_tv_end, &total_tv_start, &diff);
  4660. hours = diff.tv_sec / 3600;
  4661. mins = (diff.tv_sec % 3600) / 60;
  4662. secs = diff.tv_sec % 60;
  4663. utility = total_accepted / total_secs * 60;
  4664. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4665. work_util = total_diff1 / total_secs * 60;
  4666. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4667. applog(LOG_WARNING, "Started at %s", datestamp);
  4668. if (total_pools == 1)
  4669. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  4670. #ifdef WANT_CPUMINE
  4671. if (opt_n_threads)
  4672. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4673. #endif
  4674. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4675. displayed_hashes = total_mhashes_done / total_secs;
  4676. if (displayed_hashes < 1) {
  4677. displayed_hashes *= 1000;
  4678. mhash_base = false;
  4679. }
  4680. applog(LOG_WARNING, "Average hashrate: %.1f %shash/s", displayed_hashes, mhash_base? "Mega" : "Kilo");
  4681. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  4682. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4683. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4684. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4685. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4686. applog(LOG_WARNING, "Accepted difficulty shares: %1.f", total_diff_accepted);
  4687. applog(LOG_WARNING, "Rejected difficulty shares: %1.f", total_diff_rejected);
  4688. if (total_accepted || total_rejected)
  4689. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4690. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4691. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4692. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min", utility);
  4693. applog(LOG_WARNING, "Work Utility (diff1 shares solved / min): %.2f/min\n", work_util);
  4694. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4695. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4696. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4697. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4698. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4699. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4700. if (total_pools > 1) {
  4701. for (i = 0; i < total_pools; i++) {
  4702. struct pool *pool = pools[i];
  4703. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4704. if (pool->solved)
  4705. applog(LOG_WARNING, "SOLVED %d BLOCK%s!", pool->solved, pool->solved > 1 ? "S" : "");
  4706. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4707. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4708. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4709. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4710. applog(LOG_WARNING, " Accepted difficulty shares: %1.f", pool->diff_accepted);
  4711. applog(LOG_WARNING, " Rejected difficulty shares: %1.f", pool->diff_rejected);
  4712. if (pool->accepted || pool->rejected)
  4713. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4714. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4715. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4716. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4717. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4718. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4719. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4720. }
  4721. }
  4722. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4723. for (i = 0; i < total_devices; ++i)
  4724. log_print_status(devices[i]);
  4725. if (opt_shares)
  4726. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4727. fflush(stdout);
  4728. fflush(stderr);
  4729. if (opt_shares > total_accepted)
  4730. applog(LOG_WARNING, "WARNING - Mined only %d shares of %d requested.", total_accepted, opt_shares);
  4731. }
  4732. static void clean_up(void)
  4733. {
  4734. #ifdef HAVE_OPENCL
  4735. clear_adl(nDevs);
  4736. #endif
  4737. #ifdef HAVE_LIBUSB
  4738. libusb_exit(NULL);
  4739. #endif
  4740. gettimeofday(&total_tv_end, NULL);
  4741. #ifdef HAVE_CURSES
  4742. disable_curses();
  4743. #endif
  4744. if (!opt_realquiet && successful_connect)
  4745. print_summary();
  4746. if (opt_n_threads)
  4747. free(cpus);
  4748. curl_global_cleanup();
  4749. }
  4750. void quit(int status, const char *format, ...)
  4751. {
  4752. va_list ap;
  4753. clean_up();
  4754. if (format) {
  4755. va_start(ap, format);
  4756. vfprintf(stderr, format, ap);
  4757. va_end(ap);
  4758. }
  4759. fprintf(stderr, "\n");
  4760. fflush(stderr);
  4761. #if defined(unix)
  4762. if (forkpid > 0) {
  4763. kill(forkpid, SIGTERM);
  4764. forkpid = 0;
  4765. }
  4766. #endif
  4767. exit(status);
  4768. }
  4769. #ifdef HAVE_CURSES
  4770. char *curses_input(const char *query)
  4771. {
  4772. char *input;
  4773. echo();
  4774. input = malloc(255);
  4775. if (!input)
  4776. quit(1, "Failed to malloc input");
  4777. leaveok(logwin, false);
  4778. wlogprint("%s:\n", query);
  4779. wgetnstr(logwin, input, 255);
  4780. if (!strlen(input))
  4781. strcpy(input, "-1");
  4782. leaveok(logwin, true);
  4783. noecho();
  4784. return input;
  4785. }
  4786. #endif
  4787. void add_pool_details(struct pool *pool, bool live, char *url, char *user, char *pass)
  4788. {
  4789. url = get_proxy(url, pool);
  4790. pool->rpc_url = url;
  4791. pool->rpc_user = user;
  4792. pool->rpc_pass = pass;
  4793. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4794. if (!pool->rpc_userpass)
  4795. quit(1, "Failed to malloc userpass");
  4796. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4797. enable_pool(pool);
  4798. /* Prevent noise on startup */
  4799. pool->lagging = true;
  4800. /* Test the pool is not idle if we're live running, otherwise
  4801. * it will be tested separately */
  4802. if (live && !pool_active(pool, false))
  4803. pool->idle = true;
  4804. }
  4805. #ifdef HAVE_CURSES
  4806. static bool input_pool(bool live)
  4807. {
  4808. char *url = NULL, *user = NULL, *pass = NULL;
  4809. struct pool *pool;
  4810. bool ret = false;
  4811. immedok(logwin, true);
  4812. wlogprint("Input server details.\n");
  4813. url = curses_input("URL");
  4814. if (!url)
  4815. goto out;
  4816. user = curses_input("Username");
  4817. if (!user)
  4818. goto out;
  4819. pass = curses_input("Password");
  4820. if (!pass)
  4821. goto out;
  4822. pool = add_pool();
  4823. if (detect_stratum(pool, url))
  4824. url = strdup(pool->stratum_url);
  4825. else if (strncmp(url, "http://", 7) && strncmp(url, "https://", 8)) {
  4826. char *httpinput;
  4827. httpinput = malloc(255);
  4828. if (!httpinput)
  4829. quit(1, "Failed to malloc httpinput");
  4830. strcpy(httpinput, "http://");
  4831. strncat(httpinput, url, 248);
  4832. free(url);
  4833. url = httpinput;
  4834. }
  4835. add_pool_details(pool, live, url, user, pass);
  4836. ret = true;
  4837. out:
  4838. immedok(logwin, false);
  4839. if (!ret) {
  4840. if (url)
  4841. free(url);
  4842. if (user)
  4843. free(user);
  4844. if (pass)
  4845. free(pass);
  4846. }
  4847. return ret;
  4848. }
  4849. #endif
  4850. #if defined(unix)
  4851. static void fork_monitor()
  4852. {
  4853. // Make a pipe: [readFD, writeFD]
  4854. int pfd[2];
  4855. int r = pipe(pfd);
  4856. if (r < 0) {
  4857. perror("pipe - failed to create pipe for --monitor");
  4858. exit(1);
  4859. }
  4860. // Make stderr write end of pipe
  4861. fflush(stderr);
  4862. r = dup2(pfd[1], 2);
  4863. if (r < 0) {
  4864. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4865. exit(1);
  4866. }
  4867. r = close(pfd[1]);
  4868. if (r < 0) {
  4869. perror("close - failed to close write end of pipe for --monitor");
  4870. exit(1);
  4871. }
  4872. // Don't allow a dying monitor to kill the main process
  4873. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4874. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4875. if (SIG_ERR == sr0 || SIG_ERR == sr1) {
  4876. perror("signal - failed to edit signal mask for --monitor");
  4877. exit(1);
  4878. }
  4879. // Fork a child process
  4880. forkpid = fork();
  4881. if (forkpid < 0) {
  4882. perror("fork - failed to fork child process for --monitor");
  4883. exit(1);
  4884. }
  4885. // Child: launch monitor command
  4886. if (0 == forkpid) {
  4887. // Make stdin read end of pipe
  4888. r = dup2(pfd[0], 0);
  4889. if (r < 0) {
  4890. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4891. exit(1);
  4892. }
  4893. close(pfd[0]);
  4894. if (r < 0) {
  4895. perror("close - in child, failed to close read end of pipe for --monitor");
  4896. exit(1);
  4897. }
  4898. // Launch user specified command
  4899. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4900. perror("execl - in child failed to exec user specified command for --monitor");
  4901. exit(1);
  4902. }
  4903. // Parent: clean up unused fds and bail
  4904. r = close(pfd[0]);
  4905. if (r < 0) {
  4906. perror("close - failed to close read end of pipe for --monitor");
  4907. exit(1);
  4908. }
  4909. }
  4910. #endif // defined(unix)
  4911. #ifdef HAVE_CURSES
  4912. void enable_curses(void) {
  4913. int x,y;
  4914. lock_curses();
  4915. if (curses_active) {
  4916. unlock_curses();
  4917. return;
  4918. }
  4919. mainwin = initscr();
  4920. getmaxyx(mainwin, y, x);
  4921. statuswin = newwin(logstart, x, 0, 0);
  4922. leaveok(statuswin, true);
  4923. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4924. idlok(logwin, true);
  4925. scrollok(logwin, true);
  4926. leaveok(logwin, true);
  4927. cbreak();
  4928. noecho();
  4929. curses_active = true;
  4930. statusy = logstart;
  4931. unlock_curses();
  4932. }
  4933. #endif
  4934. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  4935. #ifndef WANT_CPUMINE
  4936. struct device_api cpu_api;
  4937. struct device_api cpu_api = {
  4938. .name = "CPU",
  4939. };
  4940. #endif
  4941. #ifdef USE_BITFORCE
  4942. extern struct device_api bitforce_api;
  4943. #endif
  4944. #ifdef USE_ICARUS
  4945. extern struct device_api icarus_api;
  4946. #endif
  4947. #ifdef USE_MODMINER
  4948. extern struct device_api modminer_api;
  4949. #endif
  4950. #ifdef USE_ZTEX
  4951. extern struct device_api ztex_api;
  4952. #endif
  4953. static int cgminer_id_count = 0;
  4954. void enable_device(struct cgpu_info *cgpu)
  4955. {
  4956. cgpu->deven = DEV_ENABLED;
  4957. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  4958. mining_threads += cgpu->threads;
  4959. #ifdef HAVE_CURSES
  4960. adj_width(mining_threads, &dev_width);
  4961. #endif
  4962. #ifdef HAVE_OPENCL
  4963. if (cgpu->api == &opencl_api) {
  4964. gpu_threads += cgpu->threads;
  4965. }
  4966. #endif
  4967. }
  4968. struct _cgpu_devid_counter {
  4969. char name[4];
  4970. int lastid;
  4971. UT_hash_handle hh;
  4972. };
  4973. bool add_cgpu(struct cgpu_info*cgpu)
  4974. {
  4975. static struct _cgpu_devid_counter *devids = NULL;
  4976. struct _cgpu_devid_counter *d;
  4977. HASH_FIND_STR(devids, cgpu->api->name, d);
  4978. if (d)
  4979. cgpu->device_id = ++d->lastid;
  4980. else {
  4981. d = malloc(sizeof(*d));
  4982. memcpy(d->name, cgpu->api->name, sizeof(d->name));
  4983. cgpu->device_id = d->lastid = 0;
  4984. HASH_ADD_STR(devids, name, d);
  4985. }
  4986. devices = realloc(devices, sizeof(struct cgpu_info *) * (total_devices + 2));
  4987. devices[total_devices++] = cgpu;
  4988. return true;
  4989. }
  4990. int main(int argc, char *argv[])
  4991. {
  4992. struct block *block, *tmpblock;
  4993. struct work *work, *tmpwork;
  4994. bool pools_active = false;
  4995. struct sigaction handler;
  4996. struct thr_info *thr;
  4997. char *s;
  4998. unsigned int k;
  4999. int i, j;
  5000. /* This dangerous functions tramples random dynamically allocated
  5001. * variables so do it before anything at all */
  5002. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  5003. quit(1, "Failed to curl_global_init");
  5004. initial_args = malloc(sizeof(char *) * (argc + 1));
  5005. for (i = 0; i < argc; i++)
  5006. initial_args[i] = strdup(argv[i]);
  5007. initial_args[argc] = NULL;
  5008. #ifdef HAVE_LIBUSB
  5009. libusb_init(NULL);
  5010. #endif
  5011. mutex_init(&hash_lock);
  5012. mutex_init(&qd_lock);
  5013. mutex_init(&console_lock);
  5014. mutex_init(&control_lock);
  5015. mutex_init(&sharelog_lock);
  5016. mutex_init(&ch_lock);
  5017. mutex_init(&sshare_lock);
  5018. rwlock_init(&blk_lock);
  5019. rwlock_init(&netacc_lock);
  5020. mutex_init(&lp_lock);
  5021. if (unlikely(pthread_cond_init(&lp_cond, NULL)))
  5022. quit(1, "Failed to pthread_cond_init lp_cond");
  5023. mutex_init(&restart_lock);
  5024. if (unlikely(pthread_cond_init(&restart_cond, NULL)))
  5025. quit(1, "Failed to pthread_cond_init restart_cond");
  5026. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  5027. #ifdef WANT_CPUMINE
  5028. init_max_name_len();
  5029. #endif
  5030. handler.sa_handler = &sighandler;
  5031. handler.sa_flags = 0;
  5032. sigemptyset(&handler.sa_mask);
  5033. sigaction(SIGTERM, &handler, &termhandler);
  5034. sigaction(SIGINT, &handler, &inthandler);
  5035. #ifndef WIN32
  5036. signal(SIGPIPE, SIG_IGN);
  5037. #endif
  5038. opt_kernel_path = alloca(PATH_MAX);
  5039. strcpy(opt_kernel_path, CGMINER_PREFIX);
  5040. cgminer_path = alloca(PATH_MAX);
  5041. s = strdup(argv[0]);
  5042. strcpy(cgminer_path, dirname(s));
  5043. free(s);
  5044. strcat(cgminer_path, "/");
  5045. #ifdef WANT_CPUMINE
  5046. // Hack to make cgminer silent when called recursively on WIN32
  5047. int skip_to_bench = 0;
  5048. #if defined(WIN32)
  5049. char buf[32];
  5050. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  5051. skip_to_bench = 1;
  5052. #endif // defined(WIN32)
  5053. #endif
  5054. devcursor = 8;
  5055. logstart = devcursor + 1;
  5056. logcursor = logstart + 1;
  5057. block = calloc(sizeof(struct block), 1);
  5058. if (unlikely(!block))
  5059. quit (1, "main OOM");
  5060. for (i = 0; i < 36; i++)
  5061. strcat(block->hash, "0");
  5062. HASH_ADD_STR(blocks, hash, block);
  5063. strcpy(current_block, block->hash);
  5064. INIT_LIST_HEAD(&scan_devices);
  5065. #ifdef HAVE_OPENCL
  5066. memset(gpus, 0, sizeof(gpus));
  5067. for (i = 0; i < MAX_GPUDEVICES; i++)
  5068. gpus[i].dynamic = true;
  5069. #endif
  5070. /* parse command line */
  5071. opt_register_table(opt_config_table,
  5072. "Options for both config file and command line");
  5073. opt_register_table(opt_cmdline_table,
  5074. "Options for command line only");
  5075. opt_parse(&argc, argv, applog_and_exit);
  5076. if (argc != 1)
  5077. quit(1, "Unexpected extra commandline arguments");
  5078. if (!config_loaded)
  5079. load_default_config();
  5080. if (opt_benchmark) {
  5081. struct pool *pool;
  5082. pool = add_pool();
  5083. pool->rpc_url = malloc(255);
  5084. strcpy(pool->rpc_url, "Benchmark");
  5085. pool->rpc_user = pool->rpc_url;
  5086. pool->rpc_pass = pool->rpc_url;
  5087. enable_pool(pool);
  5088. pool->idle = false;
  5089. successful_connect = true;
  5090. }
  5091. #ifdef HAVE_CURSES
  5092. if (opt_realquiet || devices_enabled == -1)
  5093. use_curses = false;
  5094. if (use_curses)
  5095. enable_curses();
  5096. #endif
  5097. applog(LOG_WARNING, "Started %s", packagename);
  5098. if (cnfbuf) {
  5099. applog(LOG_NOTICE, "Loaded configuration file %s", cnfbuf);
  5100. switch (fileconf_load) {
  5101. case 0:
  5102. applog(LOG_WARNING, "Fatal JSON error in configuration file.");
  5103. applog(LOG_WARNING, "Configuration file could not be used.");
  5104. break;
  5105. case -1:
  5106. applog(LOG_WARNING, "Error in configuration file, partially loaded.");
  5107. if (use_curses)
  5108. applog(LOG_WARNING, "Start cgminer with -T to see what failed to load.");
  5109. break;
  5110. default:
  5111. break;
  5112. }
  5113. free(cnfbuf);
  5114. cnfbuf = NULL;
  5115. }
  5116. strcat(opt_kernel_path, "/");
  5117. if (want_per_device_stats)
  5118. opt_log_output = true;
  5119. #ifdef WANT_CPUMINE
  5120. #ifdef USE_SCRYPT
  5121. if (opt_scrypt)
  5122. set_scrypt_algo(&opt_algo);
  5123. else
  5124. #endif
  5125. if (0 <= opt_bench_algo) {
  5126. double rate = bench_algo_stage3(opt_bench_algo);
  5127. if (!skip_to_bench)
  5128. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  5129. else {
  5130. // Write result to shared memory for parent
  5131. #if defined(WIN32)
  5132. char unique_name[64];
  5133. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  5134. HANDLE map_handle = CreateFileMapping(
  5135. INVALID_HANDLE_VALUE, // use paging file
  5136. NULL, // default security attributes
  5137. PAGE_READWRITE, // read/write access
  5138. 0, // size: high 32-bits
  5139. 4096, // size: low 32-bits
  5140. unique_name // name of map object
  5141. );
  5142. if (NULL != map_handle) {
  5143. void *shared_mem = MapViewOfFile(
  5144. map_handle, // object to map view of
  5145. FILE_MAP_WRITE, // read/write access
  5146. 0, // high offset: map from
  5147. 0, // low offset: beginning
  5148. 0 // default: map entire file
  5149. );
  5150. if (NULL != shared_mem)
  5151. CopyMemory(shared_mem, &rate, sizeof(rate));
  5152. (void)UnmapViewOfFile(shared_mem);
  5153. }
  5154. (void)CloseHandle(map_handle);
  5155. }
  5156. #endif
  5157. }
  5158. exit(0);
  5159. }
  5160. #endif
  5161. #ifdef HAVE_OPENCL
  5162. if (!opt_nogpu)
  5163. opencl_api.api_detect();
  5164. gpu_threads = 0;
  5165. #endif
  5166. #ifdef USE_ICARUS
  5167. if (!opt_scrypt)
  5168. icarus_api.api_detect();
  5169. #endif
  5170. #ifdef USE_BITFORCE
  5171. if (!opt_scrypt)
  5172. bitforce_api.api_detect();
  5173. #endif
  5174. #ifdef USE_MODMINER
  5175. if (!opt_scrypt)
  5176. modminer_api.api_detect();
  5177. #endif
  5178. #ifdef USE_ZTEX
  5179. if (!opt_scrypt)
  5180. ztex_api.api_detect();
  5181. #endif
  5182. #ifdef WANT_CPUMINE
  5183. cpu_api.api_detect();
  5184. #endif
  5185. if (devices_enabled == -1) {
  5186. applog(LOG_ERR, "Devices detected:");
  5187. for (i = 0; i < total_devices; ++i) {
  5188. struct cgpu_info *cgpu = devices[i];
  5189. if (cgpu->name)
  5190. applog(LOG_ERR, " %2d. %s %d: %s (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->name, cgpu->api->dname);
  5191. else
  5192. applog(LOG_ERR, " %2d. %s %d (driver: %s)", i, cgpu->api->name, cgpu->device_id, cgpu->api->dname);
  5193. }
  5194. quit(0, "%d devices listed", total_devices);
  5195. }
  5196. mining_threads = 0;
  5197. if (devices_enabled) {
  5198. for (i = 0; i < (int)(sizeof(devices_enabled) * 8) - 1; ++i) {
  5199. if (devices_enabled & (1 << i)) {
  5200. if (i >= total_devices)
  5201. quit (1, "Command line options set a device that doesn't exist");
  5202. enable_device(devices[i]);
  5203. } else if (i < total_devices) {
  5204. if (opt_removedisabled) {
  5205. if (devices[i]->api == &cpu_api)
  5206. --opt_n_threads;
  5207. } else {
  5208. enable_device(devices[i]);
  5209. }
  5210. devices[i]->deven = DEV_DISABLED;
  5211. }
  5212. }
  5213. total_devices = cgminer_id_count;
  5214. } else {
  5215. for (i = 0; i < total_devices; ++i)
  5216. enable_device(devices[i]);
  5217. }
  5218. if (!total_devices)
  5219. quit(1, "All devices disabled, cannot mine!");
  5220. load_temp_cutoffs();
  5221. for (i = 0; i < total_devices; ++i)
  5222. devices[i]->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5223. logstart += total_devices;
  5224. logcursor = logstart + 1;
  5225. #ifdef HAVE_CURSES
  5226. check_winsizes();
  5227. #endif
  5228. if (!total_pools) {
  5229. applog(LOG_WARNING, "Need to specify at least one pool server.");
  5230. #ifdef HAVE_CURSES
  5231. if (!use_curses || !input_pool(false))
  5232. #endif
  5233. quit(1, "Pool setup failed");
  5234. }
  5235. for (i = 0; i < total_pools; i++) {
  5236. struct pool *pool = pools[i];
  5237. pool->cgminer_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5238. pool->cgminer_pool_stats.getwork_wait_min.tv_sec = MIN_SEC_UNSET;
  5239. if (!pool->rpc_userpass) {
  5240. if (!pool->rpc_user || !pool->rpc_pass)
  5241. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  5242. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5243. if (!pool->rpc_userpass)
  5244. quit(1, "Failed to malloc userpass");
  5245. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5246. }
  5247. }
  5248. /* Set the currentpool to pool 0 */
  5249. currentpool = pools[0];
  5250. #ifdef HAVE_SYSLOG_H
  5251. if (use_syslog)
  5252. openlog(PACKAGE, LOG_PID, LOG_USER);
  5253. #endif
  5254. #if defined(unix)
  5255. if (opt_stderr_cmd)
  5256. fork_monitor();
  5257. #endif // defined(unix)
  5258. total_threads = mining_threads + 7;
  5259. thr_info = calloc(total_threads, sizeof(*thr));
  5260. if (!thr_info)
  5261. quit(1, "Failed to calloc thr_info");
  5262. /* init workio thread info */
  5263. work_thr_id = mining_threads;
  5264. thr = &thr_info[work_thr_id];
  5265. thr->id = work_thr_id;
  5266. thr->q = tq_new();
  5267. if (!thr->q)
  5268. quit(1, "Failed to tq_new");
  5269. /* start work I/O thread */
  5270. if (thr_info_create(thr, NULL, workio_thread, thr))
  5271. quit(1, "workio thread create failed");
  5272. stage_thr_id = mining_threads + 1;
  5273. thr = &thr_info[stage_thr_id];
  5274. thr->q = tq_new();
  5275. if (!thr->q)
  5276. quit(1, "Failed to tq_new");
  5277. /* start stage thread */
  5278. if (thr_info_create(thr, NULL, stage_thread, thr))
  5279. quit(1, "stage thread create failed");
  5280. pthread_detach(thr->pth);
  5281. /* Create a unique get work queue */
  5282. getq = tq_new();
  5283. if (!getq)
  5284. quit(1, "Failed to create getq");
  5285. /* We use the getq mutex as the staged lock */
  5286. stgd_lock = &getq->mutex;
  5287. if (opt_benchmark)
  5288. goto begin_bench;
  5289. for (i = 0; i < total_pools; i++) {
  5290. struct pool *pool = pools[i];
  5291. enable_pool(pool);
  5292. pool->idle = true;
  5293. }
  5294. applog(LOG_NOTICE, "Probing for an alive pool");
  5295. do {
  5296. /* Look for at least one active pool before starting */
  5297. for (i = 0; i < total_pools; i++) {
  5298. struct pool *pool = pools[i];
  5299. if (pool_active(pool, false)) {
  5300. if (!currentpool)
  5301. currentpool = pool;
  5302. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  5303. pools_active = true;
  5304. break;
  5305. } else {
  5306. if (pool == currentpool)
  5307. currentpool = NULL;
  5308. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  5309. }
  5310. }
  5311. if (!pools_active) {
  5312. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  5313. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  5314. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  5315. for (i = 0; i < total_pools; i++) {
  5316. struct pool *pool;
  5317. pool = pools[i];
  5318. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  5319. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  5320. }
  5321. #ifdef HAVE_CURSES
  5322. if (use_curses) {
  5323. halfdelay(150);
  5324. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  5325. if (getch() != ERR)
  5326. quit(0, "No servers could be used! Exiting.");
  5327. nocbreak();
  5328. } else
  5329. #endif
  5330. quit(0, "No servers could be used! Exiting.");
  5331. }
  5332. } while (!pools_active);
  5333. begin_bench:
  5334. total_mhashes_done = 0;
  5335. for (i = 0; i < total_devices; i++) {
  5336. struct cgpu_info *cgpu = devices[i];
  5337. cgpu->rolling = cgpu->total_mhashes = 0;
  5338. }
  5339. gettimeofday(&total_tv_start, NULL);
  5340. gettimeofday(&total_tv_end, NULL);
  5341. get_datestamp(datestamp, &total_tv_start);
  5342. // Start threads
  5343. k = 0;
  5344. for (i = 0; i < total_devices; ++i) {
  5345. struct cgpu_info *cgpu = devices[i];
  5346. cgpu->thr = malloc(sizeof(*cgpu->thr) * (cgpu->threads+1));
  5347. cgpu->thr[cgpu->threads] = NULL;
  5348. cgpu->status = LIFE_INIT;
  5349. for (j = 0; j < cgpu->threads; ++j, ++k) {
  5350. thr = &thr_info[k];
  5351. thr->id = k;
  5352. thr->cgpu = cgpu;
  5353. thr->device_thread = j;
  5354. thr->q = tq_new();
  5355. if (!thr->q)
  5356. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  5357. /* Enable threads for devices set not to mine but disable
  5358. * their queue in case we wish to enable them later */
  5359. if (cgpu->deven != DEV_DISABLED) {
  5360. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5361. tq_push(thr->q, &ping);
  5362. }
  5363. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  5364. continue;
  5365. thread_reportout(thr);
  5366. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5367. quit(1, "thread %d create failed", thr->id);
  5368. cgpu->thr[j] = thr;
  5369. }
  5370. }
  5371. #ifdef HAVE_OPENCL
  5372. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  5373. for (i = 0; i < nDevs; i++)
  5374. pause_dynamic_threads(i);
  5375. #endif
  5376. #ifdef WANT_CPUMINE
  5377. applog(LOG_INFO, "%d cpu miner threads started, "
  5378. "using SHA256 '%s' algorithm.",
  5379. opt_n_threads,
  5380. algo_names[opt_algo]);
  5381. #endif
  5382. gettimeofday(&total_tv_start, NULL);
  5383. gettimeofday(&total_tv_end, NULL);
  5384. watchpool_thr_id = mining_threads + 2;
  5385. thr = &thr_info[watchpool_thr_id];
  5386. /* start watchpool thread */
  5387. if (thr_info_create(thr, NULL, watchpool_thread, NULL))
  5388. quit(1, "watchpool thread create failed");
  5389. pthread_detach(thr->pth);
  5390. watchdog_thr_id = mining_threads + 3;
  5391. thr = &thr_info[watchdog_thr_id];
  5392. /* start watchdog thread */
  5393. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  5394. quit(1, "watchdog thread create failed");
  5395. pthread_detach(thr->pth);
  5396. #ifdef HAVE_OPENCL
  5397. /* Create reinit gpu thread */
  5398. gpur_thr_id = mining_threads + 4;
  5399. thr = &thr_info[gpur_thr_id];
  5400. thr->q = tq_new();
  5401. if (!thr->q)
  5402. quit(1, "tq_new failed for gpur_thr_id");
  5403. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  5404. quit(1, "reinit_gpu thread create failed");
  5405. #endif
  5406. /* Create API socket thread */
  5407. api_thr_id = mining_threads + 5;
  5408. thr = &thr_info[api_thr_id];
  5409. if (thr_info_create(thr, NULL, api_thread, thr))
  5410. quit(1, "API thread create failed");
  5411. #ifdef HAVE_CURSES
  5412. /* Create curses input thread for keyboard input. Create this last so
  5413. * that we know all threads are created since this can call kill_work
  5414. * to try and shut down ll previous threads. */
  5415. input_thr_id = mining_threads + 6;
  5416. thr = &thr_info[input_thr_id];
  5417. if (thr_info_create(thr, NULL, input_thread, thr))
  5418. quit(1, "input thread create failed");
  5419. pthread_detach(thr->pth);
  5420. #endif
  5421. for (i = 0; i < mining_threads + opt_queue; i++)
  5422. queue_request();
  5423. /* main loop - simply wait for workio thread to exit. This is not the
  5424. * normal exit path and only occurs should the workio_thread die
  5425. * unexpectedly */
  5426. pthread_join(thr_info[work_thr_id].pth, NULL);
  5427. applog(LOG_INFO, "workio thread dead, exiting.");
  5428. clean_up();
  5429. /* Not really necessary, but let's clean this up too anyway */
  5430. HASH_ITER(hh, staged_work, work, tmpwork) {
  5431. HASH_DEL(staged_work, work);
  5432. free_work(work);
  5433. }
  5434. HASH_ITER(hh, blocks, block, tmpblock) {
  5435. HASH_DEL(blocks, block);
  5436. free(block);
  5437. }
  5438. #if defined(unix)
  5439. if (forkpid > 0) {
  5440. kill(forkpid, SIGTERM);
  5441. forkpid = 0;
  5442. }
  5443. #endif
  5444. return 0;
  5445. }