cgminer.c 165 KB

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