cgminer.c 117 KB

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