main.c 140 KB

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