main.c 127 KB

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