cgminer.c 119 KB

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