cgminer.c 206 KB

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