cgminer.c 115 KB

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