cgminer.c 164 KB

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