cgminer.c 214 KB

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