main.c 162 KB

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