miner.c 156 KB

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