cgminer.c 115 KB

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