main.c 122 KB

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