main.c 140 KB

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