main.c 158 KB

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