main.c 160 KB

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