main.c 116 KB

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