main.c 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190
  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 version"),
  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. if (cgpu) {
  1743. get_statline(logline, cgpu);
  1744. printf("%s\n", logline);
  1745. }
  1746. }
  1747. /* Must be called with curses mutex lock held and curses_active */
  1748. static void curses_print_status(void)
  1749. {
  1750. struct pool *pool = current_pool();
  1751. wattron(statuswin, A_BOLD);
  1752. mvwprintw(statuswin, 0, 0, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1753. if (opt_n_threads)
  1754. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1755. wattroff(statuswin, A_BOLD);
  1756. mvwhline(statuswin, 1, 0, '-', 80);
  1757. mvwprintw(statuswin, 2, 0, " %s", statusline);
  1758. wclrtoeol(statuswin);
  1759. mvwprintw(statuswin, 3, 0, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d",
  1760. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1761. local_work, total_go, total_ro);
  1762. wclrtoeol(statuswin);
  1763. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1764. mvwprintw(statuswin, 4, 0, " Connected to multiple pools with%s LP",
  1765. have_longpoll ? "": "out");
  1766. else
  1767. mvwprintw(statuswin, 4, 0, " Connected to %s with%s LP as user %s",
  1768. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1769. wclrtoeol(statuswin);
  1770. mvwprintw(statuswin, 5, 0, " Block: %s... Started: %s", current_hash, blocktime);
  1771. mvwhline(statuswin, 6, 0, '-', 80);
  1772. mvwhline(statuswin, logstart - 1, 0, '-', 80);
  1773. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1774. gpu_threads ? "[G]PU management " : "");
  1775. /* The window will be updated once we're done with all the devices */
  1776. wnoutrefresh(statuswin);
  1777. }
  1778. static void curses_print_devstatus(int thr_id)
  1779. {
  1780. if (thr_id >= 0 && thr_id < gpu_threads) {
  1781. int gpu = dev_from_id(thr_id);
  1782. struct cgpu_info *cgpu = &gpus[gpu];
  1783. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1784. mvwprintw(statuswin, gpucursor + gpu, 0, " GPU %d: ", gpu);
  1785. #ifdef HAVE_ADL
  1786. if (cgpu->has_adl) {
  1787. float gt = gpu_temp(gpu);
  1788. int gf = gpu_fanspeed(gpu);
  1789. int gp = gpu_fanpercent(gpu);
  1790. if (gt != -1)
  1791. wprintw(statuswin, "%5.1fC ", gt);
  1792. else
  1793. wprintw(statuswin, " ");
  1794. if (gf != -1)
  1795. wprintw(statuswin, "%4dRPM ", gf);
  1796. else if (gp != -1)
  1797. wprintw(statuswin, "%3d%% ", gp);
  1798. else
  1799. wprintw(statuswin, " ");
  1800. wprintw(statuswin, "| ");
  1801. }
  1802. #endif
  1803. if (cgpu->status == LIFE_DEAD)
  1804. wprintw(statuswin, "DEAD ");
  1805. else if (cgpu->status == LIFE_SICK)
  1806. wprintw(statuswin, "SICK ");
  1807. else if (!gpu_devices[gpu])
  1808. wprintw(statuswin, "OFF ");
  1809. else
  1810. wprintw(statuswin, "%5.1f", cgpu->rolling);
  1811. wprintw(statuswin, "/%5.1fMh/s | A:%d R:%d HW:%d U:%.2f/m I:%d",
  1812. cgpu->total_mhashes / total_secs,
  1813. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1814. cgpu->utility, gpus[gpu].intensity);
  1815. wclrtoeol(statuswin);
  1816. } else if (thr_id >= gpu_threads) {
  1817. int cpu = dev_from_id(thr_id);
  1818. struct cgpu_info *cgpu = &cpus[cpu];
  1819. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1820. mvwprintw(statuswin, cpucursor + cpu, 0, " CPU %d: %5.2f/%5.2fMh/s | A:%d R:%d U:%.2f/m",
  1821. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1822. cgpu->accepted, cgpu->rejected,
  1823. cgpu->utility);
  1824. wclrtoeol(statuswin);
  1825. }
  1826. wnoutrefresh(statuswin);
  1827. }
  1828. static void print_status(int thr_id)
  1829. {
  1830. if (!curses_active)
  1831. text_print_status(thr_id);
  1832. }
  1833. /* Check for window resize. Called with curses mutex locked */
  1834. static inline bool change_logwinsize(void)
  1835. {
  1836. int x, y, logx, logy;
  1837. getmaxyx(mainwin, y, x);
  1838. getmaxyx(logwin, logy, logx);
  1839. y -= logcursor;
  1840. /* Detect screen size change */
  1841. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1842. wresize(logwin, y, x);
  1843. return true;
  1844. }
  1845. return false;
  1846. }
  1847. /* For mandatory printing when mutex is already locked */
  1848. static void wlog(const char *f, ...)
  1849. {
  1850. va_list ap;
  1851. va_start(ap, f);
  1852. vw_printw(logwin, f, ap);
  1853. va_end(ap);
  1854. }
  1855. /* Mandatory printing */
  1856. void wlogprint(const char *f, ...)
  1857. {
  1858. va_list ap;
  1859. if (curses_active_locked()) {
  1860. va_start(ap, f);
  1861. vw_printw(logwin, f, ap);
  1862. va_end(ap);
  1863. wrefresh(logwin);
  1864. unlock_curses();
  1865. }
  1866. }
  1867. void log_curses(int prio, const char *f, va_list ap)
  1868. {
  1869. if (opt_quiet && prio != LOG_ERR)
  1870. return;
  1871. if (curses_active_locked()) {
  1872. if (!opt_loginput || prio == LOG_ERR || prio == LOG_WARNING) {
  1873. vw_printw(logwin, f, ap);
  1874. wrefresh(logwin);
  1875. }
  1876. unlock_curses();
  1877. } else
  1878. vprintf(f, ap);
  1879. }
  1880. void clear_logwin(void)
  1881. {
  1882. if (curses_active_locked()) {
  1883. wclear(logwin);
  1884. wrefresh(logwin);
  1885. unlock_curses();
  1886. }
  1887. }
  1888. /* regenerate the full work->hash value and also return true if it's a block */
  1889. bool regeneratehash(const struct work *work)
  1890. {
  1891. uint32_t *data32 = (uint32_t *)(work->data);
  1892. unsigned char swap[128];
  1893. uint32_t *swap32 = (uint32_t *)swap;
  1894. unsigned char hash1[32];
  1895. uint32_t *hash32 = (uint32_t *)(work->hash);
  1896. uint32_t difficulty = 0;
  1897. uint32_t diffbytes = 0;
  1898. uint32_t diffvalue = 0;
  1899. uint32_t diffcmp[8];
  1900. int diffshift = 0;
  1901. int i;
  1902. for (i = 0; i < 80 / 4; i++)
  1903. swap32[i] = swab32(data32[i]);
  1904. sha2(swap, 80, hash1, false);
  1905. sha2(hash1, 32, (unsigned char *)(work->hash), false);
  1906. difficulty = swab32(*((uint32_t *)(work->data + 72)));
  1907. diffbytes = ((difficulty >> 24) & 0xff) - 3;
  1908. diffvalue = difficulty & 0x00ffffff;
  1909. diffshift = (diffbytes % 4) * 8;
  1910. if (diffshift == 0) {
  1911. diffshift = 32;
  1912. diffbytes--;
  1913. }
  1914. memset(diffcmp, 0, 32);
  1915. diffcmp[(diffbytes >> 2) + 1] = diffvalue >> (32 - diffshift);
  1916. diffcmp[diffbytes >> 2] = diffvalue << diffshift;
  1917. for (i = 7; i >= 0; i--) {
  1918. if (hash32[i] > diffcmp[i])
  1919. return false;
  1920. if (hash32[i] < diffcmp[i])
  1921. return true;
  1922. }
  1923. // https://en.bitcoin.it/wiki/Block says: "numerically below"
  1924. // https://en.bitcoin.it/wiki/Target says: "lower than or equal to"
  1925. // code in bitcoind 0.3.24 main.cpp CheckWork() says: if (hash > hashTarget) return false;
  1926. if (hash32[0] == diffcmp[0])
  1927. return true;
  1928. else
  1929. return false;
  1930. }
  1931. static bool donor(struct pool *pool)
  1932. {
  1933. return (pool == &donationpool);
  1934. }
  1935. static bool submit_upstream_work(const struct work *work)
  1936. {
  1937. char *hexstr = NULL;
  1938. json_t *val, *res;
  1939. char s[345], sd[345];
  1940. bool rc = false;
  1941. int thr_id = work->thr_id;
  1942. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1943. CURL *curl = curl_easy_init();
  1944. struct pool *pool = work->pool;
  1945. bool rolltime;
  1946. uint32_t *hash32;
  1947. char hashshow[64+1] = "";
  1948. bool isblock;
  1949. if (unlikely(!curl)) {
  1950. applog(LOG_ERR, "CURL initialisation failed");
  1951. return rc;
  1952. }
  1953. #ifdef __BIG_ENDIAN__
  1954. int swapcounter = 0;
  1955. for (swapcounter = 0; swapcounter < 32; swapcounter++)
  1956. (((uint32_t*) (work->data))[swapcounter]) = swab32(((uint32_t*) (work->data))[swapcounter]);
  1957. #endif
  1958. /* build hex string */
  1959. hexstr = bin2hex(work->data, sizeof(work->data));
  1960. if (unlikely(!hexstr)) {
  1961. applog(LOG_ERR, "submit_upstream_work OOM");
  1962. goto out_nofree;
  1963. }
  1964. /* build JSON-RPC request */
  1965. sprintf(s,
  1966. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1967. hexstr);
  1968. sprintf(sd,
  1969. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1970. hexstr);
  1971. if (opt_debug)
  1972. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1973. /* issue JSON-RPC request */
  1974. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1975. if (unlikely(!val)) {
  1976. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1977. if (!pool_tset(pool, &pool->submit_fail)) {
  1978. total_ro++;
  1979. pool->remotefail_occasions++;
  1980. if (!donor(pool))
  1981. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1982. }
  1983. goto out;
  1984. } else if (pool_tclear(pool, &pool->submit_fail)) {
  1985. if (!donor(pool))
  1986. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1987. }
  1988. res = json_object_get(val, "result");
  1989. if (!QUIET) {
  1990. isblock = regeneratehash(work);
  1991. if (isblock)
  1992. found_blocks++;
  1993. hash32 = (uint32_t *)(work->hash);
  1994. sprintf(hashshow, "%08lx.%08lx.%08lx%s",
  1995. (unsigned long)(hash32[7]), (unsigned long)(hash32[6]), (unsigned long)(hash32[5]),
  1996. isblock ? " BLOCK!" : "");
  1997. }
  1998. /* Theoretically threads could race when modifying accepted and
  1999. * rejected values but the chance of two submits completing at the
  2000. * same time is zero so there is no point adding extra locking */
  2001. if (json_is_true(res)) {
  2002. cgpu->accepted++;
  2003. total_accepted++;
  2004. pool->accepted++;
  2005. if (opt_debug)
  2006. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  2007. if (!QUIET) {
  2008. if (donor(work->pool))
  2009. applog(LOG_NOTICE, "Accepted %s %sPU %d thread %d donate",
  2010. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  2011. else if (total_pools > 1)
  2012. applog(LOG_NOTICE, "Accepted %s %sPU %d thread %d pool %d",
  2013. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  2014. else
  2015. applog(LOG_NOTICE, "Accepted %s %sPU %d thread %d",
  2016. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  2017. }
  2018. if (opt_shares && total_accepted >= opt_shares) {
  2019. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  2020. kill_work();
  2021. goto out;
  2022. }
  2023. } else {
  2024. cgpu->rejected++;
  2025. total_rejected++;
  2026. pool->rejected++;
  2027. if (opt_debug)
  2028. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  2029. if (!QUIET) {
  2030. if (donor(work->pool))
  2031. applog(LOG_NOTICE, "Rejected %s %sPU %d thread %d donate",
  2032. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  2033. else if (total_pools > 1)
  2034. applog(LOG_NOTICE, "Rejected %s %sPU %d thread %d pool %d",
  2035. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  2036. else
  2037. applog(LOG_NOTICE, "Rejected %s %sPU %d thread %d",
  2038. hashshow, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  2039. }
  2040. }
  2041. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  2042. if (!opt_realquiet)
  2043. print_status(thr_id);
  2044. if (!want_per_device_stats) {
  2045. char logline[255];
  2046. get_statline(logline, cgpu);
  2047. applog(LOG_INFO, "%s", logline);
  2048. }
  2049. json_decref(val);
  2050. rc = true;
  2051. out:
  2052. free(hexstr);
  2053. out_nofree:
  2054. curl_easy_cleanup(curl);
  2055. return rc;
  2056. }
  2057. static const char *rpc_req =
  2058. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  2059. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  2060. static inline struct pool *select_pool(bool lagging)
  2061. {
  2062. static int rotating_pool = 0;
  2063. struct pool *pool, *cp;
  2064. if (total_getworks && opt_donation > 0.0 && !donationpool.idle &&
  2065. (float)donationpool.getwork_requested / (float)total_getworks < opt_donation / 100)
  2066. return &donationpool;
  2067. cp = current_pool();
  2068. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  2069. pool = cp;
  2070. else
  2071. pool = NULL;
  2072. while (!pool) {
  2073. if (++rotating_pool >= total_pools)
  2074. rotating_pool = 0;
  2075. pool = pools[rotating_pool];
  2076. if ((!pool->idle && pool->enabled) || pool == cp)
  2077. break;
  2078. pool = NULL;
  2079. }
  2080. return pool;
  2081. }
  2082. static bool get_upstream_work(struct work *work, bool lagging)
  2083. {
  2084. struct pool *pool;
  2085. json_t *val = NULL;
  2086. bool rc = false;
  2087. int retries = 0;
  2088. CURL *curl;
  2089. curl = curl_easy_init();
  2090. if (unlikely(!curl)) {
  2091. applog(LOG_ERR, "CURL initialisation failed");
  2092. return rc;
  2093. }
  2094. pool = select_pool(lagging);
  2095. if (opt_debug)
  2096. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  2097. retry:
  2098. /* A single failure response here might be reported as a dead pool and
  2099. * there may be temporary denied messages etc. falsely reporting
  2100. * failure so retry a few times before giving up */
  2101. while (!val && retries++ < 3)
  2102. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2103. false, false, &work->rolltime, pool);
  2104. if (unlikely(!val)) {
  2105. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  2106. goto out;
  2107. }
  2108. rc = work_decode(json_object_get(val, "result"), work);
  2109. if (!rc && retries < 3)
  2110. goto retry;
  2111. work->pool = pool;
  2112. total_getworks++;
  2113. pool->getwork_requested++;
  2114. json_decref(val);
  2115. out:
  2116. curl_easy_cleanup(curl);
  2117. return rc;
  2118. }
  2119. static struct work *make_work(void)
  2120. {
  2121. struct work *work = calloc(1, sizeof(struct work));
  2122. if (unlikely(!work))
  2123. quit(1, "Failed to calloc work in make_work");
  2124. work->id = total_work++;
  2125. return work;
  2126. }
  2127. static void free_work(struct work *work)
  2128. {
  2129. free(work);
  2130. }
  2131. static void workio_cmd_free(struct workio_cmd *wc)
  2132. {
  2133. if (!wc)
  2134. return;
  2135. switch (wc->cmd) {
  2136. case WC_SUBMIT_WORK:
  2137. free_work(wc->u.work);
  2138. break;
  2139. default: /* do nothing */
  2140. break;
  2141. }
  2142. memset(wc, 0, sizeof(*wc)); /* poison */
  2143. free(wc);
  2144. }
  2145. static void disable_curses(void)
  2146. {
  2147. if (curses_active_locked()) {
  2148. curses_active = false;
  2149. leaveok(logwin, false);
  2150. leaveok(statuswin, false);
  2151. leaveok(mainwin, false);
  2152. nocbreak();
  2153. echo();
  2154. delwin(logwin);
  2155. delwin(statuswin);
  2156. delwin(mainwin);
  2157. endwin();
  2158. refresh();
  2159. #ifdef WIN32
  2160. // Move the cursor to after curses output.
  2161. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  2162. CONSOLE_SCREEN_BUFFER_INFO csbi;
  2163. COORD coord;
  2164. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  2165. coord.X = 0;
  2166. coord.Y = csbi.dwSize.Y - 1;
  2167. SetConsoleCursorPosition(hout, coord);
  2168. }
  2169. #endif
  2170. unlock_curses();
  2171. }
  2172. }
  2173. static void print_summary(void);
  2174. void kill_work(void)
  2175. {
  2176. struct thr_info *thr;
  2177. unsigned int i;
  2178. disable_curses();
  2179. applog(LOG_INFO, "Received kill message");
  2180. if (opt_debug)
  2181. applog(LOG_DEBUG, "Killing off watchdog thread");
  2182. /* Kill the watchdog thread */
  2183. thr = &thr_info[watchdog_thr_id];
  2184. thr_info_cancel(thr);
  2185. if (opt_debug)
  2186. applog(LOG_DEBUG, "Killing off mining threads");
  2187. /* Stop the mining threads*/
  2188. for (i = 0; i < mining_threads; i++) {
  2189. thr = &thr_info[i];
  2190. thr_info_cancel(thr);
  2191. }
  2192. if (opt_debug)
  2193. applog(LOG_DEBUG, "Killing off stage thread");
  2194. /* Stop the others */
  2195. thr = &thr_info[stage_thr_id];
  2196. thr_info_cancel(thr);
  2197. if (opt_debug)
  2198. applog(LOG_DEBUG, "Killing off longpoll thread");
  2199. thr = &thr_info[longpoll_thr_id];
  2200. if (have_longpoll)
  2201. thr_info_cancel(thr);
  2202. if (opt_debug)
  2203. applog(LOG_DEBUG, "Killing off work thread");
  2204. thr = &thr_info[work_thr_id];
  2205. thr_info_cancel(thr);
  2206. if (opt_debug)
  2207. applog(LOG_DEBUG, "Killing off API thread");
  2208. thr = &thr_info[api_thr_id];
  2209. thr_info_cancel(thr);
  2210. }
  2211. void quit(int status, const char *format, ...);
  2212. static void sighandler(int sig)
  2213. {
  2214. /* Restore signal handlers so we can still quit if kill_work fails */
  2215. sigaction(SIGTERM, &termhandler, NULL);
  2216. sigaction(SIGINT, &inthandler, NULL);
  2217. kill_work();
  2218. quit(sig, "Received interrupt signal.");
  2219. }
  2220. static void *get_work_thread(void *userdata)
  2221. {
  2222. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2223. struct work *ret_work;
  2224. int failures = 0;
  2225. pthread_detach(pthread_self());
  2226. ret_work = make_work();
  2227. if (wc->thr)
  2228. ret_work->thr = wc->thr;
  2229. else
  2230. ret_work->thr = NULL;
  2231. /* obtain new work from bitcoin via JSON-RPC */
  2232. while (!get_upstream_work(ret_work, wc->lagging)) {
  2233. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2234. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  2235. free_work(ret_work);
  2236. kill_work();
  2237. goto out;
  2238. }
  2239. /* pause, then restart work-request loop */
  2240. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  2241. fail_pause);
  2242. sleep(fail_pause);
  2243. fail_pause += opt_fail_pause;
  2244. }
  2245. fail_pause = opt_fail_pause;
  2246. if (opt_debug)
  2247. applog(LOG_DEBUG, "Pushing work to requesting thread");
  2248. /* send work to requesting thread */
  2249. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  2250. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  2251. kill_work();
  2252. free_work(ret_work);
  2253. }
  2254. out:
  2255. workio_cmd_free(wc);
  2256. return NULL;
  2257. }
  2258. static bool workio_get_work(struct workio_cmd *wc)
  2259. {
  2260. pthread_t get_thread;
  2261. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  2262. applog(LOG_ERR, "Failed to create get_work_thread");
  2263. return false;
  2264. }
  2265. return true;
  2266. }
  2267. static bool stale_work(struct work *work, bool share)
  2268. {
  2269. struct timeval now;
  2270. bool ret = false;
  2271. gettimeofday(&now, NULL);
  2272. if (share) {
  2273. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_expiry)
  2274. return true;
  2275. } else if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  2276. return true;
  2277. /* Don't compare donor work in case it's on a different chain */
  2278. if (donor(work->pool))
  2279. return ret;
  2280. if (work->work_block != work_block)
  2281. ret = true;
  2282. return ret;
  2283. }
  2284. static void *submit_work_thread(void *userdata)
  2285. {
  2286. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  2287. struct work *work = wc->u.work;
  2288. struct pool *pool = work->pool;
  2289. int failures = 0;
  2290. pthread_detach(pthread_self());
  2291. if (!opt_submit_stale && stale_work(work, true)) {
  2292. applog(LOG_NOTICE, "Stale share detected, discarding");
  2293. total_stale++;
  2294. pool->stale_shares++;
  2295. goto out;
  2296. }
  2297. /* submit solution to bitcoin via JSON-RPC */
  2298. while (!submit_upstream_work(work)) {
  2299. if (!opt_submit_stale && stale_work(work, true)) {
  2300. applog(LOG_NOTICE, "Stale share detected, discarding");
  2301. total_stale++;
  2302. pool->stale_shares++;
  2303. break;
  2304. }
  2305. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  2306. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  2307. kill_work();
  2308. break;
  2309. }
  2310. /* pause, then restart work-request loop */
  2311. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  2312. fail_pause);
  2313. sleep(fail_pause);
  2314. fail_pause += opt_fail_pause;
  2315. }
  2316. fail_pause = opt_fail_pause;
  2317. out:
  2318. workio_cmd_free(wc);
  2319. return NULL;
  2320. }
  2321. static bool workio_submit_work(struct workio_cmd *wc)
  2322. {
  2323. pthread_t submit_thread;
  2324. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  2325. applog(LOG_ERR, "Failed to create submit_work_thread");
  2326. return false;
  2327. }
  2328. return true;
  2329. }
  2330. /* Find the pool that currently has the highest priority */
  2331. static struct pool *priority_pool(int choice)
  2332. {
  2333. struct pool *ret = NULL;
  2334. int i;
  2335. for (i = 0; i < total_pools; i++) {
  2336. struct pool *pool = pools[i];
  2337. if (pool->prio == choice) {
  2338. ret = pool;
  2339. break;
  2340. }
  2341. }
  2342. if (unlikely(!ret)) {
  2343. applog(LOG_ERR, "WTF No pool %d found!", choice);
  2344. return pools[choice];
  2345. }
  2346. return ret;
  2347. }
  2348. static void switch_pools(struct pool *selected)
  2349. {
  2350. struct pool *pool, *last_pool;
  2351. int i, pool_no;
  2352. mutex_lock(&control_lock);
  2353. last_pool = currentpool;
  2354. pool_no = currentpool->pool_no;
  2355. /* Switch selected to pool number 0 and move the rest down */
  2356. if (selected) {
  2357. if (selected->prio != 0) {
  2358. for (i = 0; i < total_pools; i++) {
  2359. pool = pools[i];
  2360. if (pool->prio < selected->prio)
  2361. pool->prio++;
  2362. }
  2363. selected->prio = 0;
  2364. }
  2365. }
  2366. switch (pool_strategy) {
  2367. /* Both of these set to the master pool */
  2368. case POOL_FAILOVER:
  2369. case POOL_LOADBALANCE:
  2370. for (i = 0; i < total_pools; i++) {
  2371. pool = priority_pool(i);
  2372. if (!pool->idle && pool->enabled) {
  2373. pool_no = pool->pool_no;
  2374. break;
  2375. }
  2376. }
  2377. break;
  2378. /* Both of these simply increment and cycle */
  2379. case POOL_ROUNDROBIN:
  2380. case POOL_ROTATE:
  2381. if (selected) {
  2382. pool_no = selected->pool_no;
  2383. break;
  2384. }
  2385. pool_no++;
  2386. if (pool_no >= total_pools)
  2387. pool_no = 0;
  2388. break;
  2389. default:
  2390. break;
  2391. }
  2392. currentpool = pools[pool_no];
  2393. pool = currentpool;
  2394. mutex_unlock(&control_lock);
  2395. if (pool != last_pool)
  2396. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  2397. /* Reset the queued amount to allow more to be queued for the new pool */
  2398. mutex_lock(&qd_lock);
  2399. total_queued = 0;
  2400. mutex_unlock(&qd_lock);
  2401. }
  2402. static void discard_work(struct work *work)
  2403. {
  2404. if (!work->clone && !work->rolls && !work->mined) {
  2405. if (work->pool)
  2406. work->pool->discarded_work++;
  2407. total_discarded++;
  2408. if (opt_debug)
  2409. applog(LOG_DEBUG, "Discarded work");
  2410. } else if (opt_debug)
  2411. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  2412. free_work(work);
  2413. }
  2414. /* This is overkill, but at least we'll know accurately how much work is
  2415. * queued to prevent ever being left without work */
  2416. static void inc_queued(void)
  2417. {
  2418. mutex_lock(&qd_lock);
  2419. total_queued++;
  2420. mutex_unlock(&qd_lock);
  2421. }
  2422. static void dec_queued(void)
  2423. {
  2424. mutex_lock(&qd_lock);
  2425. if (total_queued > 0)
  2426. total_queued--;
  2427. mutex_unlock(&qd_lock);
  2428. }
  2429. static int requests_queued(void)
  2430. {
  2431. int ret;
  2432. mutex_lock(&qd_lock);
  2433. ret = total_queued;
  2434. mutex_unlock(&qd_lock);
  2435. return ret;
  2436. }
  2437. static int discard_stale(void)
  2438. {
  2439. struct work *work, *tmp;
  2440. int i, stale = 0;
  2441. mutex_lock(stgd_lock);
  2442. HASH_ITER(hh, staged_work, work, tmp) {
  2443. if (stale_work(work, false)) {
  2444. HASH_DEL(staged_work, work);
  2445. if (work->clone)
  2446. --staged_clones;
  2447. discard_work(work);
  2448. stale++;
  2449. }
  2450. }
  2451. mutex_unlock(stgd_lock);
  2452. if (opt_debug)
  2453. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  2454. /* Dec queued outside the loop to not have recursive locks */
  2455. for (i = 0; i < stale; i++)
  2456. dec_queued();
  2457. return stale;
  2458. }
  2459. static bool queue_request(struct thr_info *thr, bool needed);
  2460. static void restart_threads(void)
  2461. {
  2462. int i, stale;
  2463. /* Discard staged work that is now stale */
  2464. stale = discard_stale();
  2465. for (i = 0; i < stale; i++)
  2466. queue_request(NULL, true);
  2467. for (i = 0; i < mining_threads; i++)
  2468. work_restart[i].restart = 1;
  2469. }
  2470. static void set_curblock(char *hexstr, unsigned char *hash)
  2471. {
  2472. unsigned char hash_swap[32];
  2473. char *old_hash = NULL;
  2474. struct timeval tv_now;
  2475. /* Don't free current_hash directly to avoid dereferencing it when
  2476. * we might be accessing its data elsewhere */
  2477. if (current_hash)
  2478. old_hash = current_hash;
  2479. strcpy(current_block, hexstr);
  2480. gettimeofday(&tv_now, NULL);
  2481. get_timestamp(blocktime, &tv_now);
  2482. swap256(hash_swap, hash);
  2483. current_hash = bin2hex(hash_swap, 16);
  2484. if (unlikely(!current_hash))
  2485. quit (1, "set_curblock OOM");
  2486. if (old_hash)
  2487. free(old_hash);
  2488. }
  2489. static void test_work_current(struct work *work, bool longpoll)
  2490. {
  2491. struct block *s;
  2492. char *hexstr;
  2493. /* Allow donation to not set current work, so it will work even if
  2494. * mining on a different chain */
  2495. if (donor(work->pool))
  2496. return;
  2497. hexstr = bin2hex(work->data, 18);
  2498. if (unlikely(!hexstr)) {
  2499. applog(LOG_ERR, "stage_thread OOM");
  2500. return;
  2501. }
  2502. /* Search to see if this block exists yet and if not, consider it a
  2503. * new block and set the current block details to this one */
  2504. rd_lock(&blk_lock);
  2505. HASH_FIND_STR(blocks, hexstr, s);
  2506. rd_unlock(&blk_lock);
  2507. if (!s) {
  2508. s = calloc(sizeof(struct block), 1);
  2509. if (unlikely(!s))
  2510. quit (1, "test_work_current OOM");
  2511. strcpy(s->hash, hexstr);
  2512. wr_lock(&blk_lock);
  2513. HASH_ADD_STR(blocks, hash, s);
  2514. wr_unlock(&blk_lock);
  2515. set_curblock(hexstr, work->data);
  2516. if (unlikely(++new_blocks == 1))
  2517. goto out_free;
  2518. work_block++;
  2519. if (longpoll)
  2520. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  2521. else if (have_longpoll)
  2522. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  2523. else
  2524. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  2525. restart_threads();
  2526. } else if (longpoll) {
  2527. applog(LOG_NOTICE, "LONGPOLL requested work restart, waiting on fresh work");
  2528. work_block++;
  2529. restart_threads();
  2530. }
  2531. out_free:
  2532. free(hexstr);
  2533. }
  2534. static int tv_sort(struct work *worka, struct work *workb)
  2535. {
  2536. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  2537. }
  2538. static bool hash_push(struct work *work)
  2539. {
  2540. bool rc = true;
  2541. mutex_lock(stgd_lock);
  2542. if (likely(!getq->frozen)) {
  2543. HASH_ADD_INT(staged_work, id, work);
  2544. HASH_SORT(staged_work, tv_sort);
  2545. if (work->clone)
  2546. ++staged_clones;
  2547. } else
  2548. rc = false;
  2549. pthread_cond_signal(&getq->cond);
  2550. mutex_unlock(stgd_lock);
  2551. return rc;
  2552. }
  2553. static void *stage_thread(void *userdata)
  2554. {
  2555. struct thr_info *mythr = userdata;
  2556. bool ok = true;
  2557. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2558. while (ok) {
  2559. struct work *work = NULL;
  2560. if (opt_debug)
  2561. applog(LOG_DEBUG, "Popping work to stage thread");
  2562. work = tq_pop(mythr->q, NULL);
  2563. if (unlikely(!work)) {
  2564. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2565. ok = false;
  2566. break;
  2567. }
  2568. work->work_block = work_block;
  2569. test_work_current(work, false);
  2570. if (opt_debug)
  2571. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2572. if (unlikely(!hash_push(work))) {
  2573. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2574. continue;
  2575. }
  2576. }
  2577. tq_freeze(mythr->q);
  2578. return NULL;
  2579. }
  2580. int curses_int(const char *query)
  2581. {
  2582. int ret;
  2583. char *cvar;
  2584. cvar = curses_input(query);
  2585. ret = atoi(cvar);
  2586. free(cvar);
  2587. return ret;
  2588. }
  2589. static bool input_pool(bool live);
  2590. static int active_pools(void)
  2591. {
  2592. int ret = 0;
  2593. int i;
  2594. for (i = 0; i < total_pools; i++) {
  2595. if ((pools[i])->enabled)
  2596. ret++;
  2597. }
  2598. return ret;
  2599. }
  2600. static void display_pool_summary(struct pool *pool)
  2601. {
  2602. double efficiency = 0.0;
  2603. if (curses_active_locked()) {
  2604. wlog("Pool: %s\n", pool->rpc_url);
  2605. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2606. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2607. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2608. wlog(" Accepted shares: %d\n", pool->accepted);
  2609. wlog(" Rejected shares: %d\n", pool->rejected);
  2610. if (pool->accepted || pool->rejected)
  2611. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2612. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2613. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2614. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2615. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2616. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2617. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2618. wrefresh(logwin);
  2619. unlock_curses();
  2620. }
  2621. }
  2622. /* We can't remove the memory used for this struct pool because there may
  2623. * still be work referencing it. We just remove it from the pools list */
  2624. static void remove_pool(struct pool *pool)
  2625. {
  2626. int i, last_pool = total_pools - 1;
  2627. struct pool *other;
  2628. /* Boost priority of any lower prio than this one */
  2629. for (i = 0; i < total_pools; i++) {
  2630. other = pools[i];
  2631. if (other->prio > pool->prio)
  2632. other->prio--;
  2633. }
  2634. if (pool->pool_no < last_pool) {
  2635. /* Swap the last pool for this one */
  2636. (pools[last_pool])->pool_no = pool->pool_no;
  2637. pools[pool->pool_no] = pools[last_pool];
  2638. }
  2639. /* Give it an invalid number */
  2640. pool->pool_no = total_pools;
  2641. total_pools--;
  2642. }
  2643. static void write_config(FILE *fcfg)
  2644. {
  2645. int i;
  2646. /* Write pool values */
  2647. fputs("{\n\"pools\" : [", fcfg);
  2648. for(i = 0; i < total_pools; i++) {
  2649. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  2650. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  2651. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  2652. }
  2653. fputs("\n],\n\n", fcfg);
  2654. if (nDevs) {
  2655. /* Write GPU device values */
  2656. fputs("\"intensity\" : \"", fcfg);
  2657. for(i = 0; i < nDevs; i++)
  2658. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  2659. #ifdef HAVE_ADL
  2660. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  2661. for(i = 0; i < nDevs; i++)
  2662. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  2663. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  2664. for(i = 0; i < nDevs; i++)
  2665. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  2666. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  2667. for(i = 0; i < nDevs; i++)
  2668. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  2669. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  2670. for(i = 0; i < nDevs; i++)
  2671. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  2672. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  2673. for(i = 0; i < nDevs; i++)
  2674. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  2675. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  2676. for(i = 0; i < nDevs; i++)
  2677. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.cutofftemp);
  2678. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  2679. for(i = 0; i < nDevs; i++)
  2680. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  2681. fputs("\",\n\"temp-target\" : \"", fcfg);
  2682. for(i = 0; i < nDevs; i++)
  2683. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  2684. #endif
  2685. fputs("\",\n", fcfg);
  2686. }
  2687. fprintf(fcfg, "\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  2688. /* Simple bool and int options */
  2689. struct opt_table *opt;
  2690. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  2691. char *p, *name = strdup(opt->names);
  2692. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  2693. if (p[1] != '-')
  2694. continue;
  2695. if (opt->type & OPT_NOARG &&
  2696. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  2697. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  2698. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  2699. if (opt->type & OPT_HASARG &&
  2700. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  2701. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  2702. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  2703. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  2704. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  2705. }
  2706. }
  2707. /* Special case options */
  2708. fprintf(fcfg, ",\n\n\"donation\" : \"%.2f\"", opt_donation);
  2709. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  2710. if (pool_strategy == POOL_LOADBALANCE)
  2711. fputs(",\n\"load-balance\" : true", fcfg);
  2712. if (pool_strategy == POOL_ROUNDROBIN)
  2713. fputs(",\n\"round-robin\" : true", fcfg);
  2714. if (pool_strategy == POOL_ROTATE)
  2715. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  2716. #if defined(unix)
  2717. if (opt_stderr_cmd && *opt_stderr_cmd)
  2718. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  2719. #endif // defined(unix)
  2720. if (opt_kernel && *opt_kernel)
  2721. fprintf(fcfg, ",\n\"kernel\" : \"%s\"", opt_kernel);
  2722. if (opt_kernel_path && *opt_kernel_path) {
  2723. char *kpath = strdup(opt_kernel_path);
  2724. if (kpath[strlen(kpath)-1] == '/')
  2725. kpath[strlen(kpath)-1] = 0;
  2726. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  2727. }
  2728. if (schedstart.enable)
  2729. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  2730. if (schedstop.enable)
  2731. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  2732. for(i = 0; i < nDevs; i++)
  2733. if (!gpu_devices[i])
  2734. break;
  2735. if (i < nDevs)
  2736. for(i = 0; i < nDevs; i++)
  2737. if (gpu_devices[i])
  2738. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  2739. fputs("\n}", fcfg);
  2740. }
  2741. static void display_pools(void)
  2742. {
  2743. struct pool *pool;
  2744. int selected, i;
  2745. char input;
  2746. opt_loginput = true;
  2747. immedok(logwin, true);
  2748. clear_logwin();
  2749. updated:
  2750. for (i = 0; i < total_pools; i++) {
  2751. pool = pools[i];
  2752. if (pool == current_pool())
  2753. wattron(logwin, A_BOLD);
  2754. if (!pool->enabled)
  2755. wattron(logwin, A_DIM);
  2756. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2757. pool->pool_no,
  2758. pool->enabled? "Enabled" : "Disabled",
  2759. pool->idle? "Dead" : "Alive",
  2760. pool->prio,
  2761. pool->rpc_url, pool->rpc_user);
  2762. wattroff(logwin, A_BOLD | A_DIM);
  2763. }
  2764. retry:
  2765. wlogprint("\nCurrent pool management strategy: %s\n",
  2766. strategies[pool_strategy]);
  2767. if (pool_strategy == POOL_ROTATE)
  2768. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2769. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2770. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2771. wlogprint("Or press any other key to continue\n");
  2772. input = getch();
  2773. if (!strncasecmp(&input, "a", 1)) {
  2774. input_pool(true);
  2775. goto updated;
  2776. } else if (!strncasecmp(&input, "r", 1)) {
  2777. if (total_pools <= 1) {
  2778. wlogprint("Cannot remove last pool");
  2779. goto retry;
  2780. }
  2781. selected = curses_int("Select pool number");
  2782. if (selected < 0 || selected >= total_pools) {
  2783. wlogprint("Invalid selection\n");
  2784. goto retry;
  2785. }
  2786. pool = pools[selected];
  2787. if (pool == current_pool())
  2788. switch_pools(NULL);
  2789. if (pool == current_pool()) {
  2790. wlogprint("Unable to remove pool due to activity\n");
  2791. goto retry;
  2792. }
  2793. pool->enabled = false;
  2794. remove_pool(pool);
  2795. goto updated;
  2796. } else if (!strncasecmp(&input, "s", 1)) {
  2797. selected = curses_int("Select pool number");
  2798. if (selected < 0 || selected >= total_pools) {
  2799. wlogprint("Invalid selection\n");
  2800. goto retry;
  2801. }
  2802. pool = pools[selected];
  2803. pool->enabled = true;
  2804. switch_pools(pool);
  2805. goto updated;
  2806. } else if (!strncasecmp(&input, "d", 1)) {
  2807. if (active_pools() <= 1) {
  2808. wlogprint("Cannot disable last pool");
  2809. goto retry;
  2810. }
  2811. selected = curses_int("Select pool number");
  2812. if (selected < 0 || selected >= total_pools) {
  2813. wlogprint("Invalid selection\n");
  2814. goto retry;
  2815. }
  2816. pool = pools[selected];
  2817. pool->enabled = false;
  2818. if (pool == current_pool())
  2819. switch_pools(NULL);
  2820. goto updated;
  2821. } else if (!strncasecmp(&input, "e", 1)) {
  2822. selected = curses_int("Select pool number");
  2823. if (selected < 0 || selected >= total_pools) {
  2824. wlogprint("Invalid selection\n");
  2825. goto retry;
  2826. }
  2827. pool = pools[selected];
  2828. pool->enabled = true;
  2829. if (pool->prio < current_pool()->prio)
  2830. switch_pools(pool);
  2831. goto updated;
  2832. } else if (!strncasecmp(&input, "c", 1)) {
  2833. for (i = 0; i <= TOP_STRATEGY; i++)
  2834. wlogprint("%d: %s\n", i, strategies[i]);
  2835. selected = curses_int("Select strategy number type");
  2836. if (selected < 0 || selected > TOP_STRATEGY) {
  2837. wlogprint("Invalid selection\n");
  2838. goto retry;
  2839. }
  2840. if (selected == POOL_ROTATE) {
  2841. opt_rotate_period = curses_int("Select interval in minutes");
  2842. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2843. opt_rotate_period = 0;
  2844. wlogprint("Invalid selection\n");
  2845. goto retry;
  2846. }
  2847. }
  2848. pool_strategy = selected;
  2849. switch_pools(NULL);
  2850. goto updated;
  2851. } else if (!strncasecmp(&input, "i", 1)) {
  2852. selected = curses_int("Select pool number");
  2853. if (selected < 0 || selected >= total_pools) {
  2854. wlogprint("Invalid selection\n");
  2855. goto retry;
  2856. }
  2857. pool = pools[selected];
  2858. display_pool_summary(pool);
  2859. goto retry;
  2860. } else
  2861. clear_logwin();
  2862. immedok(logwin, false);
  2863. opt_loginput = false;
  2864. }
  2865. static void display_options(void)
  2866. {
  2867. int selected;
  2868. char input;
  2869. opt_loginput = true;
  2870. immedok(logwin, true);
  2871. clear_logwin();
  2872. retry:
  2873. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2874. 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",
  2875. opt_debug ? "on" : "off",
  2876. want_per_device_stats? "on" : "off",
  2877. opt_quiet ? "on" : "off",
  2878. opt_log_output ? "on" : "off",
  2879. opt_protocol ? "on" : "off",
  2880. opt_log_interval);
  2881. wlogprint("Select an option or any other key to return\n");
  2882. input = getch();
  2883. if (!strncasecmp(&input, "q", 1)) {
  2884. opt_quiet ^= true;
  2885. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2886. goto retry;
  2887. } else if (!strncasecmp(&input, "v", 1)) {
  2888. opt_log_output ^= true;
  2889. if (opt_log_output)
  2890. opt_quiet = false;
  2891. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2892. goto retry;
  2893. } else if (!strncasecmp(&input, "n", 1)) {
  2894. opt_log_output = false;
  2895. opt_debug = false;
  2896. opt_quiet = false;
  2897. opt_protocol = false;
  2898. want_per_device_stats = false;
  2899. wlogprint("Output mode reset to normal\n");
  2900. goto retry;
  2901. } else if (!strncasecmp(&input, "d", 1)) {
  2902. opt_debug ^= true;
  2903. opt_log_output = opt_debug;
  2904. if (opt_debug)
  2905. opt_quiet = false;
  2906. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2907. goto retry;
  2908. } else if (!strncasecmp(&input, "p", 1)) {
  2909. want_per_device_stats ^= true;
  2910. opt_log_output = want_per_device_stats;
  2911. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2912. goto retry;
  2913. } else if (!strncasecmp(&input, "r", 1)) {
  2914. opt_protocol ^= true;
  2915. if (opt_protocol)
  2916. opt_quiet = false;
  2917. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2918. goto retry;
  2919. } else if (!strncasecmp(&input, "c", 1))
  2920. clear_logwin();
  2921. else if (!strncasecmp(&input, "l", 1)) {
  2922. selected = curses_int("Interval in seconds");
  2923. if (selected < 0 || selected > 9999) {
  2924. wlogprint("Invalid selection\n");
  2925. goto retry;
  2926. }
  2927. opt_log_interval = selected;
  2928. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2929. goto retry;
  2930. } else if (!strncasecmp(&input, "s", 1)) {
  2931. opt_realquiet = true;
  2932. } else
  2933. clear_logwin();
  2934. immedok(logwin, false);
  2935. opt_loginput = false;
  2936. }
  2937. static void start_longpoll(void);
  2938. static void stop_longpoll(void);
  2939. static void set_options(void)
  2940. {
  2941. int selected;
  2942. char input;
  2943. opt_loginput = true;
  2944. immedok(logwin, true);
  2945. clear_logwin();
  2946. retry:
  2947. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2948. 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",
  2949. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  2950. wlogprint("Select an option or any other key to return\n");
  2951. input = getch();
  2952. if (!strncasecmp(&input, "q", 1)) {
  2953. selected = curses_int("Extra work items to queue");
  2954. if (selected < 0 || selected > 9999) {
  2955. wlogprint("Invalid selection\n");
  2956. goto retry;
  2957. }
  2958. opt_queue = selected;
  2959. goto retry;
  2960. } else if (!strncasecmp(&input, "l", 1)) {
  2961. want_longpoll ^= true;
  2962. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2963. if (!want_longpoll) {
  2964. if (have_longpoll)
  2965. stop_longpoll();
  2966. } else
  2967. start_longpoll();
  2968. goto retry;
  2969. } else if (!strncasecmp(&input, "s", 1)) {
  2970. selected = curses_int("Set scantime in seconds");
  2971. if (selected < 0 || selected > 9999) {
  2972. wlogprint("Invalid selection\n");
  2973. goto retry;
  2974. }
  2975. opt_scantime = selected;
  2976. goto retry;
  2977. } else if (!strncasecmp(&input, "e", 1)) {
  2978. selected = curses_int("Set expiry time in seconds");
  2979. if (selected < 0 || selected > 9999) {
  2980. wlogprint("Invalid selection\n");
  2981. goto retry;
  2982. }
  2983. opt_expiry = selected;
  2984. goto retry;
  2985. } else if (!strncasecmp(&input, "r", 1)) {
  2986. selected = curses_int("Retries before failing (-1 infinite)");
  2987. if (selected < -1 || selected > 9999) {
  2988. wlogprint("Invalid selection\n");
  2989. goto retry;
  2990. }
  2991. opt_retries = selected;
  2992. goto retry;
  2993. } else if (!strncasecmp(&input, "p", 1)) {
  2994. selected = curses_int("Seconds to pause before network retries");
  2995. if (selected < 1 || selected > 9999) {
  2996. wlogprint("Invalid selection\n");
  2997. goto retry;
  2998. }
  2999. opt_fail_pause = selected;
  3000. goto retry;
  3001. } else if (!strncasecmp(&input, "w", 1)) {
  3002. FILE *fcfg;
  3003. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  3004. #if defined(unix)
  3005. strcpy(filename, getenv("HOME"));
  3006. if (*filename)
  3007. strcat(filename, "/");
  3008. else
  3009. strcpy(filename, "");
  3010. strcat(filename, ".cgminer/");
  3011. mkdir(filename, 0777);
  3012. #else
  3013. strcpy(filename, "");
  3014. #endif
  3015. strcat(filename, def_conf);
  3016. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  3017. str = curses_input(prompt);
  3018. if (strcmp(str, "-1")) {
  3019. struct stat statbuf;
  3020. strcpy(filename, str);
  3021. if (!stat(filename, &statbuf)) {
  3022. wlogprint("File exists, overwrite?\n");
  3023. input = getch();
  3024. if (strncasecmp(&input, "y", 1))
  3025. goto retry;
  3026. }
  3027. }
  3028. fcfg = fopen(filename, "w");
  3029. if (!fcfg) {
  3030. wlogprint("Cannot open or create file\n");
  3031. goto retry;
  3032. }
  3033. write_config(fcfg);
  3034. fclose(fcfg);
  3035. goto retry;
  3036. } else
  3037. clear_logwin();
  3038. immedok(logwin, false);
  3039. opt_loginput = false;
  3040. }
  3041. #ifdef HAVE_OPENCL
  3042. void reinit_device(struct cgpu_info *cgpu);
  3043. static void manage_gpu(void)
  3044. {
  3045. struct thr_info *thr;
  3046. int selected, gpu, i;
  3047. char checkin[40];
  3048. char input;
  3049. if (!opt_g_threads)
  3050. return;
  3051. opt_loginput = true;
  3052. immedok(logwin, true);
  3053. clear_logwin();
  3054. retry:
  3055. for (gpu = 0; gpu < nDevs; gpu++) {
  3056. struct cgpu_info *cgpu = &gpus[gpu];
  3057. wlog("GPU %d: %.1f / %.1f Mh/s | A:%d R:%d HW:%d U:%.2f/m I:%d\n",
  3058. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  3059. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3060. cgpu->utility, cgpu->intensity);
  3061. #ifdef HAVE_ADL
  3062. if (gpus[gpu].has_adl) {
  3063. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3064. float temp = 0, vddc = 0;
  3065. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune)) {
  3066. char logline[255];
  3067. strcpy(logline, ""); // In case it has no data
  3068. if (temp != -1)
  3069. sprintf(logline, "%.1f C ", temp);
  3070. if (fanspeed != -1 || fanpercent != -1) {
  3071. tailsprintf(logline, "F: ");
  3072. if (fanpercent != -1)
  3073. tailsprintf(logline, "%d%% ", fanpercent);
  3074. if (fanspeed != -1)
  3075. tailsprintf(logline, "(%d RPM) ", fanspeed);
  3076. tailsprintf(logline, " ");
  3077. }
  3078. if (engineclock != -1)
  3079. tailsprintf(logline, "E: %d MHz ", engineclock);
  3080. if (memclock != -1)
  3081. tailsprintf(logline, "M: %d Mhz ", memclock);
  3082. if (vddc != -1)
  3083. tailsprintf(logline, "V: %.3fV ", vddc);
  3084. if (activity != -1)
  3085. tailsprintf(logline, "A: %d%% ", activity);
  3086. if (powertune != -1)
  3087. tailsprintf(logline, "P: %d%%", powertune);
  3088. tailsprintf(logline, "\n");
  3089. wlog(logline);
  3090. }
  3091. }
  3092. #endif
  3093. wlog("Last initialised: %s\n", cgpu->init);
  3094. wlog("Intensity: ");
  3095. if (gpus[gpu].dynamic)
  3096. wlog("Dynamic\n");
  3097. else
  3098. wlog("%d\n", gpus[gpu].intensity);
  3099. for (i = 0; i < mining_threads; i++) {
  3100. thr = &thr_info[i];
  3101. if (thr->cgpu != cgpu)
  3102. continue;
  3103. get_datestamp(checkin, &thr->last);
  3104. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  3105. switch (cgpu->status) {
  3106. default:
  3107. case LIFE_WELL:
  3108. wlog("ALIVE");
  3109. break;
  3110. case LIFE_SICK:
  3111. wlog("SICK reported in %s", checkin);
  3112. break;
  3113. case LIFE_DEAD:
  3114. wlog("DEAD reported in %s", checkin);
  3115. break;
  3116. case LIFE_NOSTART:
  3117. wlog("Never started");
  3118. break;
  3119. }
  3120. wlog("\n");
  3121. }
  3122. wlog("\n");
  3123. }
  3124. wlogprint("[E]nable [D]isable [I]ntensity [R]estart GPU %s\n",adl_active ? "[C]hange settings" : "");
  3125. wlogprint("Or press any other key to continue\n");
  3126. input = getch();
  3127. if (nDevs == 1)
  3128. selected = 0;
  3129. else
  3130. selected = -1;
  3131. if (!strncasecmp(&input, "e", 1)) {
  3132. if (selected)
  3133. selected = curses_int("Select GPU to enable");
  3134. if (selected < 0 || selected >= nDevs) {
  3135. wlogprint("Invalid selection\n");
  3136. goto retry;
  3137. }
  3138. if (gpu_devices[selected]) {
  3139. wlogprint("Device already enabled\n");
  3140. goto retry;
  3141. }
  3142. gpu_devices[selected] = true;
  3143. for (i = 0; i < gpu_threads; i++) {
  3144. if (dev_from_id(i) != selected)
  3145. continue;
  3146. thr = &thr_info[i];
  3147. if (thr->cgpu->status != LIFE_WELL) {
  3148. wlogprint("Must restart device before enabling it");
  3149. gpu_devices[selected] = false;
  3150. goto retry;
  3151. }
  3152. if (opt_debug)
  3153. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3154. tq_push(thr->q, &ping);
  3155. }
  3156. goto retry;
  3157. } if (!strncasecmp(&input, "d", 1)) {
  3158. if (selected)
  3159. selected = curses_int("Select GPU to disable");
  3160. if (selected < 0 || selected >= nDevs) {
  3161. wlogprint("Invalid selection\n");
  3162. goto retry;
  3163. }
  3164. if (!gpu_devices[selected]) {
  3165. wlogprint("Device already disabled\n");
  3166. goto retry;
  3167. }
  3168. gpu_devices[selected] = false;
  3169. goto retry;
  3170. } else if (!strncasecmp(&input, "i", 1)) {
  3171. int intensity;
  3172. char *intvar;
  3173. if (selected)
  3174. selected = curses_int("Select GPU to change intensity on");
  3175. if (selected < 0 || selected >= nDevs) {
  3176. wlogprint("Invalid selection\n");
  3177. goto retry;
  3178. }
  3179. intvar = curses_input("Set GPU scan intensity (d or -10 -> 10)");
  3180. if (!intvar) {
  3181. wlogprint("Invalid input\n");
  3182. goto retry;
  3183. }
  3184. if (!strncasecmp(intvar, "d", 1)) {
  3185. wlogprint("Dynamic mode enabled on gpu %d\n", selected);
  3186. gpus[selected].dynamic = true;
  3187. free(intvar);
  3188. goto retry;
  3189. }
  3190. intensity = atoi(intvar);
  3191. free(intvar);
  3192. if (intensity < -10 || intensity > 10) {
  3193. wlogprint("Invalid selection\n");
  3194. goto retry;
  3195. }
  3196. gpus[selected].dynamic = false;
  3197. gpus[selected].intensity = intensity;
  3198. wlogprint("Intensity on gpu %d set to %d\n", selected, intensity);
  3199. goto retry;
  3200. } else if (!strncasecmp(&input, "r", 1)) {
  3201. if (selected)
  3202. selected = curses_int("Select GPU to attempt to restart");
  3203. if (selected < 0 || selected >= nDevs) {
  3204. wlogprint("Invalid selection\n");
  3205. goto retry;
  3206. }
  3207. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  3208. reinit_device(&gpus[selected]);
  3209. goto retry;
  3210. } else if (adl_active && (!strncasecmp(&input, "c", 1))) {
  3211. if (selected)
  3212. selected = curses_int("Select GPU to change settings on");
  3213. if (selected < 0 || selected >= nDevs) {
  3214. wlogprint("Invalid selection\n");
  3215. goto retry;
  3216. }
  3217. change_gpusettings(selected);
  3218. goto retry;
  3219. } else
  3220. clear_logwin();
  3221. immedok(logwin, false);
  3222. opt_loginput = false;
  3223. }
  3224. #else
  3225. static void manage_gpu(void)
  3226. {
  3227. }
  3228. #endif
  3229. static void *input_thread(void *userdata)
  3230. {
  3231. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3232. if (!curses_active)
  3233. return NULL;
  3234. while (1) {
  3235. char input;
  3236. input = getch();
  3237. if (!strncasecmp(&input, "q", 1)) {
  3238. kill_work();
  3239. return NULL;
  3240. } else if (!strncasecmp(&input, "d", 1))
  3241. display_options();
  3242. else if (!strncasecmp(&input, "p", 1))
  3243. display_pools();
  3244. else if (!strncasecmp(&input, "s", 1))
  3245. set_options();
  3246. else if (gpu_threads && !strncasecmp(&input, "g", 1))
  3247. manage_gpu();
  3248. if (opt_realquiet) {
  3249. disable_curses();
  3250. break;
  3251. }
  3252. }
  3253. return NULL;
  3254. }
  3255. static void *workio_thread(void *userdata)
  3256. {
  3257. struct thr_info *mythr = userdata;
  3258. bool ok = true;
  3259. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3260. while (ok) {
  3261. struct workio_cmd *wc;
  3262. if (opt_debug)
  3263. applog(LOG_DEBUG, "Popping work to work thread");
  3264. /* wait for workio_cmd sent to us, on our queue */
  3265. wc = tq_pop(mythr->q, NULL);
  3266. if (unlikely(!wc)) {
  3267. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  3268. ok = false;
  3269. break;
  3270. }
  3271. /* process workio_cmd */
  3272. switch (wc->cmd) {
  3273. case WC_GET_WORK:
  3274. ok = workio_get_work(wc);
  3275. break;
  3276. case WC_SUBMIT_WORK:
  3277. ok = workio_submit_work(wc);
  3278. break;
  3279. default:
  3280. ok = false;
  3281. break;
  3282. }
  3283. }
  3284. tq_freeze(mythr->q);
  3285. return NULL;
  3286. }
  3287. static void *api_thread(void *userdata)
  3288. {
  3289. struct thr_info *mythr = userdata;
  3290. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3291. api();
  3292. PTH(mythr) = 0L;
  3293. return NULL;
  3294. }
  3295. static void thread_reportin(struct thr_info *thr)
  3296. {
  3297. gettimeofday(&thr->last, NULL);
  3298. thr->cgpu->status = LIFE_WELL;
  3299. thr->getwork = false;
  3300. }
  3301. static inline void thread_reportout(struct thr_info *thr)
  3302. {
  3303. thr->getwork = true;
  3304. }
  3305. static void hashmeter(int thr_id, struct timeval *diff,
  3306. unsigned long hashes_done)
  3307. {
  3308. struct timeval temp_tv_end, total_diff;
  3309. double secs;
  3310. double local_secs;
  3311. double utility, efficiency = 0.0;
  3312. static double local_mhashes_done = 0;
  3313. static double rolling = 0;
  3314. double local_mhashes = (double)hashes_done / 1000000.0;
  3315. bool showlog = false;
  3316. /* Update the last time this thread reported in */
  3317. if (thr_id >= 0)
  3318. gettimeofday(&thr_info[thr_id].last, NULL);
  3319. /* Don't bother calculating anything if we're not displaying it */
  3320. if (opt_realquiet || !opt_log_interval)
  3321. return;
  3322. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  3323. /* So we can call hashmeter from a non worker thread */
  3324. if (thr_id >= 0) {
  3325. struct thr_info *thr = &thr_info[thr_id];
  3326. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  3327. double thread_rolling = 0.0;
  3328. int i;
  3329. if (opt_debug)
  3330. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  3331. thr_id, hashes_done, hashes_done / secs);
  3332. /* Rolling average for each thread and each device */
  3333. decay_time(&thr->rolling, local_mhashes / secs);
  3334. for (i = 0; i < mining_threads; i++) {
  3335. struct thr_info *th = &thr_info[i];
  3336. if (th->cgpu == cgpu)
  3337. thread_rolling += th->rolling;
  3338. }
  3339. decay_time(&cgpu->rolling, thread_rolling);
  3340. cgpu->total_mhashes += local_mhashes;
  3341. // If needed, output detailed, per-device stats
  3342. if (want_per_device_stats) {
  3343. struct timeval now;
  3344. struct timeval elapsed;
  3345. gettimeofday(&now, NULL);
  3346. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  3347. if (opt_log_interval <= elapsed.tv_sec) {
  3348. struct cgpu_info *cgpu = thr->cgpu;
  3349. char logline[255];
  3350. cgpu->last_message_tv = now;
  3351. get_statline(logline, cgpu);
  3352. if (!curses_active) {
  3353. printf("%s \r", logline);
  3354. fflush(stdout);
  3355. } else
  3356. applog(LOG_INFO, "%s", logline);
  3357. }
  3358. }
  3359. }
  3360. /* Totals are updated by all threads so can race without locking */
  3361. mutex_lock(&hash_lock);
  3362. gettimeofday(&temp_tv_end, NULL);
  3363. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  3364. total_mhashes_done += local_mhashes;
  3365. local_mhashes_done += local_mhashes;
  3366. if (total_diff.tv_sec < opt_log_interval)
  3367. /* Only update the total every opt_log_interval seconds */
  3368. goto out_unlock;
  3369. showlog = true;
  3370. gettimeofday(&total_tv_end, NULL);
  3371. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  3372. decay_time(&rolling, local_mhashes_done / local_secs);
  3373. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  3374. total_secs = (double)total_diff.tv_sec +
  3375. ((double)total_diff.tv_usec / 1000000.0);
  3376. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3377. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3378. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  3379. want_per_device_stats ? "ALL " : "",
  3380. opt_log_interval, rolling, total_mhashes_done / total_secs,
  3381. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  3382. local_mhashes_done = 0;
  3383. out_unlock:
  3384. mutex_unlock(&hash_lock);
  3385. if (showlog) {
  3386. if (!curses_active) {
  3387. printf("%s \r", statusline);
  3388. fflush(stdout);
  3389. } else
  3390. applog(LOG_INFO, "%s", statusline);
  3391. }
  3392. }
  3393. static bool pool_active(struct pool *pool, bool pinging)
  3394. {
  3395. bool ret = false;
  3396. json_t *val;
  3397. CURL *curl;
  3398. bool rolltime;
  3399. curl = curl_easy_init();
  3400. if (unlikely(!curl)) {
  3401. applog(LOG_ERR, "CURL initialisation failed");
  3402. return false;
  3403. }
  3404. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  3405. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  3406. true, false, &rolltime, pool);
  3407. if (val) {
  3408. struct work *work = make_work();
  3409. bool rc;
  3410. rc = work_decode(json_object_get(val, "result"), work);
  3411. if (rc) {
  3412. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  3413. pool->pool_no, pool->rpc_url);
  3414. work->pool = pool;
  3415. work->rolltime = rolltime;
  3416. if (opt_debug)
  3417. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  3418. tq_push(thr_info[stage_thr_id].q, work);
  3419. total_getworks++;
  3420. pool->getwork_requested++;
  3421. inc_queued();
  3422. ret = true;
  3423. gettimeofday(&pool->tv_idle, NULL);
  3424. } else {
  3425. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  3426. pool->pool_no, pool->rpc_url);
  3427. free_work(work);
  3428. }
  3429. json_decref(val);
  3430. } else {
  3431. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  3432. pool->pool_no, pool->rpc_url);
  3433. if (!pinging) {
  3434. if (!donor(pool))
  3435. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  3436. else
  3437. applog(LOG_WARNING, "Donor pool slow to respond");
  3438. }
  3439. }
  3440. curl_easy_cleanup(curl);
  3441. return ret;
  3442. }
  3443. static void pool_died(struct pool *pool)
  3444. {
  3445. if (!pool_tset(pool, &pool->idle)) {
  3446. if (!donor(pool))
  3447. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  3448. gettimeofday(&pool->tv_idle, NULL);
  3449. switch_pools(NULL);
  3450. }
  3451. }
  3452. static inline int cp_prio(void)
  3453. {
  3454. int prio;
  3455. mutex_lock(&control_lock);
  3456. prio = currentpool->prio;
  3457. mutex_unlock(&control_lock);
  3458. return prio;
  3459. }
  3460. static void pool_resus(struct pool *pool)
  3461. {
  3462. if (!donor(pool))
  3463. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  3464. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  3465. switch_pools(NULL);
  3466. }
  3467. static bool queue_request(struct thr_info *thr, bool needed)
  3468. {
  3469. struct workio_cmd *wc;
  3470. int rq = requests_queued();
  3471. if (rq >= mining_threads + staged_clones)
  3472. return true;
  3473. /* fill out work request message */
  3474. wc = calloc(1, sizeof(*wc));
  3475. if (unlikely(!wc)) {
  3476. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  3477. return false;
  3478. }
  3479. wc->cmd = WC_GET_WORK;
  3480. if (thr)
  3481. wc->thr = thr;
  3482. else
  3483. wc->thr = NULL;
  3484. /* If we're queueing work faster than we can stage it, consider the
  3485. * system lagging and allow work to be gathered from another pool if
  3486. * possible */
  3487. if (rq && needed && !requests_staged() && !opt_fail_only)
  3488. wc->lagging = true;
  3489. if (opt_debug)
  3490. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  3491. /* send work request to workio thread */
  3492. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3493. applog(LOG_ERR, "Failed to tq_push in queue_request");
  3494. workio_cmd_free(wc);
  3495. return false;
  3496. }
  3497. inc_queued();
  3498. return true;
  3499. }
  3500. struct work *hash_pop(const struct timespec *abstime)
  3501. {
  3502. struct work *work = NULL;
  3503. int rc;
  3504. mutex_lock(stgd_lock);
  3505. if (HASH_COUNT(staged_work))
  3506. goto pop;
  3507. if (abstime)
  3508. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  3509. else
  3510. rc = pthread_cond_wait(&getq->cond, stgd_lock);
  3511. if (rc)
  3512. goto out;
  3513. if (!HASH_COUNT(staged_work))
  3514. goto out;
  3515. pop:
  3516. work = staged_work;
  3517. HASH_DEL(staged_work, work);
  3518. if (work->clone)
  3519. --staged_clones;
  3520. out:
  3521. mutex_unlock(stgd_lock);
  3522. return work;
  3523. }
  3524. static inline bool should_roll(struct work *work)
  3525. {
  3526. int rs;
  3527. rs = requests_staged();
  3528. if (rs >= mining_threads)
  3529. return false;
  3530. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  3531. return true;
  3532. return false;
  3533. }
  3534. static inline bool can_roll(struct work *work)
  3535. {
  3536. return (work->pool && !stale_work(work, false) && work->rolltime &&
  3537. work->rolls < 11 && !work->clone && !donor(work->pool));
  3538. }
  3539. static void roll_work(struct work *work)
  3540. {
  3541. uint32_t *work_ntime;
  3542. uint32_t ntime;
  3543. work_ntime = (uint32_t *)(work->data + 68);
  3544. ntime = be32toh(*work_ntime);
  3545. ntime++;
  3546. *work_ntime = htobe32(ntime);
  3547. local_work++;
  3548. work->rolls++;
  3549. work->blk.nonce = 0;
  3550. if (opt_debug)
  3551. applog(LOG_DEBUG, "Successfully rolled work");
  3552. }
  3553. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  3554. * giving it to will not finish scanning it. We keep the master copy to be
  3555. * recycled more rapidly and discard the clone to avoid repeating work */
  3556. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  3557. {
  3558. if (can_roll(work) && should_roll(work)) {
  3559. roll_work(work);
  3560. return true;
  3561. }
  3562. return false;
  3563. #if 0
  3564. /* Work division is disabled because it can lead to repeated work */
  3565. uint64_t hash_inc;
  3566. if (work->clone)
  3567. return false;
  3568. hash_inc = MAXTHREADS / hash_div * 2;
  3569. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  3570. /* Okay we can divide it up */
  3571. work->blk.nonce += hash_inc;
  3572. work->cloned = true;
  3573. local_work++;
  3574. if (opt_debug)
  3575. applog(LOG_DEBUG, "Successfully divided work");
  3576. return true;
  3577. } else if (can_roll(work) && should_roll(work)) {
  3578. roll_work(work);
  3579. return true;
  3580. }
  3581. return false;
  3582. #endif
  3583. }
  3584. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  3585. const int thr_id, uint32_t hash_div)
  3586. {
  3587. struct timespec abstime = {};
  3588. struct timeval now;
  3589. struct work *work_heap;
  3590. struct pool *pool;
  3591. bool ret = false;
  3592. int failures = 0;
  3593. /* Tell the watchdog thread this thread is waiting on getwork and
  3594. * should not be restarted */
  3595. thread_reportout(thr);
  3596. retry:
  3597. pool = current_pool();
  3598. if (unlikely((!requested || requests_queued() < opt_queue) && !queue_request(thr, true))) {
  3599. applog(LOG_WARNING, "Failed to queue_request in get_work");
  3600. goto out;
  3601. }
  3602. if (can_roll(work) && should_roll(work)) {
  3603. roll_work(work);
  3604. ret = true;
  3605. goto out;
  3606. }
  3607. if (!requests_staged()) {
  3608. if (requested && requests_queued() >= mining_threads &&
  3609. !pool_tset(pool, &pool->lagging)) {
  3610. applog(LOG_WARNING, "Pool %d not providing work fast enough",
  3611. pool->pool_no);
  3612. pool->getfail_occasions++;
  3613. total_go++;
  3614. }
  3615. }
  3616. requested = false;
  3617. gettimeofday(&now, NULL);
  3618. abstime.tv_sec = now.tv_sec + 60;
  3619. if (opt_debug)
  3620. applog(LOG_DEBUG, "Popping work from get queue to get work");
  3621. /* wait for 1st response, or get cached response */
  3622. work_heap = hash_pop(&abstime);
  3623. if (unlikely(!work_heap)) {
  3624. /* Attempt to switch pools if this one times out */
  3625. pool_died(pool);
  3626. goto retry;
  3627. }
  3628. if (stale_work(work_heap, false)) {
  3629. dec_queued();
  3630. discard_work(work_heap);
  3631. goto retry;
  3632. }
  3633. pool = work_heap->pool;
  3634. /* If we make it here we have succeeded in getting fresh work */
  3635. if (!work_heap->mined) {
  3636. pool_tclear(pool, &pool->lagging);
  3637. if (pool_tclear(pool, &pool->idle))
  3638. pool_resus(pool);
  3639. }
  3640. memcpy(work, work_heap, sizeof(*work));
  3641. /* Copy the res nonce back so we know to start at a higher baseline
  3642. * should we divide the same work up again. Make the work we're
  3643. * handing out be clone */
  3644. if (divide_work(&now, work_heap, hash_div)) {
  3645. if (opt_debug)
  3646. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  3647. hash_push(work_heap);
  3648. work->clone = true;
  3649. } else {
  3650. dec_queued();
  3651. free_work(work_heap);
  3652. }
  3653. ret = true;
  3654. out:
  3655. if (unlikely(ret == false)) {
  3656. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  3657. applog(LOG_ERR, "Failed %d times to get_work");
  3658. return ret;
  3659. }
  3660. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  3661. sleep(fail_pause);
  3662. fail_pause += opt_fail_pause;
  3663. goto retry;
  3664. }
  3665. fail_pause = opt_fail_pause;
  3666. work->thr_id = thr_id;
  3667. thread_reportin(thr);
  3668. if (ret)
  3669. work->mined = true;
  3670. return ret;
  3671. }
  3672. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  3673. {
  3674. struct workio_cmd *wc;
  3675. /* fill out work request message */
  3676. wc = calloc(1, sizeof(*wc));
  3677. if (unlikely(!wc)) {
  3678. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  3679. return false;
  3680. }
  3681. wc->u.work = make_work();
  3682. wc->cmd = WC_SUBMIT_WORK;
  3683. wc->thr = thr;
  3684. memcpy(wc->u.work, work_in, sizeof(*work_in));
  3685. if (opt_debug)
  3686. applog(LOG_DEBUG, "Pushing submit work to work thread");
  3687. /* send solution to workio thread */
  3688. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  3689. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  3690. goto err_out;
  3691. }
  3692. return true;
  3693. err_out:
  3694. workio_cmd_free(wc);
  3695. return false;
  3696. }
  3697. bool hashtest(const struct work *work)
  3698. {
  3699. uint32_t *data32 = (uint32_t *)(work->data);
  3700. unsigned char swap[128];
  3701. uint32_t *swap32 = (uint32_t *)swap;
  3702. unsigned char hash1[32];
  3703. unsigned char hash2[32];
  3704. uint32_t *hash2_32 = (uint32_t *)hash2;
  3705. int i;
  3706. for (i = 0; i < 80 / 4; i++)
  3707. swap32[i] = swab32(data32[i]);
  3708. sha2(swap, 80, hash1, false);
  3709. sha2(hash1, 32, hash2, false);
  3710. for (i = 0; i < 32 / 4; i++)
  3711. hash2_32[i] = swab32(hash2_32[i]);
  3712. memcpy((void*)work->hash, hash2, 32);
  3713. return fulltest(work->hash, work->target);
  3714. }
  3715. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  3716. {
  3717. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  3718. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  3719. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  3720. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  3721. /* Do one last check before attempting to submit the work */
  3722. if (!hashtest(work)) {
  3723. applog(LOG_INFO, "Share below target");
  3724. return true;
  3725. }
  3726. return submit_work_sync(thr, work);
  3727. }
  3728. static void *miner_thread(void *userdata)
  3729. {
  3730. struct work *work = make_work();
  3731. struct thr_info *mythr = userdata;
  3732. const int thr_id = mythr->id;
  3733. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  3734. unsigned long hashes_done = max_nonce;
  3735. bool needs_work = true;
  3736. /* Try to cycle approximately 5 times before each log update */
  3737. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3738. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3739. bool requested = false;
  3740. uint32_t nonce_inc = max_nonce, hash_div = 1;
  3741. double hash_divfloat = 1.0;
  3742. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3743. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  3744. * and if that fails, then SCHED_BATCH. No need for this to be an
  3745. * error if it fails */
  3746. setpriority(PRIO_PROCESS, 0, 19);
  3747. drop_policy();
  3748. /* Cpu affinity only makes sense if the number of threads is a multiple
  3749. * of the number of CPUs */
  3750. if (!(opt_n_threads % num_processors))
  3751. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  3752. /* Invalidate pool so it fails can_roll() test */
  3753. work->pool = NULL;
  3754. while (1) {
  3755. struct timeval tv_workstart, tv_start, tv_end, diff;
  3756. uint64_t max64;
  3757. bool rc;
  3758. if (needs_work) {
  3759. gettimeofday(&tv_workstart, NULL);
  3760. /* obtain new work from internal workio thread */
  3761. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3762. applog(LOG_ERR, "work retrieval failed, exiting "
  3763. "mining thread %d", thr_id);
  3764. goto out;
  3765. }
  3766. needs_work = requested = false;
  3767. total_hashes = 0;
  3768. max_nonce = work->blk.nonce + hashes_done;
  3769. }
  3770. hashes_done = 0;
  3771. gettimeofday(&tv_start, NULL);
  3772. /* scan nonces for a proof-of-work hash */
  3773. switch (opt_algo) {
  3774. case ALGO_C:
  3775. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  3776. work->hash1, work->hash, work->target,
  3777. max_nonce, &hashes_done,
  3778. work->blk.nonce);
  3779. break;
  3780. #ifdef WANT_X8632_SSE2
  3781. case ALGO_SSE2_32: {
  3782. unsigned int rc5 =
  3783. scanhash_sse2_32(thr_id, work->midstate, work->data + 64,
  3784. work->hash1, work->hash,
  3785. work->target,
  3786. max_nonce, &hashes_done,
  3787. work->blk.nonce);
  3788. rc = (rc5 == -1) ? false : true;
  3789. }
  3790. break;
  3791. #endif
  3792. #ifdef WANT_X8664_SSE2
  3793. case ALGO_SSE2_64: {
  3794. unsigned int rc5 =
  3795. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  3796. work->hash1, work->hash,
  3797. work->target,
  3798. max_nonce, &hashes_done,
  3799. work->blk.nonce);
  3800. rc = (rc5 == -1) ? false : true;
  3801. }
  3802. break;
  3803. #endif
  3804. #ifdef WANT_X8664_SSE4
  3805. case ALGO_SSE4_64: {
  3806. unsigned int rc5 =
  3807. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  3808. work->hash1, work->hash,
  3809. work->target,
  3810. max_nonce, &hashes_done,
  3811. work->blk.nonce);
  3812. rc = (rc5 == -1) ? false : true;
  3813. }
  3814. break;
  3815. #endif
  3816. #ifdef WANT_SSE2_4WAY
  3817. case ALGO_4WAY: {
  3818. unsigned int rc4 =
  3819. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  3820. work->hash1, work->hash,
  3821. work->target,
  3822. max_nonce, &hashes_done,
  3823. work->blk.nonce);
  3824. rc = (rc4 == -1) ? false : true;
  3825. }
  3826. break;
  3827. #endif
  3828. #ifdef WANT_ALTIVEC_4WAY
  3829. case ALGO_ALTIVEC_4WAY:
  3830. {
  3831. unsigned int rc4 = ScanHash_altivec_4way(thr_id, work->midstate, work->data + 64,
  3832. work->hash1, work->hash,
  3833. work->target,
  3834. max_nonce, &hashes_done,
  3835. work->blk.nonce);
  3836. rc = (rc4 == -1) ? false : true;
  3837. }
  3838. break;
  3839. #endif
  3840. #ifdef WANT_VIA_PADLOCK
  3841. case ALGO_VIA:
  3842. rc = scanhash_via(thr_id, work->data, work->target,
  3843. max_nonce, &hashes_done,
  3844. work->blk.nonce);
  3845. break;
  3846. #endif
  3847. case ALGO_CRYPTOPP:
  3848. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  3849. work->hash1, work->hash, work->target,
  3850. max_nonce, &hashes_done,
  3851. work->blk.nonce);
  3852. break;
  3853. #ifdef WANT_CRYPTOPP_ASM32
  3854. case ALGO_CRYPTOPP_ASM32:
  3855. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  3856. work->hash1, work->hash, work->target,
  3857. max_nonce, &hashes_done,
  3858. work->blk.nonce);
  3859. break;
  3860. #endif
  3861. default:
  3862. /* should never happen */
  3863. goto out;
  3864. }
  3865. /* record scanhash elapsed time */
  3866. gettimeofday(&tv_end, NULL);
  3867. timeval_subtract(&diff, &tv_end, &tv_start);
  3868. hashes_done -= work->blk.nonce;
  3869. hashmeter(thr_id, &diff, hashes_done);
  3870. total_hashes += hashes_done;
  3871. work->blk.nonce += hashes_done;
  3872. /* adjust max_nonce to meet target cycle time */
  3873. if (diff.tv_usec > 500000)
  3874. diff.tv_sec++;
  3875. if (diff.tv_sec && diff.tv_sec != cycle) {
  3876. uint64_t next_inc = ((uint64_t)hashes_done * (uint64_t)cycle) / (uint64_t)diff.tv_sec;
  3877. if (next_inc > (uint64_t)nonce_inc / 2 * 3)
  3878. next_inc = nonce_inc / 2 * 3;
  3879. nonce_inc = next_inc;
  3880. } else if (!diff.tv_sec)
  3881. nonce_inc = hashes_done * 2;
  3882. if (nonce_inc < 4)
  3883. nonce_inc = 0xffffff;
  3884. max64 = work->blk.nonce + nonce_inc;
  3885. if (max64 > 0xfffffffaULL)
  3886. max64 = 0xfffffffaULL;
  3887. max_nonce = max64;
  3888. /* if nonce found, submit work */
  3889. if (unlikely(rc)) {
  3890. if (opt_debug)
  3891. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  3892. if (unlikely(!submit_work_sync(mythr, work))) {
  3893. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  3894. break;
  3895. }
  3896. work->blk.nonce += 4;
  3897. }
  3898. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3899. if (!requested && (diff.tv_sec >= request_interval)) {
  3900. thread_reportout(mythr);
  3901. if (unlikely(!queue_request(mythr, false))) {
  3902. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3903. goto out;
  3904. }
  3905. thread_reportin(mythr);
  3906. requested = true;
  3907. }
  3908. if (diff.tv_sec > opt_scantime) {
  3909. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  3910. hash_div = hash_divfloat;
  3911. needs_work = true;
  3912. } else if (work_restart[thr_id].restart || stale_work(work, false) ||
  3913. work->blk.nonce >= MAXTHREADS - hashes_done)
  3914. needs_work = true;
  3915. if (unlikely(mythr->pause)) {
  3916. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3917. mythr->rolling = mythr->cgpu->rolling = 0;
  3918. if (opt_debug)
  3919. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3920. thread_reportout(mythr);
  3921. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3922. thread_reportin(mythr);
  3923. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3924. }
  3925. }
  3926. out:
  3927. thread_reportin(mythr);
  3928. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3929. tq_freeze(mythr->q);
  3930. return NULL;
  3931. }
  3932. enum {
  3933. STAT_SLEEP_INTERVAL = 1,
  3934. STAT_CTR_INTERVAL = 10000000,
  3935. FAILURE_INTERVAL = 30,
  3936. };
  3937. #ifdef HAVE_OPENCL
  3938. static _clState *clStates[MAX_GPUDEVICES];
  3939. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  3940. {
  3941. cl_kernel *kernel = &clState->kernel;
  3942. cl_int status = 0;
  3943. int num = 0;
  3944. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3945. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3946. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3947. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3948. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3949. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3950. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3951. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3952. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3953. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3954. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3955. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3956. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3957. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3958. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  3959. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  3960. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  3961. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  3962. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  3963. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  3964. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  3965. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  3966. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  3967. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3968. (void *)&clState->outputBuffer);
  3969. return status;
  3970. }
  3971. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  3972. {
  3973. cl_uint vwidth = clState->preferred_vwidth;
  3974. cl_kernel *kernel = &clState->kernel;
  3975. cl_int status = 0;
  3976. int i, num = 0;
  3977. uint *nonces;
  3978. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3979. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3980. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3981. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3982. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3983. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3984. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3985. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3986. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3987. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3988. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3989. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3990. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3991. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3992. nonces = alloca(sizeof(uint) * vwidth);
  3993. for (i = 0; i < vwidth; i++)
  3994. nonces[i] = blk->nonce + i;
  3995. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3996. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3997. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3998. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3999. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  4000. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  4001. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  4002. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  4003. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  4004. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  4005. (void *)&clState->outputBuffer);
  4006. return status;
  4007. }
  4008. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  4009. unsigned int *hashes, size_t *globalThreads,
  4010. unsigned int minthreads, int intensity)
  4011. {
  4012. *threads = 1 << (15 + intensity);
  4013. if (*threads < minthreads)
  4014. *threads = minthreads;
  4015. *globalThreads = *threads;
  4016. *hashes = *threads * vectors;
  4017. }
  4018. static void *gpuminer_thread(void *userdata)
  4019. {
  4020. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  4021. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  4022. struct timeval tv_start, tv_end, diff, tv_workstart;
  4023. struct thr_info *mythr = userdata;
  4024. const int thr_id = mythr->id;
  4025. uint32_t *res, *blank_res;
  4026. double gpu_ms_average = 7;
  4027. int gpu = dev_from_id(thr_id);
  4028. size_t globalThreads[1];
  4029. size_t localThreads[1];
  4030. cl_int status;
  4031. _clState *clState = clStates[thr_id];
  4032. const cl_kernel *kernel = &clState->kernel;
  4033. struct work *work = make_work();
  4034. unsigned int threads;
  4035. unsigned const int vectors = clState->preferred_vwidth;
  4036. unsigned int hashes;
  4037. unsigned int hashes_done = 0;
  4038. /* Request the next work item at 2/3 of the scantime */
  4039. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  4040. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  4041. bool requested = false;
  4042. uint32_t total_hashes = 0, hash_div = 1;
  4043. switch (chosen_kernel) {
  4044. case KL_POCLBM:
  4045. queue_kernel_parameters = &queue_poclbm_kernel;
  4046. break;
  4047. case KL_PHATK:
  4048. default:
  4049. queue_kernel_parameters = &queue_phatk_kernel;
  4050. break;
  4051. }
  4052. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4053. res = calloc(BUFFERSIZE, 1);
  4054. blank_res = calloc(BUFFERSIZE, 1);
  4055. if (!res || !blank_res) {
  4056. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  4057. goto out;
  4058. }
  4059. gettimeofday(&tv_start, NULL);
  4060. localThreads[0] = clState->work_size;
  4061. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  4062. localThreads[0], gpus[gpu].intensity);
  4063. diff.tv_sec = 0;
  4064. gettimeofday(&tv_end, NULL);
  4065. work->pool = NULL;
  4066. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  4067. BUFFERSIZE, blank_res, 0, NULL, NULL);
  4068. if (unlikely(status != CL_SUCCESS))
  4069. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  4070. mythr->cgpu->status = LIFE_WELL;
  4071. if (opt_debug)
  4072. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  4073. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  4074. gettimeofday(&tv_workstart, NULL);
  4075. /* obtain new work from internal workio thread */
  4076. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  4077. applog(LOG_ERR, "work retrieval failed, exiting "
  4078. "gpu mining thread %d", thr_id);
  4079. goto out;
  4080. }
  4081. requested = false;
  4082. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  4083. work->blk.nonce = 0;
  4084. while (1) {
  4085. struct timeval tv_gpustart, tv_gpuend;
  4086. suseconds_t gpu_us;
  4087. gettimeofday(&tv_gpustart, NULL);
  4088. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  4089. /* This finish flushes the readbuffer set with CL_FALSE later */
  4090. clFinish(clState->commandQueue);
  4091. gettimeofday(&tv_gpuend, NULL);
  4092. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  4093. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  4094. decay_time(&gpu_ms_average, gpu_us / 1000);
  4095. if (gpus[gpu].dynamic) {
  4096. /* Try to not let the GPU be out for longer than 6ms, but
  4097. * increase intensity when the system is idle, unless
  4098. * dynamic is disabled. */
  4099. if (gpu_ms_average > 7) {
  4100. if (gpus[gpu].intensity > -10)
  4101. gpus[gpu].intensity--;
  4102. } else if (gpu_ms_average < 3) {
  4103. if (gpus[gpu].intensity < 10)
  4104. gpus[gpu].intensity++;
  4105. }
  4106. }
  4107. set_threads_hashes(vectors, &threads, &hashes, globalThreads,
  4108. localThreads[0], gpus[gpu].intensity);
  4109. if (diff.tv_sec > opt_scantime ||
  4110. work->blk.nonce >= MAXTHREADS - hashes ||
  4111. work_restart[thr_id].restart ||
  4112. stale_work(work, false)) {
  4113. /* Ignore any reads since we're getting new work and queue a clean buffer */
  4114. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  4115. BUFFERSIZE, blank_res, 0, NULL, NULL);
  4116. if (unlikely(status != CL_SUCCESS))
  4117. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  4118. memset(res, 0, BUFFERSIZE);
  4119. gettimeofday(&tv_workstart, NULL);
  4120. if (opt_debug)
  4121. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  4122. /* obtain new work from internal workio thread */
  4123. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  4124. applog(LOG_ERR, "work retrieval failed, exiting "
  4125. "gpu mining thread %d", thr_id);
  4126. goto out;
  4127. }
  4128. requested = false;
  4129. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  4130. work_restart[thr_id].restart = 0;
  4131. /* Flushes the writebuffer set with CL_FALSE above */
  4132. clFinish(clState->commandQueue);
  4133. }
  4134. status = queue_kernel_parameters(clState, &work->blk);
  4135. if (unlikely(status != CL_SUCCESS))
  4136. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  4137. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  4138. if (res[FOUND]) {
  4139. /* Clear the buffer again */
  4140. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  4141. BUFFERSIZE, blank_res, 0, NULL, NULL);
  4142. if (unlikely(status != CL_SUCCESS))
  4143. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  4144. if (opt_debug)
  4145. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  4146. postcalc_hash_async(mythr, work, res);
  4147. memset(res, 0, BUFFERSIZE);
  4148. clFinish(clState->commandQueue);
  4149. }
  4150. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  4151. globalThreads, localThreads, 0, NULL, NULL);
  4152. if (unlikely(status != CL_SUCCESS))
  4153. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  4154. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  4155. BUFFERSIZE, res, 0, NULL, NULL);
  4156. if (unlikely(status != CL_SUCCESS))
  4157. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  4158. gettimeofday(&tv_end, NULL);
  4159. timeval_subtract(&diff, &tv_end, &tv_start);
  4160. hashes_done += hashes;
  4161. total_hashes += hashes;
  4162. work->blk.nonce += hashes;
  4163. if (diff.tv_sec >= cycle) {
  4164. hashmeter(thr_id, &diff, hashes_done);
  4165. gettimeofday(&tv_start, NULL);
  4166. hashes_done = 0;
  4167. }
  4168. timeval_subtract(&diff, &tv_end, &tv_workstart);
  4169. if (!requested) {
  4170. #if 0
  4171. if (diff.tv_sec > request_interval)
  4172. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  4173. #endif
  4174. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  4175. thread_reportout(mythr);
  4176. if (unlikely(!queue_request(mythr, false))) {
  4177. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  4178. goto out;
  4179. }
  4180. thread_reportin(mythr);
  4181. requested = true;
  4182. }
  4183. }
  4184. if (unlikely(!gpu_devices[gpu] || mythr->pause)) {
  4185. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  4186. mythr->rolling = mythr->cgpu->rolling = 0;
  4187. if (opt_debug)
  4188. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  4189. thread_reportout(mythr);
  4190. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  4191. thread_reportin(mythr);
  4192. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  4193. }
  4194. }
  4195. out:
  4196. clReleaseCommandQueue(clState->commandQueue);
  4197. clReleaseKernel(clState->kernel);
  4198. clReleaseProgram(clState->program);
  4199. clReleaseContext(clState->context);
  4200. thread_reportin(mythr);
  4201. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  4202. tq_freeze(mythr->q);
  4203. return NULL;
  4204. }
  4205. #endif /* HAVE_OPENCL */
  4206. /* Stage another work item from the work returned in a longpoll */
  4207. static void convert_to_work(json_t *val, bool rolltime, struct pool *pool)
  4208. {
  4209. struct work *work;
  4210. bool rc;
  4211. work = make_work();
  4212. rc= work_decode(json_object_get(val, "result"), work);
  4213. if (unlikely(!rc)) {
  4214. applog(LOG_ERR, "Could not convert longpoll data to work");
  4215. return;
  4216. }
  4217. work->pool = pool;
  4218. work->rolltime = rolltime;
  4219. /* We'll be checking this work item twice, but we already know it's
  4220. * from a new block so explicitly force the new block detection now
  4221. * rather than waiting for it to hit the stage thread. This also
  4222. * allows testwork to know whether LP discovered the block or not. */
  4223. test_work_current(work, true);
  4224. if (opt_debug)
  4225. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  4226. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  4227. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  4228. else if (opt_debug)
  4229. applog(LOG_DEBUG, "Converted longpoll data to work");
  4230. }
  4231. /* If we want longpoll, enable it for the chosen default pool, or, if
  4232. * the pool does not support longpoll, find the first one that does
  4233. * and use its longpoll support */
  4234. static struct pool *select_longpoll_pool(void)
  4235. {
  4236. struct pool *cp = current_pool();
  4237. int i;
  4238. if (cp->hdr_path)
  4239. return cp;
  4240. for (i = 0; i < total_pools; i++) {
  4241. struct pool *pool = pools[i];
  4242. if (pool->hdr_path)
  4243. return pool;
  4244. }
  4245. return NULL;
  4246. }
  4247. static void *longpoll_thread(void *userdata)
  4248. {
  4249. char *copy_start, *hdr_path, *lp_url = NULL;
  4250. struct thr_info *mythr = userdata;
  4251. struct timeval start, end;
  4252. bool need_slash = false;
  4253. struct pool *sp, *pool;
  4254. CURL *curl = NULL;
  4255. int failures = 0;
  4256. bool rolltime;
  4257. json_t *val;
  4258. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4259. pthread_detach(pthread_self());
  4260. curl = curl_easy_init();
  4261. if (unlikely(!curl)) {
  4262. applog(LOG_ERR, "CURL initialisation failed");
  4263. goto out;
  4264. }
  4265. tq_pop(mythr->q, NULL);
  4266. pool = select_longpoll_pool();
  4267. new_longpoll:
  4268. if (!pool) {
  4269. applog(LOG_WARNING, "No long-poll found on any pool server");
  4270. goto out;
  4271. }
  4272. hdr_path = pool->hdr_path;
  4273. /* full URL */
  4274. if (strstr(hdr_path, "://")) {
  4275. lp_url = hdr_path;
  4276. hdr_path = NULL;
  4277. } else {
  4278. /* absolute path, on current server */
  4279. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  4280. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  4281. need_slash = true;
  4282. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  4283. if (!lp_url)
  4284. goto out;
  4285. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  4286. }
  4287. have_longpoll = true;
  4288. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  4289. while (1) {
  4290. gettimeofday(&start, NULL);
  4291. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  4292. false, true, &rolltime, pool);
  4293. if (likely(val)) {
  4294. convert_to_work(val, rolltime, pool);
  4295. failures = 0;
  4296. json_decref(val);
  4297. } else {
  4298. /* Some pools regularly drop the longpoll request so
  4299. * only see this as longpoll failure if it happens
  4300. * immediately and just restart it the rest of the
  4301. * time. */
  4302. gettimeofday(&end, NULL);
  4303. if (end.tv_sec - start.tv_sec > 30)
  4304. continue;
  4305. if (opt_retries == -1 || failures++ < opt_retries) {
  4306. applog(LOG_WARNING,
  4307. "longpoll failed for %s, sleeping for 30s", lp_url);
  4308. sleep(30);
  4309. } else {
  4310. applog(LOG_ERR,
  4311. "longpoll failed for %s, ending thread", lp_url);
  4312. goto out;
  4313. }
  4314. }
  4315. sp = select_longpoll_pool();
  4316. if (sp != pool) {
  4317. if (likely(lp_url))
  4318. free(lp_url);
  4319. pool = sp;
  4320. goto new_longpoll;
  4321. }
  4322. }
  4323. out:
  4324. if (curl)
  4325. curl_easy_cleanup(curl);
  4326. tq_freeze(mythr->q);
  4327. return NULL;
  4328. }
  4329. static void stop_longpoll(void)
  4330. {
  4331. struct thr_info *thr = &thr_info[longpoll_thr_id];
  4332. thr_info_cancel(thr);
  4333. have_longpoll = false;
  4334. tq_freeze(thr->q);
  4335. }
  4336. static void start_longpoll(void)
  4337. {
  4338. struct thr_info *thr = &thr_info[longpoll_thr_id];
  4339. tq_thaw(thr->q);
  4340. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  4341. quit(1, "longpoll thread create failed");
  4342. if (opt_debug)
  4343. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  4344. tq_push(thr_info[longpoll_thr_id].q, &ping);
  4345. }
  4346. static void *reinit_cpu(void *userdata)
  4347. {
  4348. pthread_detach(pthread_self());
  4349. #if 0
  4350. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  4351. int cpu = cgpu->cpu_gpu;
  4352. long thr_id = ....(long)userdata;
  4353. struct thr_info *thr = &thr_info[thr_id];
  4354. int cpu = dev_from_id(thr_id);
  4355. cpus[cpu].alive = false;
  4356. thr->rolling = thr->cgpu->rolling = 0;
  4357. tq_freeze(thr->q);
  4358. if (!pthread_cancel(*thr->pth))
  4359. pthread_join(*thr->pth, NULL);
  4360. free(thr->q);
  4361. thr->q = tq_new();
  4362. if (!thr->q)
  4363. quit(1, "Failed to tq_new in reinit_cputhread");
  4364. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  4365. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  4366. applog(LOG_ERR, "thread %d create failed", thr_id);
  4367. return NULL;
  4368. }
  4369. tq_push(thr->q, &ping);
  4370. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  4371. #endif
  4372. return NULL;
  4373. }
  4374. #ifdef HAVE_OPENCL
  4375. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  4376. * init command fails due to a completely wedged GPU, the thread will never
  4377. * return, unable to harm other GPUs. If it does return, it means we only had
  4378. * a soft failure and then the reinit_gpu thread is ready to tackle another
  4379. * GPU */
  4380. static void *reinit_gpu(void *userdata)
  4381. {
  4382. struct thr_info *mythr = userdata;
  4383. struct cgpu_info *cgpu;
  4384. struct thr_info *thr;
  4385. struct timeval now;
  4386. char name[256];
  4387. int thr_id;
  4388. int gpu;
  4389. pthread_detach(pthread_self());
  4390. select_cgpu:
  4391. cgpu = tq_pop(mythr->q, NULL);
  4392. if (!cgpu)
  4393. goto out;
  4394. if (clDevicesNum() != nDevs) {
  4395. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  4396. goto out;
  4397. }
  4398. gpu = cgpu->cpu_gpu;
  4399. gpu_devices[gpu] = false;
  4400. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4401. if (dev_from_id(thr_id) != gpu)
  4402. continue;
  4403. thr = &thr_info[thr_id];
  4404. if (!thr) {
  4405. applog(LOG_WARNING, "No reference to thread %d exists", thr_id);
  4406. continue;
  4407. }
  4408. thr->rolling = thr->cgpu->rolling = 0;
  4409. /* Reports the last time we tried to revive a sick GPU */
  4410. gettimeofday(&thr->sick, NULL);
  4411. if (!pthread_cancel(thr->pth)) {
  4412. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  4413. } else
  4414. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  4415. }
  4416. gpu_devices[gpu] = true;
  4417. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4418. if (dev_from_id(thr_id) != gpu)
  4419. continue;
  4420. thr = &thr_info[thr_id];
  4421. /* Lose this ram cause we may get stuck here! */
  4422. //tq_freeze(thr->q);
  4423. thr->q = tq_new();
  4424. if (!thr->q)
  4425. quit(1, "Failed to tq_new in reinit_gpu");
  4426. /* Lose this ram cause we may dereference in the dying thread! */
  4427. //free(clState);
  4428. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  4429. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  4430. if (!clStates[thr_id]) {
  4431. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  4432. goto select_cgpu;
  4433. }
  4434. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4435. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  4436. applog(LOG_ERR, "thread %d create failed", thr_id);
  4437. return NULL;
  4438. }
  4439. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  4440. }
  4441. gettimeofday(&now, NULL);
  4442. get_datestamp(cgpu->init, &now);
  4443. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  4444. if (dev_from_id(thr_id) != gpu)
  4445. continue;
  4446. thr = &thr_info[thr_id];
  4447. tq_push(thr->q, &ping);
  4448. }
  4449. goto select_cgpu;
  4450. out:
  4451. return NULL;
  4452. }
  4453. #else
  4454. static void *reinit_gpu(void *userdata)
  4455. {
  4456. }
  4457. #endif
  4458. void reinit_device(struct cgpu_info *cgpu)
  4459. {
  4460. if (cgpu->is_gpu)
  4461. tq_push(thr_info[gpur_thr_id].q, cgpu);
  4462. else
  4463. tq_push(thr_info[cpur_thr_id].q, cgpu);
  4464. }
  4465. /* Determine which are the first threads belonging to a device and if they're
  4466. * active */
  4467. static bool active_device(int thr_id)
  4468. {
  4469. if (thr_id < gpu_threads) {
  4470. if (thr_id >= total_devices)
  4471. return false;
  4472. if (!gpu_devices[dev_from_id(thr_id)])
  4473. return false;
  4474. } else if (thr_id > gpu_threads + num_processors)
  4475. return false;
  4476. return true;
  4477. }
  4478. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  4479. * the screen at regular intervals, and restarts threads if they appear to have
  4480. * died. */
  4481. static void *watchdog_thread(void *userdata)
  4482. {
  4483. const unsigned int interval = 3;
  4484. static struct timeval rotate_tv;
  4485. struct timeval zero_tv;
  4486. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  4487. memset(&zero_tv, 0, sizeof(struct timeval));
  4488. gettimeofday(&rotate_tv, NULL);
  4489. while (1) {
  4490. int i;
  4491. struct timeval now;
  4492. sleep(interval);
  4493. if (requests_queued() < opt_queue)
  4494. queue_request(NULL, false);
  4495. hashmeter(-1, &zero_tv, 0);
  4496. if (curses_active_locked()) {
  4497. change_logwinsize();
  4498. curses_print_status();
  4499. for (i = 0; i < mining_threads; i++)
  4500. curses_print_devstatus(i);
  4501. clearok(statuswin, true);
  4502. doupdate();
  4503. unlock_curses();
  4504. }
  4505. gettimeofday(&now, NULL);
  4506. for (i = 0; i < total_pools; i++) {
  4507. struct pool *pool = pools[i];
  4508. if (!pool->enabled)
  4509. continue;
  4510. /* Test pool is idle once every minute */
  4511. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  4512. gettimeofday(&pool->tv_idle, NULL);
  4513. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  4514. pool_resus(pool);
  4515. }
  4516. }
  4517. if (opt_donation > 0.0) {
  4518. if (donationpool.idle && now.tv_sec - donationpool.tv_idle.tv_sec > 60) {
  4519. gettimeofday(&donationpool.tv_idle, NULL);
  4520. if (pool_active(&donationpool, true) && pool_tclear(&donationpool, &donationpool.idle))
  4521. pool_resus(&donationpool);
  4522. }
  4523. }
  4524. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  4525. gettimeofday(&rotate_tv, NULL);
  4526. switch_pools(NULL);
  4527. }
  4528. if (!sched_paused && !should_run()) {
  4529. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  4530. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4531. if (!schedstart.enable) {
  4532. quit(0, "Terminating execution as planned");
  4533. break;
  4534. }
  4535. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  4536. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4537. sched_paused = true;
  4538. for (i = 0; i < mining_threads; i++) {
  4539. struct thr_info *thr;
  4540. thr = &thr_info[i];
  4541. thr->pause = true;
  4542. }
  4543. } else if (sched_paused && should_run()) {
  4544. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  4545. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  4546. if (schedstop.enable)
  4547. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  4548. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  4549. sched_paused = false;
  4550. for (i = 0; i < mining_threads; i++) {
  4551. struct thr_info *thr;
  4552. thr = &thr_info[i];
  4553. /* Don't touch disabled GPUs */
  4554. if (thr->cgpu->is_gpu && !gpu_devices[thr->cgpu->cpu_gpu])
  4555. continue;
  4556. thr->pause = false;
  4557. tq_push(thr->q, &ping);
  4558. }
  4559. }
  4560. for (i = 0; i < gpu_threads; i++) {
  4561. struct thr_info *thr;
  4562. bool *enable;
  4563. int gpu;
  4564. /* Use only one thread per device to determine if the GPU is healthy */
  4565. if (i >= nDevs)
  4566. break;
  4567. thr = &thr_info[i];
  4568. gpu = thr->cgpu->cpu_gpu;
  4569. enable = &gpu_devices[gpu];
  4570. #ifdef HAVE_ADL
  4571. if (adl_active && gpus[gpu].has_adl && *enable)
  4572. gpu_autotune(gpu, enable);
  4573. if (opt_debug && gpus[gpu].has_adl) {
  4574. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  4575. float temp = 0, vddc = 0;
  4576. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  4577. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  4578. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  4579. }
  4580. #endif
  4581. /* Thread is waiting on getwork or disabled */
  4582. if (thr->getwork || !*enable)
  4583. continue;
  4584. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  4585. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  4586. gpus[gpu].status = LIFE_WELL;
  4587. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  4588. thr->rolling = thr->cgpu->rolling = 0;
  4589. gpus[gpu].status = LIFE_SICK;
  4590. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  4591. gettimeofday(&thr->sick, NULL);
  4592. #ifdef HAVE_ADL
  4593. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  4594. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  4595. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  4596. } else
  4597. #endif
  4598. if (opt_restart) {
  4599. applog(LOG_ERR, "Attempting to restart GPU");
  4600. reinit_device(thr->cgpu);
  4601. }
  4602. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  4603. gpus[gpu].status = LIFE_DEAD;
  4604. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  4605. gettimeofday(&thr->sick, NULL);
  4606. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  4607. (gpus[i].status == LIFE_SICK || gpus[i].status == LIFE_DEAD)) {
  4608. /* Attempt to restart a GPU that's sick or dead once every minute */
  4609. gettimeofday(&thr->sick, NULL);
  4610. #ifdef HAVE_ADL
  4611. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  4612. /* Again do not attempt to restart a device that may have hard hung */
  4613. } else
  4614. #endif
  4615. if (opt_restart)
  4616. reinit_device(thr->cgpu);
  4617. }
  4618. }
  4619. }
  4620. return NULL;
  4621. }
  4622. static void log_print_status(int thr_id)
  4623. {
  4624. struct cgpu_info *cgpu;
  4625. char logline[255];
  4626. cgpu = thr_info[thr_id].cgpu;
  4627. if (cgpu) {
  4628. get_statline(logline, cgpu);
  4629. applog(LOG_WARNING, "%s", logline);
  4630. }
  4631. }
  4632. static void print_summary(void)
  4633. {
  4634. struct timeval diff;
  4635. int hours, mins, secs, i;
  4636. double utility, efficiency = 0.0;
  4637. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  4638. hours = diff.tv_sec / 3600;
  4639. mins = (diff.tv_sec % 3600) / 60;
  4640. secs = diff.tv_sec % 60;
  4641. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  4642. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  4643. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  4644. applog(LOG_WARNING, "Started at %s", datestamp);
  4645. if (opt_n_threads)
  4646. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  4647. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  4648. if (total_secs)
  4649. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  4650. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  4651. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  4652. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  4653. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  4654. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  4655. if (total_accepted || total_rejected)
  4656. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  4657. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  4658. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  4659. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  4660. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  4661. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  4662. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  4663. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  4664. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  4665. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  4666. if (total_pools > 1) {
  4667. for (i = 0; i < total_pools; i++) {
  4668. struct pool *pool = pools[i];
  4669. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  4670. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  4671. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  4672. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  4673. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  4674. if (pool->accepted || pool->rejected)
  4675. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  4676. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  4677. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  4678. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  4679. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  4680. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  4681. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  4682. }
  4683. }
  4684. if (opt_donation > 0.0)
  4685. applog(LOG_WARNING, "Donated share submissions: %d\n", donationpool.accepted + donationpool.rejected);
  4686. applog(LOG_WARNING, "Summary of per device statistics:\n");
  4687. for (i = 0; i < mining_threads; i++) {
  4688. if (active_device(i))
  4689. log_print_status(i);
  4690. }
  4691. if (opt_shares)
  4692. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  4693. fflush(stdout);
  4694. fflush(stderr);
  4695. if (opt_shares > total_accepted)
  4696. quit(1, "Did not successfully mine as many shares as were requested.");
  4697. }
  4698. void quit(int status, const char *format, ...)
  4699. {
  4700. va_list ap;
  4701. disable_curses();
  4702. if (!opt_realquiet && successful_connect)
  4703. print_summary();
  4704. if (format) {
  4705. va_start(ap, format);
  4706. vfprintf(stderr, format, ap);
  4707. va_end(ap);
  4708. }
  4709. fprintf(stderr, "\n");
  4710. fflush(stderr);
  4711. exit(status);
  4712. }
  4713. char *curses_input(const char *query)
  4714. {
  4715. char *input;
  4716. echo();
  4717. input = malloc(255);
  4718. if (!input)
  4719. quit(1, "Failed to malloc input");
  4720. leaveok(logwin, false);
  4721. wlogprint("%s:\n", query);
  4722. wgetnstr(logwin, input, 255);
  4723. if (!strlen(input))
  4724. strcpy(input, "-1");
  4725. leaveok(logwin, true);
  4726. noecho();
  4727. return input;
  4728. }
  4729. static bool input_pool(bool live)
  4730. {
  4731. char *url = NULL, *user = NULL, *pass = NULL;
  4732. struct pool *pool = NULL;
  4733. bool ret = false;
  4734. immedok(logwin, true);
  4735. if (total_pools == MAX_POOLS) {
  4736. wlogprint("Reached maximum number of pools.\n");
  4737. goto out;
  4738. }
  4739. wlogprint("Input server details.\n");
  4740. url = curses_input("URL");
  4741. if (!url)
  4742. goto out;
  4743. if (strncmp(url, "http://", 7) &&
  4744. strncmp(url, "https://", 8)) {
  4745. char *httpinput;
  4746. httpinput = malloc(255);
  4747. if (!httpinput)
  4748. quit(1, "Failed to malloc httpinput");
  4749. strcpy(httpinput, "http://");
  4750. strncat(httpinput, url, 248);
  4751. free(url);
  4752. url = httpinput;
  4753. }
  4754. user = curses_input("Username");
  4755. if (!user)
  4756. goto out;
  4757. pass = curses_input("Password");
  4758. if (!pass)
  4759. goto out;
  4760. pool = calloc(sizeof(struct pool), 1);
  4761. if (!pool)
  4762. quit(1, "Failed to realloc pools in input_pool");
  4763. pool->pool_no = total_pools;
  4764. pool->prio = total_pools;
  4765. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  4766. quit (1, "Failed to pthread_mutex_init in input_pool");
  4767. pool->rpc_url = url;
  4768. pool->rpc_user = user;
  4769. pool->rpc_pass = pass;
  4770. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4771. if (!pool->rpc_userpass)
  4772. quit(1, "Failed to malloc userpass");
  4773. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4774. pool->tv_idle.tv_sec = ~0UL;
  4775. /* Test the pool is not idle if we're live running, otherwise
  4776. * it will be tested separately */
  4777. ret = true;
  4778. pool->enabled = true;
  4779. if (live && !pool_active(pool, false))
  4780. pool->idle = true;
  4781. pools[total_pools++] = pool;
  4782. out:
  4783. immedok(logwin, false);
  4784. if (!ret) {
  4785. if (url)
  4786. free(url);
  4787. if (user)
  4788. free(user);
  4789. if (pass)
  4790. free(pass);
  4791. if (pool)
  4792. free(pool);
  4793. }
  4794. return ret;
  4795. }
  4796. #if defined(unix)
  4797. static void fork_monitor()
  4798. {
  4799. // Make a pipe: [readFD, writeFD]
  4800. int pfd[2];
  4801. int r = pipe(pfd);
  4802. if (r<0) {
  4803. perror("pipe - failed to create pipe for --monitor");
  4804. exit(1);
  4805. }
  4806. // Make stderr write end of pipe
  4807. fflush(stderr);
  4808. r = dup2(pfd[1], 2);
  4809. if (r<0) {
  4810. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  4811. exit(1);
  4812. }
  4813. r = close(pfd[1]);
  4814. if (r<0) {
  4815. perror("close - failed to close write end of pipe for --monitor");
  4816. exit(1);
  4817. }
  4818. // Don't allow a dying monitor to kill the main process
  4819. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  4820. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  4821. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  4822. perror("signal - failed to edit signal mask for --monitor");
  4823. exit(1);
  4824. }
  4825. // Fork a child process
  4826. r = fork();
  4827. if (r<0) {
  4828. perror("fork - failed to fork child process for --monitor");
  4829. exit(1);
  4830. }
  4831. // Child: launch monitor command
  4832. if (0==r) {
  4833. // Make stdin read end of pipe
  4834. r = dup2(pfd[0], 0);
  4835. if (r<0) {
  4836. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  4837. exit(1);
  4838. }
  4839. close(pfd[0]);
  4840. if (r<0) {
  4841. perror("close - in child, failed to close read end of pipe for --monitor");
  4842. exit(1);
  4843. }
  4844. // Launch user specified command
  4845. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  4846. perror("execl - in child failed to exec user specified command for --monitor");
  4847. exit(1);
  4848. }
  4849. // Parent: clean up unused fds and bail
  4850. r = close(pfd[0]);
  4851. if (r<0) {
  4852. perror("close - failed to close read end of pipe for --monitor");
  4853. exit(1);
  4854. }
  4855. }
  4856. #endif // defined(unix)
  4857. static void enable_curses(void) {
  4858. int x,y;
  4859. lock_curses();
  4860. if (curses_active) {
  4861. unlock_curses();
  4862. return;
  4863. }
  4864. mainwin = initscr();
  4865. getmaxyx(mainwin, y, x);
  4866. statuswin = newwin(logstart, x, 0, 0);
  4867. leaveok(statuswin, true);
  4868. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4869. idlok(logwin, true);
  4870. scrollok(logwin, true);
  4871. leaveok(logwin, true);
  4872. cbreak();
  4873. noecho();
  4874. curses_active = true;
  4875. unlock_curses();
  4876. }
  4877. int main (int argc, char *argv[])
  4878. {
  4879. unsigned int i, pools_active = 0;
  4880. struct block *block, *tmpblock;
  4881. struct work *work, *tmpwork;
  4882. struct sigaction handler;
  4883. struct thr_info *thr;
  4884. char name[256];
  4885. /* This dangerous functions tramples random dynamically allocated
  4886. * variables so do it before anything at all */
  4887. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4888. quit(1, "Failed to curl_global_init");
  4889. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  4890. quit(1, "Failed to pthread_mutex_init");
  4891. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  4892. quit(1, "Failed to pthread_mutex_init");
  4893. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  4894. quit(1, "Failed to pthread_mutex_init");
  4895. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  4896. quit(1, "Failed to pthread_mutex_init");
  4897. if (unlikely(pthread_rwlock_init(&blk_lock, NULL)))
  4898. quit(1, "Failed to pthread_rwlock_init");
  4899. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4900. init_max_name_len();
  4901. handler.sa_handler = &sighandler;
  4902. handler.sa_flags = 0;
  4903. sigemptyset(&handler.sa_mask);
  4904. sigaction(SIGTERM, &handler, &termhandler);
  4905. sigaction(SIGINT, &handler, &inthandler);
  4906. opt_kernel_path = alloca(PATH_MAX);
  4907. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4908. cgminer_path = alloca(PATH_MAX);
  4909. strcpy(cgminer_path, dirname(argv[0]));
  4910. strcat(cgminer_path, "/");
  4911. // Hack to make cgminer silent when called recursively on WIN32
  4912. int skip_to_bench = 0;
  4913. #if defined(WIN32)
  4914. char buf[32];
  4915. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4916. skip_to_bench = 1;
  4917. #endif // defined(WIN32)
  4918. block = calloc(sizeof(struct block), 1);
  4919. if (unlikely(!block))
  4920. quit (1, "main OOM");
  4921. for (i = 0; i < 36; i++)
  4922. strcat(block->hash, "0");
  4923. HASH_ADD_STR(blocks, hash, block);
  4924. strcpy(current_block, block->hash);
  4925. // Reckon number of cores in the box
  4926. #if defined(WIN32)
  4927. DWORD system_am;
  4928. DWORD process_am;
  4929. BOOL ok = GetProcessAffinityMask(
  4930. GetCurrentProcess(),
  4931. &system_am,
  4932. &process_am
  4933. );
  4934. if (!ok) {
  4935. applog(LOG_ERR, "couldn't figure out number of processors :(");
  4936. num_processors = 1;
  4937. } else {
  4938. size_t n = 32;
  4939. num_processors = 0;
  4940. while (n--)
  4941. if (process_am & (1<<n))
  4942. ++num_processors;
  4943. }
  4944. #else
  4945. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  4946. #endif /* !WIN32 */
  4947. opt_n_threads = num_processors;
  4948. #ifdef HAVE_OPENCL
  4949. if (!skip_to_bench) {
  4950. for (i = 0; i < MAX_GPUDEVICES; i++) {
  4951. gpu_devices[i] = false;
  4952. gpus[i].dynamic = true;
  4953. }
  4954. nDevs = clDevicesNum();
  4955. if (nDevs < 0) {
  4956. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  4957. nDevs = 0;
  4958. }
  4959. }
  4960. #endif
  4961. /* parse command line */
  4962. opt_register_table(opt_config_table,
  4963. "Options for both config file and command line");
  4964. opt_register_table(opt_cmdline_table,
  4965. "Options for command line only");
  4966. if (!config_loaded)
  4967. load_default_config();
  4968. opt_parse(&argc, argv, applog_and_exit);
  4969. if (argc != 1)
  4970. quit(1, "Unexpected extra commandline arguments");
  4971. applog(LOG_WARNING, "Started %s", packagename);
  4972. if (opt_nogpu)
  4973. nDevs = 0;
  4974. if (nDevs && !opt_usecpu)
  4975. opt_n_threads = 0;
  4976. strcat(opt_kernel_path, "/");
  4977. if (want_per_device_stats)
  4978. opt_log_output = true;
  4979. if (0<=opt_bench_algo) {
  4980. double rate = bench_algo_stage3(opt_bench_algo);
  4981. if (!skip_to_bench) {
  4982. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4983. } else {
  4984. // Write result to shared memory for parent
  4985. #if defined(WIN32)
  4986. char unique_name[64];
  4987. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4988. HANDLE map_handle = CreateFileMapping(
  4989. INVALID_HANDLE_VALUE, // use paging file
  4990. NULL, // default security attributes
  4991. PAGE_READWRITE, // read/write access
  4992. 0, // size: high 32-bits
  4993. 4096, // size: low 32-bits
  4994. unique_name // name of map object
  4995. );
  4996. if (NULL!=map_handle) {
  4997. void *shared_mem = MapViewOfFile(
  4998. map_handle, // object to map view of
  4999. FILE_MAP_WRITE, // read/write access
  5000. 0, // high offset: map from
  5001. 0, // low offset: beginning
  5002. 0 // default: map entire file
  5003. );
  5004. if (NULL!=shared_mem)
  5005. CopyMemory(shared_mem, &rate, sizeof(rate));
  5006. (void)UnmapViewOfFile(shared_mem);
  5007. }
  5008. (void)CloseHandle(map_handle);
  5009. }
  5010. #endif
  5011. }
  5012. exit(0);
  5013. }
  5014. if (opt_kernel) {
  5015. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  5016. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  5017. if (!strcmp(opt_kernel, "poclbm"))
  5018. chosen_kernel = KL_POCLBM;
  5019. else
  5020. chosen_kernel = KL_PHATK;
  5021. } else
  5022. chosen_kernel = KL_NONE;
  5023. #ifdef HAVE_OPENCL
  5024. gpu_threads = nDevs * opt_g_threads;
  5025. if (total_devices) {
  5026. if (total_devices > nDevs)
  5027. quit(1, "More devices specified than exist");
  5028. for (i = 0; i < MAX_GPUDEVICES; i++)
  5029. if (gpu_devices[i] && i + 1 > nDevs)
  5030. quit (1, "Command line options set a device that doesn't exist");
  5031. #ifdef HAVE_ADL
  5032. for (i = 0; i < nDevs; i++) {
  5033. /* Make sure we do not attempt to adl manage devices
  5034. * that we disable */
  5035. if (!gpu_devices[i])
  5036. gpus[i].gpu_engine =
  5037. gpus[i].gpu_memclock =
  5038. gpus[i].gpu_vddc =
  5039. gpus[i].gpu_fan =
  5040. gpus[i].gpu_powertune = 0;
  5041. }
  5042. #endif
  5043. } else {
  5044. for (i = 0; i < nDevs; i++)
  5045. gpu_devices[i] = true;
  5046. total_devices = nDevs;
  5047. }
  5048. #else
  5049. gpu_threads = 0;
  5050. #endif
  5051. if (!gpu_threads && !forced_n_threads) {
  5052. /* Maybe they turned GPU off; restore default CPU threads. */
  5053. opt_n_threads = num_processors;
  5054. }
  5055. if (!opt_n_threads && ! gpu_threads)
  5056. quit(1, "All devices disabled, cannot mine!");
  5057. logcursor = 8;
  5058. gpucursor = logcursor;
  5059. cpucursor = gpucursor + nDevs;
  5060. logstart = cpucursor + 1;
  5061. if (opt_n_threads) {
  5062. if (opt_n_threads < num_processors)
  5063. logstart += opt_n_threads;
  5064. else
  5065. logstart += num_processors;
  5066. }
  5067. logcursor = logstart + 1;
  5068. if (opt_realquiet)
  5069. use_curses = false;
  5070. if (!total_pools) {
  5071. enable_curses();
  5072. applog(LOG_WARNING, "Need to specify at least one pool server.");
  5073. if (!input_pool(false))
  5074. quit(1, "Pool setup failed");
  5075. if (!use_curses)
  5076. disable_curses();
  5077. }
  5078. for (i = 0; i < total_pools; i++) {
  5079. struct pool *pool = pools[i];
  5080. if (!pool->rpc_userpass) {
  5081. if (!pool->rpc_user || !pool->rpc_pass)
  5082. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  5083. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  5084. if (!pool->rpc_userpass)
  5085. quit(1, "Failed to malloc userpass");
  5086. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  5087. } else {
  5088. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  5089. if (!pool->rpc_user)
  5090. quit(1, "Failed to malloc user");
  5091. strcpy(pool->rpc_user, pool->rpc_userpass);
  5092. pool->rpc_user = strtok(pool->rpc_user, ":");
  5093. if (!pool->rpc_user)
  5094. quit(1, "Failed to find colon delimiter in userpass");
  5095. }
  5096. }
  5097. /* Set the currentpool to pool 0 */
  5098. currentpool = pools[0];
  5099. #ifdef HAVE_SYSLOG_H
  5100. if (use_syslog)
  5101. openlog(PACKAGE, LOG_PID, LOG_USER);
  5102. #endif
  5103. #if defined(unix)
  5104. if (opt_stderr_cmd)
  5105. fork_monitor();
  5106. #endif // defined(unix)
  5107. mining_threads = opt_n_threads + gpu_threads;
  5108. total_threads = mining_threads + 8;
  5109. work_restart = calloc(total_threads, sizeof(*work_restart));
  5110. if (!work_restart)
  5111. quit(1, "Failed to calloc work_restart");
  5112. thr_info = calloc(total_threads, sizeof(*thr));
  5113. if (!thr_info)
  5114. quit(1, "Failed to calloc thr_info");
  5115. /* init workio thread info */
  5116. work_thr_id = mining_threads;
  5117. thr = &thr_info[work_thr_id];
  5118. thr->id = work_thr_id;
  5119. thr->q = tq_new();
  5120. if (!thr->q)
  5121. quit(1, "Failed to tq_new");
  5122. /* start work I/O thread */
  5123. if (thr_info_create(thr, NULL, workio_thread, thr))
  5124. quit(1, "workio thread create failed");
  5125. /* init longpoll thread info */
  5126. longpoll_thr_id = mining_threads + 1;
  5127. thr = &thr_info[longpoll_thr_id];
  5128. thr->id = longpoll_thr_id;
  5129. thr->q = tq_new();
  5130. if (!thr->q)
  5131. quit(1, "Failed to tq_new");
  5132. if (opt_n_threads ) {
  5133. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  5134. if (unlikely(!cpus))
  5135. quit(1, "Failed to calloc cpus");
  5136. }
  5137. stage_thr_id = mining_threads + 3;
  5138. thr = &thr_info[stage_thr_id];
  5139. thr->q = tq_new();
  5140. if (!thr->q)
  5141. quit(1, "Failed to tq_new");
  5142. /* start stage thread */
  5143. if (thr_info_create(thr, NULL, stage_thread, thr))
  5144. quit(1, "stage thread create failed");
  5145. pthread_detach(thr->pth);
  5146. /* Create a unique get work queue */
  5147. getq = tq_new();
  5148. if (!getq)
  5149. quit(1, "Failed to create getq");
  5150. /* We use the getq mutex as the staged lock */
  5151. stgd_lock = &getq->mutex;
  5152. retry_pools:
  5153. /* Test each pool to see if we can retrieve and use work and for what
  5154. * it supports */
  5155. for (i = 0; i < total_pools; i++) {
  5156. struct pool *pool;
  5157. pool = pools[i];
  5158. pool->enabled = true;
  5159. if (pool_active(pool, false)) {
  5160. if (!currentpool)
  5161. currentpool = pool;
  5162. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  5163. pools_active++;
  5164. } else {
  5165. if (pool == currentpool)
  5166. currentpool = NULL;
  5167. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  5168. pool->idle = true;
  5169. }
  5170. }
  5171. if (!pools_active) {
  5172. enable_curses();
  5173. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  5174. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  5175. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  5176. for (i = 0; i < total_pools; i++) {
  5177. struct pool *pool;
  5178. pool = pools[i];
  5179. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  5180. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  5181. }
  5182. halfdelay(150);
  5183. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  5184. if (getch() != ERR)
  5185. quit(0, "No servers could be used! Exiting.");
  5186. nocbreak();
  5187. goto retry_pools;
  5188. }
  5189. if (opt_donation > 0.0) {
  5190. if (!get_dondata(&donationpool.rpc_url, &donationpool.rpc_userpass))
  5191. opt_donation = 0.0;
  5192. else {
  5193. if (unlikely(pthread_mutex_init(&donationpool.pool_lock, NULL)))
  5194. quit (1, "Failed to pthread_mutex_init in add donpool");
  5195. donationpool.enabled = true;
  5196. donationpool.pool_no = MAX_POOLS;
  5197. if (!pool_active(&donationpool, false))
  5198. donationpool.idle = true;
  5199. }
  5200. }
  5201. if (want_longpoll)
  5202. start_longpoll();
  5203. gettimeofday(&total_tv_start, NULL);
  5204. gettimeofday(&total_tv_end, NULL);
  5205. get_datestamp(datestamp, &total_tv_start);
  5206. #ifdef HAVE_OPENCL
  5207. if (!opt_noadl)
  5208. init_adl(nDevs);
  5209. bool failmessage = false;
  5210. /* start GPU mining threads */
  5211. for (i = 0; i < nDevs * opt_g_threads; i++) {
  5212. int gpu = i % nDevs;
  5213. struct cgpu_info *cgpu;
  5214. struct timeval now;
  5215. gpus[gpu].is_gpu = 1;
  5216. gpus[gpu].cpu_gpu = gpu;
  5217. thr = &thr_info[i];
  5218. thr->id = i;
  5219. cgpu = thr->cgpu = &gpus[gpu];
  5220. thr->q = tq_new();
  5221. if (!thr->q)
  5222. quit(1, "tq_new failed in starting gpu mining threads");
  5223. /* Enable threads for devices set not to mine but disable
  5224. * their queue in case we wish to enable them later*/
  5225. if (gpu_devices[gpu]) {
  5226. if (opt_debug)
  5227. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  5228. tq_push(thr->q, &ping);
  5229. }
  5230. applog(LOG_INFO, "Init GPU thread %i", i);
  5231. clStates[i] = initCl(gpu, name, sizeof(name));
  5232. if (!clStates[i]) {
  5233. enable_curses();
  5234. applog(LOG_ERR, "Failed to init GPU thread %d, disabling device %d", i, gpu);
  5235. if (!failmessage) {
  5236. char *buf;
  5237. applog(LOG_ERR, "Restarting the GPU from the menu is unlikely to fix this.");
  5238. applog(LOG_ERR, "Try stopping other applications using the GPU like afterburner.");
  5239. applog(LOG_ERR, "Then restart cgminer.");
  5240. failmessage = true;
  5241. buf = curses_input("Press enter to continue");
  5242. if (buf)
  5243. free(buf);
  5244. }
  5245. gpu_devices[gpu] = false;
  5246. cgpu->status = LIFE_NOSTART;
  5247. continue;
  5248. }
  5249. applog(LOG_INFO, "initCl() finished. Found %s", name);
  5250. gettimeofday(&now, NULL);
  5251. get_datestamp(cgpu->init, &now);
  5252. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  5253. quit(1, "thread %d create failed", i);
  5254. }
  5255. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  5256. #else
  5257. opt_g_threads = 0;
  5258. #endif
  5259. /* start CPU mining threads */
  5260. for (i = gpu_threads; i < mining_threads; i++) {
  5261. int cpu = (i - gpu_threads) % num_processors;
  5262. thr = &thr_info[i];
  5263. thr->id = i;
  5264. cpus[cpu].cpu_gpu = cpu;
  5265. thr->cgpu = &cpus[cpu];
  5266. thr->q = tq_new();
  5267. if (!thr->q)
  5268. quit(1, "tq_new failed in starting cpu mining threads");
  5269. thread_reportin(thr);
  5270. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  5271. quit(1, "thread %d create failed", i);
  5272. }
  5273. applog(LOG_INFO, "%d cpu miner threads started, "
  5274. "using SHA256 '%s' algorithm.",
  5275. opt_n_threads,
  5276. algo_names[opt_algo]);
  5277. if (use_curses)
  5278. enable_curses();
  5279. watchdog_thr_id = mining_threads + 2;
  5280. thr = &thr_info[watchdog_thr_id];
  5281. /* start wakeup thread */
  5282. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  5283. quit(1, "wakeup thread create failed");
  5284. /* Create curses input thread for keyboard input */
  5285. input_thr_id = mining_threads + 4;
  5286. thr = &thr_info[input_thr_id];
  5287. if (thr_info_create(thr, NULL, input_thread, thr))
  5288. quit(1, "input thread create failed");
  5289. pthread_detach(thr->pth);
  5290. /* Create reinit cpu thread */
  5291. cpur_thr_id = mining_threads + 5;
  5292. thr = &thr_info[cpur_thr_id];
  5293. thr->q = tq_new();
  5294. if (!thr->q)
  5295. quit(1, "tq_new failed for cpur_thr_id");
  5296. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  5297. quit(1, "reinit_cpu thread create failed");
  5298. /* Create reinit gpu thread */
  5299. gpur_thr_id = mining_threads + 6;
  5300. thr = &thr_info[gpur_thr_id];
  5301. thr->q = tq_new();
  5302. if (!thr->q)
  5303. quit(1, "tq_new failed for gpur_thr_id");
  5304. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  5305. quit(1, "reinit_gpu thread create failed");
  5306. /* Create API socket thread */
  5307. api_thr_id = mining_threads + 7;
  5308. thr = &thr_info[api_thr_id];
  5309. if (thr_info_create(thr, NULL, api_thread, thr))
  5310. quit(1, "API thread create failed");
  5311. pthread_detach(thr->pth);
  5312. sleep(opt_log_interval);
  5313. if (opt_donation > 0.0)
  5314. applog(LOG_WARNING, "Donation is enabled at %.1f%% thank you :-)", opt_donation);
  5315. else
  5316. applog(LOG_WARNING, "--donation is disabled, please consider just 0.5%% :-(");
  5317. /* main loop - simply wait for workio thread to exit */
  5318. pthread_join(thr_info[work_thr_id].pth, NULL);
  5319. applog(LOG_INFO, "workio thread dead, exiting.");
  5320. gettimeofday(&total_tv_end, NULL);
  5321. disable_curses();
  5322. if (!opt_realquiet && successful_connect)
  5323. print_summary();
  5324. #ifdef HAVE_OPENCL
  5325. clear_adl(nDevs);
  5326. #endif
  5327. if (opt_n_threads)
  5328. free(cpus);
  5329. HASH_ITER(hh, staged_work, work, tmpwork) {
  5330. HASH_DEL(staged_work, work);
  5331. free_work(work);
  5332. }
  5333. HASH_ITER(hh, blocks, block, tmpblock) {
  5334. HASH_DEL(blocks, block);
  5335. free(block);
  5336. }
  5337. curl_global_cleanup();
  5338. return 0;
  5339. }