cgminer.c 145 KB

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