cgminer.c 206 KB

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