cgminer.c 187 KB

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