cgminer.c 186 KB

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