miner.c 160 KB

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