cgminer.c 136 KB

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