cgminer.c 180 KB

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