main.c 162 KB

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