cgminer.c 126 KB

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