main.c 149 KB

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