main.c 148 KB

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