main.c 152 KB

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