cgminer.c 164 KB

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