main.c 161 KB

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