main.c 124 KB

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