cgminer.c 170 KB

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