cgminer.c 196 KB

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