core.c 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * NVM Express device driver
  4. * Copyright (c) 2011-2014, Intel Corporation.
  5. */
  6. #include <linux/async.h>
  7. #include <linux/blkdev.h>
  8. #include <linux/blk-mq.h>
  9. #include <linux/blk-integrity.h>
  10. #include <linux/compat.h>
  11. #include <linux/delay.h>
  12. #include <linux/errno.h>
  13. #include <linux/hdreg.h>
  14. #include <linux/kernel.h>
  15. #include <linux/module.h>
  16. #include <linux/backing-dev.h>
  17. #include <linux/slab.h>
  18. #include <linux/types.h>
  19. #include <linux/pr.h>
  20. #include <linux/ptrace.h>
  21. #include <linux/nvme_ioctl.h>
  22. #include <linux/pm_qos.h>
  23. #include <linux/ratelimit.h>
  24. #include <linux/unaligned.h>
  25. #include "nvme.h"
  26. #include "fabrics.h"
  27. #include <linux/nvme-auth.h>
  28. #define CREATE_TRACE_POINTS
  29. #include "trace.h"
  30. #define NVME_MINORS (1U << MINORBITS)
  31. struct nvme_ns_info {
  32. struct nvme_ns_ids ids;
  33. u32 nsid;
  34. __le32 anagrpid;
  35. u8 pi_offset;
  36. bool is_shared;
  37. bool is_readonly;
  38. bool is_ready;
  39. bool is_removed;
  40. };
  41. unsigned int admin_timeout = 60;
  42. module_param(admin_timeout, uint, 0644);
  43. MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
  44. EXPORT_SYMBOL_GPL(admin_timeout);
  45. unsigned int nvme_io_timeout = 30;
  46. module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
  47. MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
  48. EXPORT_SYMBOL_GPL(nvme_io_timeout);
  49. static unsigned char shutdown_timeout = 5;
  50. module_param(shutdown_timeout, byte, 0644);
  51. MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
  52. static u8 nvme_max_retries = 5;
  53. module_param_named(max_retries, nvme_max_retries, byte, 0644);
  54. MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
  55. static unsigned long default_ps_max_latency_us = 100000;
  56. module_param(default_ps_max_latency_us, ulong, 0644);
  57. MODULE_PARM_DESC(default_ps_max_latency_us,
  58. "max power saving latency for new devices; use PM QOS to change per device");
  59. static bool force_apst;
  60. module_param(force_apst, bool, 0644);
  61. MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
  62. static unsigned long apst_primary_timeout_ms = 100;
  63. module_param(apst_primary_timeout_ms, ulong, 0644);
  64. MODULE_PARM_DESC(apst_primary_timeout_ms,
  65. "primary APST timeout in ms");
  66. static unsigned long apst_secondary_timeout_ms = 2000;
  67. module_param(apst_secondary_timeout_ms, ulong, 0644);
  68. MODULE_PARM_DESC(apst_secondary_timeout_ms,
  69. "secondary APST timeout in ms");
  70. static unsigned long apst_primary_latency_tol_us = 15000;
  71. module_param(apst_primary_latency_tol_us, ulong, 0644);
  72. MODULE_PARM_DESC(apst_primary_latency_tol_us,
  73. "primary APST latency tolerance in us");
  74. static unsigned long apst_secondary_latency_tol_us = 100000;
  75. module_param(apst_secondary_latency_tol_us, ulong, 0644);
  76. MODULE_PARM_DESC(apst_secondary_latency_tol_us,
  77. "secondary APST latency tolerance in us");
  78. /*
  79. * Older kernels didn't enable protection information if it was at an offset.
  80. * Newer kernels do, so it breaks reads on the upgrade if such formats were
  81. * used in prior kernels since the metadata written did not contain a valid
  82. * checksum.
  83. */
  84. static bool disable_pi_offsets = false;
  85. module_param(disable_pi_offsets, bool, 0444);
  86. MODULE_PARM_DESC(disable_pi_offsets,
  87. "disable protection information if it has an offset");
  88. /*
  89. * nvme_wq - hosts nvme related works that are not reset or delete
  90. * nvme_reset_wq - hosts nvme reset works
  91. * nvme_delete_wq - hosts nvme delete works
  92. *
  93. * nvme_wq will host works such as scan, aen handling, fw activation,
  94. * keep-alive, periodic reconnects etc. nvme_reset_wq
  95. * runs reset works which also flush works hosted on nvme_wq for
  96. * serialization purposes. nvme_delete_wq host controller deletion
  97. * works which flush reset works for serialization.
  98. */
  99. struct workqueue_struct *nvme_wq;
  100. EXPORT_SYMBOL_GPL(nvme_wq);
  101. struct workqueue_struct *nvme_reset_wq;
  102. EXPORT_SYMBOL_GPL(nvme_reset_wq);
  103. struct workqueue_struct *nvme_delete_wq;
  104. EXPORT_SYMBOL_GPL(nvme_delete_wq);
  105. static LIST_HEAD(nvme_subsystems);
  106. DEFINE_MUTEX(nvme_subsystems_lock);
  107. static DEFINE_IDA(nvme_instance_ida);
  108. static dev_t nvme_ctrl_base_chr_devt;
  109. static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env);
  110. static const struct class nvme_class = {
  111. .name = "nvme",
  112. .dev_uevent = nvme_class_uevent,
  113. };
  114. static const struct class nvme_subsys_class = {
  115. .name = "nvme-subsystem",
  116. };
  117. static DEFINE_IDA(nvme_ns_chr_minor_ida);
  118. static dev_t nvme_ns_chr_devt;
  119. static const struct class nvme_ns_chr_class = {
  120. .name = "nvme-generic",
  121. };
  122. static void nvme_put_subsystem(struct nvme_subsystem *subsys);
  123. static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
  124. unsigned nsid);
  125. static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
  126. struct nvme_command *cmd);
  127. void nvme_queue_scan(struct nvme_ctrl *ctrl)
  128. {
  129. /*
  130. * Only new queue scan work when admin and IO queues are both alive
  131. */
  132. if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE && ctrl->tagset)
  133. queue_work(nvme_wq, &ctrl->scan_work);
  134. }
  135. /*
  136. * Use this function to proceed with scheduling reset_work for a controller
  137. * that had previously been set to the resetting state. This is intended for
  138. * code paths that can't be interrupted by other reset attempts. A hot removal
  139. * may prevent this from succeeding.
  140. */
  141. int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
  142. {
  143. if (nvme_ctrl_state(ctrl) != NVME_CTRL_RESETTING)
  144. return -EBUSY;
  145. if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
  146. return -EBUSY;
  147. return 0;
  148. }
  149. EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
  150. static void nvme_failfast_work(struct work_struct *work)
  151. {
  152. struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
  153. struct nvme_ctrl, failfast_work);
  154. if (nvme_ctrl_state(ctrl) != NVME_CTRL_CONNECTING)
  155. return;
  156. set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
  157. dev_info(ctrl->device, "failfast expired\n");
  158. nvme_kick_requeue_lists(ctrl);
  159. }
  160. static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
  161. {
  162. if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
  163. return;
  164. schedule_delayed_work(&ctrl->failfast_work,
  165. ctrl->opts->fast_io_fail_tmo * HZ);
  166. }
  167. static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
  168. {
  169. if (!ctrl->opts)
  170. return;
  171. cancel_delayed_work_sync(&ctrl->failfast_work);
  172. clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
  173. }
  174. int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
  175. {
  176. if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
  177. return -EBUSY;
  178. if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
  179. return -EBUSY;
  180. return 0;
  181. }
  182. EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
  183. int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
  184. {
  185. int ret;
  186. ret = nvme_reset_ctrl(ctrl);
  187. if (!ret) {
  188. flush_work(&ctrl->reset_work);
  189. if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE)
  190. ret = -ENETRESET;
  191. }
  192. return ret;
  193. }
  194. static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
  195. {
  196. dev_info(ctrl->device,
  197. "Removing ctrl: NQN \"%s\"\n", nvmf_ctrl_subsysnqn(ctrl));
  198. flush_work(&ctrl->reset_work);
  199. nvme_stop_ctrl(ctrl);
  200. nvme_remove_namespaces(ctrl);
  201. ctrl->ops->delete_ctrl(ctrl);
  202. nvme_uninit_ctrl(ctrl);
  203. }
  204. static void nvme_delete_ctrl_work(struct work_struct *work)
  205. {
  206. struct nvme_ctrl *ctrl =
  207. container_of(work, struct nvme_ctrl, delete_work);
  208. nvme_do_delete_ctrl(ctrl);
  209. }
  210. int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
  211. {
  212. if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
  213. return -EBUSY;
  214. if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
  215. return -EBUSY;
  216. return 0;
  217. }
  218. EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
  219. void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
  220. {
  221. /*
  222. * Keep a reference until nvme_do_delete_ctrl() complete,
  223. * since ->delete_ctrl can free the controller.
  224. */
  225. nvme_get_ctrl(ctrl);
  226. if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
  227. nvme_do_delete_ctrl(ctrl);
  228. nvme_put_ctrl(ctrl);
  229. }
  230. static blk_status_t nvme_error_status(u16 status)
  231. {
  232. switch (status & NVME_SCT_SC_MASK) {
  233. case NVME_SC_SUCCESS:
  234. return BLK_STS_OK;
  235. case NVME_SC_CAP_EXCEEDED:
  236. return BLK_STS_NOSPC;
  237. case NVME_SC_LBA_RANGE:
  238. case NVME_SC_CMD_INTERRUPTED:
  239. case NVME_SC_NS_NOT_READY:
  240. return BLK_STS_TARGET;
  241. case NVME_SC_BAD_ATTRIBUTES:
  242. case NVME_SC_INVALID_OPCODE:
  243. case NVME_SC_INVALID_FIELD:
  244. case NVME_SC_INVALID_NS:
  245. return BLK_STS_NOTSUPP;
  246. case NVME_SC_WRITE_FAULT:
  247. case NVME_SC_READ_ERROR:
  248. case NVME_SC_UNWRITTEN_BLOCK:
  249. case NVME_SC_ACCESS_DENIED:
  250. case NVME_SC_READ_ONLY:
  251. case NVME_SC_COMPARE_FAILED:
  252. return BLK_STS_MEDIUM;
  253. case NVME_SC_GUARD_CHECK:
  254. case NVME_SC_APPTAG_CHECK:
  255. case NVME_SC_REFTAG_CHECK:
  256. case NVME_SC_INVALID_PI:
  257. return BLK_STS_PROTECTION;
  258. case NVME_SC_RESERVATION_CONFLICT:
  259. return BLK_STS_RESV_CONFLICT;
  260. case NVME_SC_HOST_PATH_ERROR:
  261. return BLK_STS_TRANSPORT;
  262. case NVME_SC_ZONE_TOO_MANY_ACTIVE:
  263. return BLK_STS_ZONE_ACTIVE_RESOURCE;
  264. case NVME_SC_ZONE_TOO_MANY_OPEN:
  265. return BLK_STS_ZONE_OPEN_RESOURCE;
  266. default:
  267. return BLK_STS_IOERR;
  268. }
  269. }
  270. static void nvme_retry_req(struct request *req)
  271. {
  272. unsigned long delay = 0;
  273. u16 crd;
  274. /* The mask and shift result must be <= 3 */
  275. crd = (nvme_req(req)->status & NVME_STATUS_CRD) >> 11;
  276. if (crd)
  277. delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
  278. nvme_req(req)->retries++;
  279. blk_mq_requeue_request(req, false);
  280. blk_mq_delay_kick_requeue_list(req->q, delay);
  281. }
  282. static void nvme_log_error(struct request *req)
  283. {
  284. struct nvme_ns *ns = req->q->queuedata;
  285. struct nvme_request *nr = nvme_req(req);
  286. if (ns) {
  287. pr_err_ratelimited("%s: %s(0x%x) @ LBA %llu, %u blocks, %s (sct 0x%x / sc 0x%x) %s%s\n",
  288. ns->disk ? ns->disk->disk_name : "?",
  289. nvme_get_opcode_str(nr->cmd->common.opcode),
  290. nr->cmd->common.opcode,
  291. nvme_sect_to_lba(ns->head, blk_rq_pos(req)),
  292. blk_rq_bytes(req) >> ns->head->lba_shift,
  293. nvme_get_error_status_str(nr->status),
  294. NVME_SCT(nr->status), /* Status Code Type */
  295. nr->status & NVME_SC_MASK, /* Status Code */
  296. nr->status & NVME_STATUS_MORE ? "MORE " : "",
  297. nr->status & NVME_STATUS_DNR ? "DNR " : "");
  298. return;
  299. }
  300. pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s\n",
  301. dev_name(nr->ctrl->device),
  302. nvme_get_admin_opcode_str(nr->cmd->common.opcode),
  303. nr->cmd->common.opcode,
  304. nvme_get_error_status_str(nr->status),
  305. NVME_SCT(nr->status), /* Status Code Type */
  306. nr->status & NVME_SC_MASK, /* Status Code */
  307. nr->status & NVME_STATUS_MORE ? "MORE " : "",
  308. nr->status & NVME_STATUS_DNR ? "DNR " : "");
  309. }
  310. static void nvme_log_err_passthru(struct request *req)
  311. {
  312. struct nvme_ns *ns = req->q->queuedata;
  313. struct nvme_request *nr = nvme_req(req);
  314. pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s"
  315. "cdw10=0x%x cdw11=0x%x cdw12=0x%x cdw13=0x%x cdw14=0x%x cdw15=0x%x\n",
  316. ns ? ns->disk->disk_name : dev_name(nr->ctrl->device),
  317. ns ? nvme_get_opcode_str(nr->cmd->common.opcode) :
  318. nvme_get_admin_opcode_str(nr->cmd->common.opcode),
  319. nr->cmd->common.opcode,
  320. nvme_get_error_status_str(nr->status),
  321. NVME_SCT(nr->status), /* Status Code Type */
  322. nr->status & NVME_SC_MASK, /* Status Code */
  323. nr->status & NVME_STATUS_MORE ? "MORE " : "",
  324. nr->status & NVME_STATUS_DNR ? "DNR " : "",
  325. le32_to_cpu(nr->cmd->common.cdw10),
  326. le32_to_cpu(nr->cmd->common.cdw11),
  327. le32_to_cpu(nr->cmd->common.cdw12),
  328. le32_to_cpu(nr->cmd->common.cdw13),
  329. le32_to_cpu(nr->cmd->common.cdw14),
  330. le32_to_cpu(nr->cmd->common.cdw15));
  331. }
  332. enum nvme_disposition {
  333. COMPLETE,
  334. RETRY,
  335. FAILOVER,
  336. AUTHENTICATE,
  337. };
  338. static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
  339. {
  340. if (likely(nvme_req(req)->status == 0))
  341. return COMPLETE;
  342. if (blk_noretry_request(req) ||
  343. (nvme_req(req)->status & NVME_STATUS_DNR) ||
  344. nvme_req(req)->retries >= nvme_max_retries)
  345. return COMPLETE;
  346. if ((nvme_req(req)->status & NVME_SCT_SC_MASK) == NVME_SC_AUTH_REQUIRED)
  347. return AUTHENTICATE;
  348. if (req->cmd_flags & REQ_NVME_MPATH) {
  349. if (nvme_is_path_error(nvme_req(req)->status) ||
  350. blk_queue_dying(req->q))
  351. return FAILOVER;
  352. } else {
  353. if (blk_queue_dying(req->q))
  354. return COMPLETE;
  355. }
  356. return RETRY;
  357. }
  358. static inline void nvme_end_req_zoned(struct request *req)
  359. {
  360. if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
  361. req_op(req) == REQ_OP_ZONE_APPEND) {
  362. struct nvme_ns *ns = req->q->queuedata;
  363. req->__sector = nvme_lba_to_sect(ns->head,
  364. le64_to_cpu(nvme_req(req)->result.u64));
  365. }
  366. }
  367. static inline void __nvme_end_req(struct request *req)
  368. {
  369. if (unlikely(nvme_req(req)->status && !(req->rq_flags & RQF_QUIET))) {
  370. if (blk_rq_is_passthrough(req))
  371. nvme_log_err_passthru(req);
  372. else
  373. nvme_log_error(req);
  374. }
  375. nvme_end_req_zoned(req);
  376. nvme_trace_bio_complete(req);
  377. if (req->cmd_flags & REQ_NVME_MPATH)
  378. nvme_mpath_end_request(req);
  379. }
  380. void nvme_end_req(struct request *req)
  381. {
  382. blk_status_t status = nvme_error_status(nvme_req(req)->status);
  383. __nvme_end_req(req);
  384. blk_mq_end_request(req, status);
  385. }
  386. void nvme_complete_rq(struct request *req)
  387. {
  388. struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
  389. trace_nvme_complete_rq(req);
  390. nvme_cleanup_cmd(req);
  391. /*
  392. * Completions of long-running commands should not be able to
  393. * defer sending of periodic keep alives, since the controller
  394. * may have completed processing such commands a long time ago
  395. * (arbitrarily close to command submission time).
  396. * req->deadline - req->timeout is the command submission time
  397. * in jiffies.
  398. */
  399. if (ctrl->kas &&
  400. req->deadline - req->timeout >= ctrl->ka_last_check_time)
  401. ctrl->comp_seen = true;
  402. switch (nvme_decide_disposition(req)) {
  403. case COMPLETE:
  404. nvme_end_req(req);
  405. return;
  406. case RETRY:
  407. nvme_retry_req(req);
  408. return;
  409. case FAILOVER:
  410. nvme_failover_req(req);
  411. return;
  412. case AUTHENTICATE:
  413. #ifdef CONFIG_NVME_HOST_AUTH
  414. queue_work(nvme_wq, &ctrl->dhchap_auth_work);
  415. nvme_retry_req(req);
  416. #else
  417. nvme_end_req(req);
  418. #endif
  419. return;
  420. }
  421. }
  422. EXPORT_SYMBOL_GPL(nvme_complete_rq);
  423. void nvme_complete_batch_req(struct request *req)
  424. {
  425. trace_nvme_complete_rq(req);
  426. nvme_cleanup_cmd(req);
  427. __nvme_end_req(req);
  428. }
  429. EXPORT_SYMBOL_GPL(nvme_complete_batch_req);
  430. /*
  431. * Called to unwind from ->queue_rq on a failed command submission so that the
  432. * multipathing code gets called to potentially failover to another path.
  433. * The caller needs to unwind all transport specific resource allocations and
  434. * must return propagate the return value.
  435. */
  436. blk_status_t nvme_host_path_error(struct request *req)
  437. {
  438. nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
  439. blk_mq_set_request_complete(req);
  440. nvme_complete_rq(req);
  441. return BLK_STS_OK;
  442. }
  443. EXPORT_SYMBOL_GPL(nvme_host_path_error);
  444. bool nvme_cancel_request(struct request *req, void *data)
  445. {
  446. dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
  447. "Cancelling I/O %d", req->tag);
  448. /* don't abort one completed or idle request */
  449. if (blk_mq_rq_state(req) != MQ_RQ_IN_FLIGHT)
  450. return true;
  451. nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
  452. nvme_req(req)->flags |= NVME_REQ_CANCELLED;
  453. blk_mq_complete_request(req);
  454. return true;
  455. }
  456. EXPORT_SYMBOL_GPL(nvme_cancel_request);
  457. void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
  458. {
  459. if (ctrl->tagset) {
  460. blk_mq_tagset_busy_iter(ctrl->tagset,
  461. nvme_cancel_request, ctrl);
  462. blk_mq_tagset_wait_completed_request(ctrl->tagset);
  463. }
  464. }
  465. EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
  466. void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
  467. {
  468. if (ctrl->admin_tagset) {
  469. blk_mq_tagset_busy_iter(ctrl->admin_tagset,
  470. nvme_cancel_request, ctrl);
  471. blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
  472. }
  473. }
  474. EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
  475. bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
  476. enum nvme_ctrl_state new_state)
  477. {
  478. enum nvme_ctrl_state old_state;
  479. unsigned long flags;
  480. bool changed = false;
  481. spin_lock_irqsave(&ctrl->lock, flags);
  482. old_state = nvme_ctrl_state(ctrl);
  483. switch (new_state) {
  484. case NVME_CTRL_LIVE:
  485. switch (old_state) {
  486. case NVME_CTRL_CONNECTING:
  487. changed = true;
  488. fallthrough;
  489. default:
  490. break;
  491. }
  492. break;
  493. case NVME_CTRL_RESETTING:
  494. switch (old_state) {
  495. case NVME_CTRL_NEW:
  496. case NVME_CTRL_LIVE:
  497. changed = true;
  498. fallthrough;
  499. default:
  500. break;
  501. }
  502. break;
  503. case NVME_CTRL_CONNECTING:
  504. switch (old_state) {
  505. case NVME_CTRL_NEW:
  506. case NVME_CTRL_RESETTING:
  507. changed = true;
  508. fallthrough;
  509. default:
  510. break;
  511. }
  512. break;
  513. case NVME_CTRL_DELETING:
  514. switch (old_state) {
  515. case NVME_CTRL_LIVE:
  516. case NVME_CTRL_RESETTING:
  517. case NVME_CTRL_CONNECTING:
  518. changed = true;
  519. fallthrough;
  520. default:
  521. break;
  522. }
  523. break;
  524. case NVME_CTRL_DELETING_NOIO:
  525. switch (old_state) {
  526. case NVME_CTRL_DELETING:
  527. case NVME_CTRL_DEAD:
  528. changed = true;
  529. fallthrough;
  530. default:
  531. break;
  532. }
  533. break;
  534. case NVME_CTRL_DEAD:
  535. switch (old_state) {
  536. case NVME_CTRL_DELETING:
  537. changed = true;
  538. fallthrough;
  539. default:
  540. break;
  541. }
  542. break;
  543. default:
  544. break;
  545. }
  546. if (changed) {
  547. WRITE_ONCE(ctrl->state, new_state);
  548. wake_up_all(&ctrl->state_wq);
  549. }
  550. spin_unlock_irqrestore(&ctrl->lock, flags);
  551. if (!changed)
  552. return false;
  553. if (new_state == NVME_CTRL_LIVE) {
  554. if (old_state == NVME_CTRL_CONNECTING)
  555. nvme_stop_failfast_work(ctrl);
  556. nvme_kick_requeue_lists(ctrl);
  557. } else if (new_state == NVME_CTRL_CONNECTING &&
  558. old_state == NVME_CTRL_RESETTING) {
  559. nvme_start_failfast_work(ctrl);
  560. }
  561. return changed;
  562. }
  563. EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
  564. /*
  565. * Waits for the controller state to be resetting, or returns false if it is
  566. * not possible to ever transition to that state.
  567. */
  568. bool nvme_wait_reset(struct nvme_ctrl *ctrl)
  569. {
  570. wait_event(ctrl->state_wq,
  571. nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
  572. nvme_state_terminal(ctrl));
  573. return nvme_ctrl_state(ctrl) == NVME_CTRL_RESETTING;
  574. }
  575. EXPORT_SYMBOL_GPL(nvme_wait_reset);
  576. static void nvme_free_ns_head(struct kref *ref)
  577. {
  578. struct nvme_ns_head *head =
  579. container_of(ref, struct nvme_ns_head, ref);
  580. nvme_mpath_remove_disk(head);
  581. ida_free(&head->subsys->ns_ida, head->instance);
  582. cleanup_srcu_struct(&head->srcu);
  583. nvme_put_subsystem(head->subsys);
  584. kfree(head);
  585. }
  586. bool nvme_tryget_ns_head(struct nvme_ns_head *head)
  587. {
  588. return kref_get_unless_zero(&head->ref);
  589. }
  590. void nvme_put_ns_head(struct nvme_ns_head *head)
  591. {
  592. kref_put(&head->ref, nvme_free_ns_head);
  593. }
  594. static void nvme_free_ns(struct kref *kref)
  595. {
  596. struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
  597. put_disk(ns->disk);
  598. nvme_put_ns_head(ns->head);
  599. nvme_put_ctrl(ns->ctrl);
  600. kfree(ns);
  601. }
  602. bool nvme_get_ns(struct nvme_ns *ns)
  603. {
  604. return kref_get_unless_zero(&ns->kref);
  605. }
  606. void nvme_put_ns(struct nvme_ns *ns)
  607. {
  608. kref_put(&ns->kref, nvme_free_ns);
  609. }
  610. EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
  611. static inline void nvme_clear_nvme_request(struct request *req)
  612. {
  613. nvme_req(req)->status = 0;
  614. nvme_req(req)->retries = 0;
  615. nvme_req(req)->flags = 0;
  616. req->rq_flags |= RQF_DONTPREP;
  617. }
  618. /* initialize a passthrough request */
  619. void nvme_init_request(struct request *req, struct nvme_command *cmd)
  620. {
  621. struct nvme_request *nr = nvme_req(req);
  622. bool logging_enabled;
  623. if (req->q->queuedata) {
  624. struct nvme_ns *ns = req->q->disk->private_data;
  625. logging_enabled = ns->head->passthru_err_log_enabled;
  626. req->timeout = NVME_IO_TIMEOUT;
  627. } else { /* no queuedata implies admin queue */
  628. logging_enabled = nr->ctrl->passthru_err_log_enabled;
  629. req->timeout = NVME_ADMIN_TIMEOUT;
  630. }
  631. if (!logging_enabled)
  632. req->rq_flags |= RQF_QUIET;
  633. /* passthru commands should let the driver set the SGL flags */
  634. cmd->common.flags &= ~NVME_CMD_SGL_ALL;
  635. req->cmd_flags |= REQ_FAILFAST_DRIVER;
  636. if (req->mq_hctx->type == HCTX_TYPE_POLL)
  637. req->cmd_flags |= REQ_POLLED;
  638. nvme_clear_nvme_request(req);
  639. memcpy(nr->cmd, cmd, sizeof(*cmd));
  640. }
  641. EXPORT_SYMBOL_GPL(nvme_init_request);
  642. /*
  643. * For something we're not in a state to send to the device the default action
  644. * is to busy it and retry it after the controller state is recovered. However,
  645. * if the controller is deleting or if anything is marked for failfast or
  646. * nvme multipath it is immediately failed.
  647. *
  648. * Note: commands used to initialize the controller will be marked for failfast.
  649. * Note: nvme cli/ioctl commands are marked for failfast.
  650. */
  651. blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl,
  652. struct request *rq)
  653. {
  654. enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
  655. if (state != NVME_CTRL_DELETING_NOIO &&
  656. state != NVME_CTRL_DELETING &&
  657. state != NVME_CTRL_DEAD &&
  658. !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) &&
  659. !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
  660. return BLK_STS_RESOURCE;
  661. if (!(rq->rq_flags & RQF_DONTPREP))
  662. nvme_clear_nvme_request(rq);
  663. return nvme_host_path_error(rq);
  664. }
  665. EXPORT_SYMBOL_GPL(nvme_fail_nonready_command);
  666. bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
  667. bool queue_live, enum nvme_ctrl_state state)
  668. {
  669. struct nvme_request *req = nvme_req(rq);
  670. /*
  671. * currently we have a problem sending passthru commands
  672. * on the admin_q if the controller is not LIVE because we can't
  673. * make sure that they are going out after the admin connect,
  674. * controller enable and/or other commands in the initialization
  675. * sequence. until the controller will be LIVE, fail with
  676. * BLK_STS_RESOURCE so that they will be rescheduled.
  677. */
  678. if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD))
  679. return false;
  680. if (ctrl->ops->flags & NVME_F_FABRICS) {
  681. /*
  682. * Only allow commands on a live queue, except for the connect
  683. * command, which is require to set the queue live in the
  684. * appropinquate states.
  685. */
  686. switch (state) {
  687. case NVME_CTRL_CONNECTING:
  688. if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) &&
  689. (req->cmd->fabrics.fctype == nvme_fabrics_type_connect ||
  690. req->cmd->fabrics.fctype == nvme_fabrics_type_auth_send ||
  691. req->cmd->fabrics.fctype == nvme_fabrics_type_auth_receive))
  692. return true;
  693. break;
  694. default:
  695. break;
  696. case NVME_CTRL_DEAD:
  697. return false;
  698. }
  699. }
  700. return queue_live;
  701. }
  702. EXPORT_SYMBOL_GPL(__nvme_check_ready);
  703. static inline void nvme_setup_flush(struct nvme_ns *ns,
  704. struct nvme_command *cmnd)
  705. {
  706. memset(cmnd, 0, sizeof(*cmnd));
  707. cmnd->common.opcode = nvme_cmd_flush;
  708. cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
  709. }
  710. static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
  711. struct nvme_command *cmnd)
  712. {
  713. unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
  714. struct nvme_dsm_range *range;
  715. struct bio *bio;
  716. /*
  717. * Some devices do not consider the DSM 'Number of Ranges' field when
  718. * determining how much data to DMA. Always allocate memory for maximum
  719. * number of segments to prevent device reading beyond end of buffer.
  720. */
  721. static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
  722. range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
  723. if (!range) {
  724. /*
  725. * If we fail allocation our range, fallback to the controller
  726. * discard page. If that's also busy, it's safe to return
  727. * busy, as we know we can make progress once that's freed.
  728. */
  729. if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
  730. return BLK_STS_RESOURCE;
  731. range = page_address(ns->ctrl->discard_page);
  732. }
  733. if (queue_max_discard_segments(req->q) == 1) {
  734. u64 slba = nvme_sect_to_lba(ns->head, blk_rq_pos(req));
  735. u32 nlb = blk_rq_sectors(req) >> (ns->head->lba_shift - 9);
  736. range[0].cattr = cpu_to_le32(0);
  737. range[0].nlb = cpu_to_le32(nlb);
  738. range[0].slba = cpu_to_le64(slba);
  739. n = 1;
  740. } else {
  741. __rq_for_each_bio(bio, req) {
  742. u64 slba = nvme_sect_to_lba(ns->head,
  743. bio->bi_iter.bi_sector);
  744. u32 nlb = bio->bi_iter.bi_size >> ns->head->lba_shift;
  745. if (n < segments) {
  746. range[n].cattr = cpu_to_le32(0);
  747. range[n].nlb = cpu_to_le32(nlb);
  748. range[n].slba = cpu_to_le64(slba);
  749. }
  750. n++;
  751. }
  752. }
  753. if (WARN_ON_ONCE(n != segments)) {
  754. if (virt_to_page(range) == ns->ctrl->discard_page)
  755. clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
  756. else
  757. kfree(range);
  758. return BLK_STS_IOERR;
  759. }
  760. memset(cmnd, 0, sizeof(*cmnd));
  761. cmnd->dsm.opcode = nvme_cmd_dsm;
  762. cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
  763. cmnd->dsm.nr = cpu_to_le32(segments - 1);
  764. cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
  765. bvec_set_virt(&req->special_vec, range, alloc_size);
  766. req->rq_flags |= RQF_SPECIAL_PAYLOAD;
  767. return BLK_STS_OK;
  768. }
  769. static void nvme_set_ref_tag(struct nvme_ns *ns, struct nvme_command *cmnd,
  770. struct request *req)
  771. {
  772. u32 upper, lower;
  773. u64 ref48;
  774. /* only type1 and type 2 PI formats have a reftag */
  775. switch (ns->head->pi_type) {
  776. case NVME_NS_DPS_PI_TYPE1:
  777. case NVME_NS_DPS_PI_TYPE2:
  778. break;
  779. default:
  780. return;
  781. }
  782. /* both rw and write zeroes share the same reftag format */
  783. switch (ns->head->guard_type) {
  784. case NVME_NVM_NS_16B_GUARD:
  785. cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
  786. break;
  787. case NVME_NVM_NS_64B_GUARD:
  788. ref48 = ext_pi_ref_tag(req);
  789. lower = lower_32_bits(ref48);
  790. upper = upper_32_bits(ref48);
  791. cmnd->rw.reftag = cpu_to_le32(lower);
  792. cmnd->rw.cdw3 = cpu_to_le32(upper);
  793. break;
  794. default:
  795. break;
  796. }
  797. }
  798. static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
  799. struct request *req, struct nvme_command *cmnd)
  800. {
  801. memset(cmnd, 0, sizeof(*cmnd));
  802. if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
  803. return nvme_setup_discard(ns, req, cmnd);
  804. cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
  805. cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
  806. cmnd->write_zeroes.slba =
  807. cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req)));
  808. cmnd->write_zeroes.length =
  809. cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1);
  810. if (!(req->cmd_flags & REQ_NOUNMAP) &&
  811. (ns->head->features & NVME_NS_DEAC))
  812. cmnd->write_zeroes.control |= cpu_to_le16(NVME_WZ_DEAC);
  813. if (nvme_ns_has_pi(ns->head)) {
  814. cmnd->write_zeroes.control |= cpu_to_le16(NVME_RW_PRINFO_PRACT);
  815. nvme_set_ref_tag(ns, cmnd, req);
  816. }
  817. return BLK_STS_OK;
  818. }
  819. /*
  820. * NVMe does not support a dedicated command to issue an atomic write. A write
  821. * which does adhere to the device atomic limits will silently be executed
  822. * non-atomically. The request issuer should ensure that the write is within
  823. * the queue atomic writes limits, but just validate this in case it is not.
  824. */
  825. static bool nvme_valid_atomic_write(struct request *req)
  826. {
  827. struct request_queue *q = req->q;
  828. u32 boundary_bytes = queue_atomic_write_boundary_bytes(q);
  829. if (blk_rq_bytes(req) > queue_atomic_write_unit_max_bytes(q))
  830. return false;
  831. if (boundary_bytes) {
  832. u64 mask = boundary_bytes - 1, imask = ~mask;
  833. u64 start = blk_rq_pos(req) << SECTOR_SHIFT;
  834. u64 end = start + blk_rq_bytes(req) - 1;
  835. /* If greater then must be crossing a boundary */
  836. if (blk_rq_bytes(req) > boundary_bytes)
  837. return false;
  838. if ((start & imask) != (end & imask))
  839. return false;
  840. }
  841. return true;
  842. }
  843. static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
  844. struct request *req, struct nvme_command *cmnd,
  845. enum nvme_opcode op)
  846. {
  847. u16 control = 0;
  848. u32 dsmgmt = 0;
  849. if (req->cmd_flags & REQ_FUA)
  850. control |= NVME_RW_FUA;
  851. if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
  852. control |= NVME_RW_LR;
  853. if (req->cmd_flags & REQ_RAHEAD)
  854. dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
  855. if (req->cmd_flags & REQ_ATOMIC && !nvme_valid_atomic_write(req))
  856. return BLK_STS_INVAL;
  857. cmnd->rw.opcode = op;
  858. cmnd->rw.flags = 0;
  859. cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
  860. cmnd->rw.cdw2 = 0;
  861. cmnd->rw.cdw3 = 0;
  862. cmnd->rw.metadata = 0;
  863. cmnd->rw.slba =
  864. cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req)));
  865. cmnd->rw.length =
  866. cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1);
  867. cmnd->rw.reftag = 0;
  868. cmnd->rw.lbat = 0;
  869. cmnd->rw.lbatm = 0;
  870. if (ns->head->ms) {
  871. /*
  872. * If formated with metadata, the block layer always provides a
  873. * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
  874. * we enable the PRACT bit for protection information or set the
  875. * namespace capacity to zero to prevent any I/O.
  876. */
  877. if (!blk_integrity_rq(req)) {
  878. if (WARN_ON_ONCE(!nvme_ns_has_pi(ns->head)))
  879. return BLK_STS_NOTSUPP;
  880. control |= NVME_RW_PRINFO_PRACT;
  881. nvme_set_ref_tag(ns, cmnd, req);
  882. }
  883. switch (ns->head->pi_type) {
  884. case NVME_NS_DPS_PI_TYPE3:
  885. control |= NVME_RW_PRINFO_PRCHK_GUARD;
  886. break;
  887. case NVME_NS_DPS_PI_TYPE1:
  888. case NVME_NS_DPS_PI_TYPE2:
  889. control |= NVME_RW_PRINFO_PRCHK_GUARD |
  890. NVME_RW_PRINFO_PRCHK_REF;
  891. if (op == nvme_cmd_zone_append)
  892. control |= NVME_RW_APPEND_PIREMAP;
  893. nvme_set_ref_tag(ns, cmnd, req);
  894. break;
  895. }
  896. }
  897. cmnd->rw.control = cpu_to_le16(control);
  898. cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
  899. return 0;
  900. }
  901. void nvme_cleanup_cmd(struct request *req)
  902. {
  903. if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
  904. struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
  905. if (req->special_vec.bv_page == ctrl->discard_page)
  906. clear_bit_unlock(0, &ctrl->discard_page_busy);
  907. else
  908. kfree(bvec_virt(&req->special_vec));
  909. req->rq_flags &= ~RQF_SPECIAL_PAYLOAD;
  910. }
  911. }
  912. EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
  913. blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
  914. {
  915. struct nvme_command *cmd = nvme_req(req)->cmd;
  916. blk_status_t ret = BLK_STS_OK;
  917. if (!(req->rq_flags & RQF_DONTPREP))
  918. nvme_clear_nvme_request(req);
  919. switch (req_op(req)) {
  920. case REQ_OP_DRV_IN:
  921. case REQ_OP_DRV_OUT:
  922. /* these are setup prior to execution in nvme_init_request() */
  923. break;
  924. case REQ_OP_FLUSH:
  925. nvme_setup_flush(ns, cmd);
  926. break;
  927. case REQ_OP_ZONE_RESET_ALL:
  928. case REQ_OP_ZONE_RESET:
  929. ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
  930. break;
  931. case REQ_OP_ZONE_OPEN:
  932. ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
  933. break;
  934. case REQ_OP_ZONE_CLOSE:
  935. ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
  936. break;
  937. case REQ_OP_ZONE_FINISH:
  938. ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
  939. break;
  940. case REQ_OP_WRITE_ZEROES:
  941. ret = nvme_setup_write_zeroes(ns, req, cmd);
  942. break;
  943. case REQ_OP_DISCARD:
  944. ret = nvme_setup_discard(ns, req, cmd);
  945. break;
  946. case REQ_OP_READ:
  947. ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
  948. break;
  949. case REQ_OP_WRITE:
  950. ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
  951. break;
  952. case REQ_OP_ZONE_APPEND:
  953. ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
  954. break;
  955. default:
  956. WARN_ON_ONCE(1);
  957. return BLK_STS_IOERR;
  958. }
  959. cmd->common.command_id = nvme_cid(req);
  960. trace_nvme_setup_cmd(req, cmd);
  961. return ret;
  962. }
  963. EXPORT_SYMBOL_GPL(nvme_setup_cmd);
  964. /*
  965. * Return values:
  966. * 0: success
  967. * >0: nvme controller's cqe status response
  968. * <0: kernel error in lieu of controller response
  969. */
  970. int nvme_execute_rq(struct request *rq, bool at_head)
  971. {
  972. blk_status_t status;
  973. status = blk_execute_rq(rq, at_head);
  974. if (nvme_req(rq)->flags & NVME_REQ_CANCELLED)
  975. return -EINTR;
  976. if (nvme_req(rq)->status)
  977. return nvme_req(rq)->status;
  978. return blk_status_to_errno(status);
  979. }
  980. EXPORT_SYMBOL_NS_GPL(nvme_execute_rq, NVME_TARGET_PASSTHRU);
  981. /*
  982. * Returns 0 on success. If the result is negative, it's a Linux error code;
  983. * if the result is positive, it's an NVM Express status code
  984. */
  985. int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
  986. union nvme_result *result, void *buffer, unsigned bufflen,
  987. int qid, nvme_submit_flags_t flags)
  988. {
  989. struct request *req;
  990. int ret;
  991. blk_mq_req_flags_t blk_flags = 0;
  992. if (flags & NVME_SUBMIT_NOWAIT)
  993. blk_flags |= BLK_MQ_REQ_NOWAIT;
  994. if (flags & NVME_SUBMIT_RESERVED)
  995. blk_flags |= BLK_MQ_REQ_RESERVED;
  996. if (qid == NVME_QID_ANY)
  997. req = blk_mq_alloc_request(q, nvme_req_op(cmd), blk_flags);
  998. else
  999. req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), blk_flags,
  1000. qid - 1);
  1001. if (IS_ERR(req))
  1002. return PTR_ERR(req);
  1003. nvme_init_request(req, cmd);
  1004. if (flags & NVME_SUBMIT_RETRY)
  1005. req->cmd_flags &= ~REQ_FAILFAST_DRIVER;
  1006. if (buffer && bufflen) {
  1007. ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
  1008. if (ret)
  1009. goto out;
  1010. }
  1011. ret = nvme_execute_rq(req, flags & NVME_SUBMIT_AT_HEAD);
  1012. if (result && ret >= 0)
  1013. *result = nvme_req(req)->result;
  1014. out:
  1015. blk_mq_free_request(req);
  1016. return ret;
  1017. }
  1018. EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
  1019. int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
  1020. void *buffer, unsigned bufflen)
  1021. {
  1022. return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen,
  1023. NVME_QID_ANY, 0);
  1024. }
  1025. EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
  1026. u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
  1027. {
  1028. u32 effects = 0;
  1029. if (ns) {
  1030. effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
  1031. if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
  1032. dev_warn_once(ctrl->device,
  1033. "IO command:%02x has unusual effects:%08x\n",
  1034. opcode, effects);
  1035. /*
  1036. * NVME_CMD_EFFECTS_CSE_MASK causes a freeze all I/O queues,
  1037. * which would deadlock when done on an I/O command. Note that
  1038. * We already warn about an unusual effect above.
  1039. */
  1040. effects &= ~NVME_CMD_EFFECTS_CSE_MASK;
  1041. } else {
  1042. effects = le32_to_cpu(ctrl->effects->acs[opcode]);
  1043. /* Ignore execution restrictions if any relaxation bits are set */
  1044. if (effects & NVME_CMD_EFFECTS_CSER_MASK)
  1045. effects &= ~NVME_CMD_EFFECTS_CSE_MASK;
  1046. }
  1047. return effects;
  1048. }
  1049. EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
  1050. u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
  1051. {
  1052. u32 effects = nvme_command_effects(ctrl, ns, opcode);
  1053. /*
  1054. * For simplicity, IO to all namespaces is quiesced even if the command
  1055. * effects say only one namespace is affected.
  1056. */
  1057. if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
  1058. mutex_lock(&ctrl->scan_lock);
  1059. mutex_lock(&ctrl->subsys->lock);
  1060. nvme_mpath_start_freeze(ctrl->subsys);
  1061. nvme_mpath_wait_freeze(ctrl->subsys);
  1062. nvme_start_freeze(ctrl);
  1063. nvme_wait_freeze(ctrl);
  1064. }
  1065. return effects;
  1066. }
  1067. EXPORT_SYMBOL_NS_GPL(nvme_passthru_start, NVME_TARGET_PASSTHRU);
  1068. void nvme_passthru_end(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u32 effects,
  1069. struct nvme_command *cmd, int status)
  1070. {
  1071. if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
  1072. nvme_unfreeze(ctrl);
  1073. nvme_mpath_unfreeze(ctrl->subsys);
  1074. mutex_unlock(&ctrl->subsys->lock);
  1075. mutex_unlock(&ctrl->scan_lock);
  1076. }
  1077. if (effects & NVME_CMD_EFFECTS_CCC) {
  1078. if (!test_and_set_bit(NVME_CTRL_DIRTY_CAPABILITY,
  1079. &ctrl->flags)) {
  1080. dev_info(ctrl->device,
  1081. "controller capabilities changed, reset may be required to take effect.\n");
  1082. }
  1083. }
  1084. if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
  1085. nvme_queue_scan(ctrl);
  1086. flush_work(&ctrl->scan_work);
  1087. }
  1088. if (ns)
  1089. return;
  1090. switch (cmd->common.opcode) {
  1091. case nvme_admin_set_features:
  1092. switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) {
  1093. case NVME_FEAT_KATO:
  1094. /*
  1095. * Keep alive commands interval on the host should be
  1096. * updated when KATO is modified by Set Features
  1097. * commands.
  1098. */
  1099. if (!status)
  1100. nvme_update_keep_alive(ctrl, cmd);
  1101. break;
  1102. default:
  1103. break;
  1104. }
  1105. break;
  1106. default:
  1107. break;
  1108. }
  1109. }
  1110. EXPORT_SYMBOL_NS_GPL(nvme_passthru_end, NVME_TARGET_PASSTHRU);
  1111. /*
  1112. * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
  1113. *
  1114. * The host should send Keep Alive commands at half of the Keep Alive Timeout
  1115. * accounting for transport roundtrip times [..].
  1116. */
  1117. static unsigned long nvme_keep_alive_work_period(struct nvme_ctrl *ctrl)
  1118. {
  1119. unsigned long delay = ctrl->kato * HZ / 2;
  1120. /*
  1121. * When using Traffic Based Keep Alive, we need to run
  1122. * nvme_keep_alive_work at twice the normal frequency, as one
  1123. * command completion can postpone sending a keep alive command
  1124. * by up to twice the delay between runs.
  1125. */
  1126. if (ctrl->ctratt & NVME_CTRL_ATTR_TBKAS)
  1127. delay /= 2;
  1128. return delay;
  1129. }
  1130. static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
  1131. {
  1132. unsigned long now = jiffies;
  1133. unsigned long delay = nvme_keep_alive_work_period(ctrl);
  1134. unsigned long ka_next_check_tm = ctrl->ka_last_check_time + delay;
  1135. if (time_after(now, ka_next_check_tm))
  1136. delay = 0;
  1137. else
  1138. delay = ka_next_check_tm - now;
  1139. queue_delayed_work(nvme_wq, &ctrl->ka_work, delay);
  1140. }
  1141. static enum rq_end_io_ret nvme_keep_alive_end_io(struct request *rq,
  1142. blk_status_t status)
  1143. {
  1144. struct nvme_ctrl *ctrl = rq->end_io_data;
  1145. unsigned long rtt = jiffies - (rq->deadline - rq->timeout);
  1146. unsigned long delay = nvme_keep_alive_work_period(ctrl);
  1147. enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
  1148. /*
  1149. * Subtract off the keepalive RTT so nvme_keep_alive_work runs
  1150. * at the desired frequency.
  1151. */
  1152. if (rtt <= delay) {
  1153. delay -= rtt;
  1154. } else {
  1155. dev_warn(ctrl->device, "long keepalive RTT (%u ms)\n",
  1156. jiffies_to_msecs(rtt));
  1157. delay = 0;
  1158. }
  1159. blk_mq_free_request(rq);
  1160. if (status) {
  1161. dev_err(ctrl->device,
  1162. "failed nvme_keep_alive_end_io error=%d\n",
  1163. status);
  1164. return RQ_END_IO_NONE;
  1165. }
  1166. ctrl->ka_last_check_time = jiffies;
  1167. ctrl->comp_seen = false;
  1168. if (state == NVME_CTRL_LIVE || state == NVME_CTRL_CONNECTING)
  1169. queue_delayed_work(nvme_wq, &ctrl->ka_work, delay);
  1170. return RQ_END_IO_NONE;
  1171. }
  1172. static void nvme_keep_alive_work(struct work_struct *work)
  1173. {
  1174. struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
  1175. struct nvme_ctrl, ka_work);
  1176. bool comp_seen = ctrl->comp_seen;
  1177. struct request *rq;
  1178. ctrl->ka_last_check_time = jiffies;
  1179. if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
  1180. dev_dbg(ctrl->device,
  1181. "reschedule traffic based keep-alive timer\n");
  1182. ctrl->comp_seen = false;
  1183. nvme_queue_keep_alive_work(ctrl);
  1184. return;
  1185. }
  1186. rq = blk_mq_alloc_request(ctrl->admin_q, nvme_req_op(&ctrl->ka_cmd),
  1187. BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
  1188. if (IS_ERR(rq)) {
  1189. /* allocation failure, reset the controller */
  1190. dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
  1191. nvme_reset_ctrl(ctrl);
  1192. return;
  1193. }
  1194. nvme_init_request(rq, &ctrl->ka_cmd);
  1195. rq->timeout = ctrl->kato * HZ;
  1196. rq->end_io = nvme_keep_alive_end_io;
  1197. rq->end_io_data = ctrl;
  1198. blk_execute_rq_nowait(rq, false);
  1199. }
  1200. static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
  1201. {
  1202. if (unlikely(ctrl->kato == 0))
  1203. return;
  1204. nvme_queue_keep_alive_work(ctrl);
  1205. }
  1206. void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
  1207. {
  1208. if (unlikely(ctrl->kato == 0))
  1209. return;
  1210. cancel_delayed_work_sync(&ctrl->ka_work);
  1211. }
  1212. EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
  1213. static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
  1214. struct nvme_command *cmd)
  1215. {
  1216. unsigned int new_kato =
  1217. DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000);
  1218. dev_info(ctrl->device,
  1219. "keep alive interval updated from %u ms to %u ms\n",
  1220. ctrl->kato * 1000 / 2, new_kato * 1000 / 2);
  1221. nvme_stop_keep_alive(ctrl);
  1222. ctrl->kato = new_kato;
  1223. nvme_start_keep_alive(ctrl);
  1224. }
  1225. static bool nvme_id_cns_ok(struct nvme_ctrl *ctrl, u8 cns)
  1226. {
  1227. /*
  1228. * The CNS field occupies a full byte starting with NVMe 1.2
  1229. */
  1230. if (ctrl->vs >= NVME_VS(1, 2, 0))
  1231. return true;
  1232. /*
  1233. * NVMe 1.1 expanded the CNS value to two bits, which means values
  1234. * larger than that could get truncated and treated as an incorrect
  1235. * value.
  1236. *
  1237. * Qemu implemented 1.0 behavior for controllers claiming 1.1
  1238. * compliance, so they need to be quirked here.
  1239. */
  1240. if (ctrl->vs >= NVME_VS(1, 1, 0) &&
  1241. !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS))
  1242. return cns <= 3;
  1243. /*
  1244. * NVMe 1.0 used a single bit for the CNS value.
  1245. */
  1246. return cns <= 1;
  1247. }
  1248. static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
  1249. {
  1250. struct nvme_command c = { };
  1251. int error;
  1252. /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
  1253. c.identify.opcode = nvme_admin_identify;
  1254. c.identify.cns = NVME_ID_CNS_CTRL;
  1255. *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
  1256. if (!*id)
  1257. return -ENOMEM;
  1258. error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
  1259. sizeof(struct nvme_id_ctrl));
  1260. if (error) {
  1261. kfree(*id);
  1262. *id = NULL;
  1263. }
  1264. return error;
  1265. }
  1266. static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
  1267. struct nvme_ns_id_desc *cur, bool *csi_seen)
  1268. {
  1269. const char *warn_str = "ctrl returned bogus length:";
  1270. void *data = cur;
  1271. switch (cur->nidt) {
  1272. case NVME_NIDT_EUI64:
  1273. if (cur->nidl != NVME_NIDT_EUI64_LEN) {
  1274. dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
  1275. warn_str, cur->nidl);
  1276. return -1;
  1277. }
  1278. if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
  1279. return NVME_NIDT_EUI64_LEN;
  1280. memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
  1281. return NVME_NIDT_EUI64_LEN;
  1282. case NVME_NIDT_NGUID:
  1283. if (cur->nidl != NVME_NIDT_NGUID_LEN) {
  1284. dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
  1285. warn_str, cur->nidl);
  1286. return -1;
  1287. }
  1288. if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
  1289. return NVME_NIDT_NGUID_LEN;
  1290. memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
  1291. return NVME_NIDT_NGUID_LEN;
  1292. case NVME_NIDT_UUID:
  1293. if (cur->nidl != NVME_NIDT_UUID_LEN) {
  1294. dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
  1295. warn_str, cur->nidl);
  1296. return -1;
  1297. }
  1298. if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
  1299. return NVME_NIDT_UUID_LEN;
  1300. uuid_copy(&ids->uuid, data + sizeof(*cur));
  1301. return NVME_NIDT_UUID_LEN;
  1302. case NVME_NIDT_CSI:
  1303. if (cur->nidl != NVME_NIDT_CSI_LEN) {
  1304. dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
  1305. warn_str, cur->nidl);
  1306. return -1;
  1307. }
  1308. memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
  1309. *csi_seen = true;
  1310. return NVME_NIDT_CSI_LEN;
  1311. default:
  1312. /* Skip unknown types */
  1313. return cur->nidl;
  1314. }
  1315. }
  1316. static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl,
  1317. struct nvme_ns_info *info)
  1318. {
  1319. struct nvme_command c = { };
  1320. bool csi_seen = false;
  1321. int status, pos, len;
  1322. void *data;
  1323. if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
  1324. return 0;
  1325. if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
  1326. return 0;
  1327. c.identify.opcode = nvme_admin_identify;
  1328. c.identify.nsid = cpu_to_le32(info->nsid);
  1329. c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
  1330. data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
  1331. if (!data)
  1332. return -ENOMEM;
  1333. status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
  1334. NVME_IDENTIFY_DATA_SIZE);
  1335. if (status) {
  1336. dev_warn(ctrl->device,
  1337. "Identify Descriptors failed (nsid=%u, status=0x%x)\n",
  1338. info->nsid, status);
  1339. goto free_data;
  1340. }
  1341. for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
  1342. struct nvme_ns_id_desc *cur = data + pos;
  1343. if (cur->nidl == 0)
  1344. break;
  1345. len = nvme_process_ns_desc(ctrl, &info->ids, cur, &csi_seen);
  1346. if (len < 0)
  1347. break;
  1348. len += sizeof(*cur);
  1349. }
  1350. if (nvme_multi_css(ctrl) && !csi_seen) {
  1351. dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
  1352. info->nsid);
  1353. status = -EINVAL;
  1354. }
  1355. free_data:
  1356. kfree(data);
  1357. return status;
  1358. }
  1359. int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
  1360. struct nvme_id_ns **id)
  1361. {
  1362. struct nvme_command c = { };
  1363. int error;
  1364. /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
  1365. c.identify.opcode = nvme_admin_identify;
  1366. c.identify.nsid = cpu_to_le32(nsid);
  1367. c.identify.cns = NVME_ID_CNS_NS;
  1368. *id = kmalloc(sizeof(**id), GFP_KERNEL);
  1369. if (!*id)
  1370. return -ENOMEM;
  1371. error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
  1372. if (error) {
  1373. dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
  1374. kfree(*id);
  1375. *id = NULL;
  1376. }
  1377. return error;
  1378. }
  1379. static int nvme_ns_info_from_identify(struct nvme_ctrl *ctrl,
  1380. struct nvme_ns_info *info)
  1381. {
  1382. struct nvme_ns_ids *ids = &info->ids;
  1383. struct nvme_id_ns *id;
  1384. int ret;
  1385. ret = nvme_identify_ns(ctrl, info->nsid, &id);
  1386. if (ret)
  1387. return ret;
  1388. if (id->ncap == 0) {
  1389. /* namespace not allocated or attached */
  1390. info->is_removed = true;
  1391. ret = -ENODEV;
  1392. goto error;
  1393. }
  1394. info->anagrpid = id->anagrpid;
  1395. info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
  1396. info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
  1397. info->is_ready = true;
  1398. if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) {
  1399. dev_info(ctrl->device,
  1400. "Ignoring bogus Namespace Identifiers\n");
  1401. } else {
  1402. if (ctrl->vs >= NVME_VS(1, 1, 0) &&
  1403. !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
  1404. memcpy(ids->eui64, id->eui64, sizeof(ids->eui64));
  1405. if (ctrl->vs >= NVME_VS(1, 2, 0) &&
  1406. !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
  1407. memcpy(ids->nguid, id->nguid, sizeof(ids->nguid));
  1408. }
  1409. error:
  1410. kfree(id);
  1411. return ret;
  1412. }
  1413. static int nvme_ns_info_from_id_cs_indep(struct nvme_ctrl *ctrl,
  1414. struct nvme_ns_info *info)
  1415. {
  1416. struct nvme_id_ns_cs_indep *id;
  1417. struct nvme_command c = {
  1418. .identify.opcode = nvme_admin_identify,
  1419. .identify.nsid = cpu_to_le32(info->nsid),
  1420. .identify.cns = NVME_ID_CNS_NS_CS_INDEP,
  1421. };
  1422. int ret;
  1423. id = kmalloc(sizeof(*id), GFP_KERNEL);
  1424. if (!id)
  1425. return -ENOMEM;
  1426. ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
  1427. if (!ret) {
  1428. info->anagrpid = id->anagrpid;
  1429. info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
  1430. info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
  1431. info->is_ready = id->nstat & NVME_NSTAT_NRDY;
  1432. }
  1433. kfree(id);
  1434. return ret;
  1435. }
  1436. static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
  1437. unsigned int dword11, void *buffer, size_t buflen, u32 *result)
  1438. {
  1439. union nvme_result res = { 0 };
  1440. struct nvme_command c = { };
  1441. int ret;
  1442. c.features.opcode = op;
  1443. c.features.fid = cpu_to_le32(fid);
  1444. c.features.dword11 = cpu_to_le32(dword11);
  1445. ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
  1446. buffer, buflen, NVME_QID_ANY, 0);
  1447. if (ret >= 0 && result)
  1448. *result = le32_to_cpu(res.u32);
  1449. return ret;
  1450. }
  1451. int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
  1452. unsigned int dword11, void *buffer, size_t buflen,
  1453. u32 *result)
  1454. {
  1455. return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
  1456. buflen, result);
  1457. }
  1458. EXPORT_SYMBOL_GPL(nvme_set_features);
  1459. int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
  1460. unsigned int dword11, void *buffer, size_t buflen,
  1461. u32 *result)
  1462. {
  1463. return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
  1464. buflen, result);
  1465. }
  1466. EXPORT_SYMBOL_GPL(nvme_get_features);
  1467. int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
  1468. {
  1469. u32 q_count = (*count - 1) | ((*count - 1) << 16);
  1470. u32 result;
  1471. int status, nr_io_queues;
  1472. status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
  1473. &result);
  1474. /*
  1475. * It's either a kernel error or the host observed a connection
  1476. * lost. In either case it's not possible communicate with the
  1477. * controller and thus enter the error code path.
  1478. */
  1479. if (status < 0 || status == NVME_SC_HOST_PATH_ERROR)
  1480. return status;
  1481. /*
  1482. * Degraded controllers might return an error when setting the queue
  1483. * count. We still want to be able to bring them online and offer
  1484. * access to the admin queue, as that might be only way to fix them up.
  1485. */
  1486. if (status > 0) {
  1487. dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
  1488. *count = 0;
  1489. } else {
  1490. nr_io_queues = min(result & 0xffff, result >> 16) + 1;
  1491. *count = min(*count, nr_io_queues);
  1492. }
  1493. return 0;
  1494. }
  1495. EXPORT_SYMBOL_GPL(nvme_set_queue_count);
  1496. #define NVME_AEN_SUPPORTED \
  1497. (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
  1498. NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
  1499. static void nvme_enable_aen(struct nvme_ctrl *ctrl)
  1500. {
  1501. u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
  1502. int status;
  1503. if (!supported_aens)
  1504. return;
  1505. status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
  1506. NULL, 0, &result);
  1507. if (status)
  1508. dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
  1509. supported_aens);
  1510. queue_work(nvme_wq, &ctrl->async_event_work);
  1511. }
  1512. static int nvme_ns_open(struct nvme_ns *ns)
  1513. {
  1514. /* should never be called due to GENHD_FL_HIDDEN */
  1515. if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
  1516. goto fail;
  1517. if (!nvme_get_ns(ns))
  1518. goto fail;
  1519. if (!try_module_get(ns->ctrl->ops->module))
  1520. goto fail_put_ns;
  1521. return 0;
  1522. fail_put_ns:
  1523. nvme_put_ns(ns);
  1524. fail:
  1525. return -ENXIO;
  1526. }
  1527. static void nvme_ns_release(struct nvme_ns *ns)
  1528. {
  1529. module_put(ns->ctrl->ops->module);
  1530. nvme_put_ns(ns);
  1531. }
  1532. static int nvme_open(struct gendisk *disk, blk_mode_t mode)
  1533. {
  1534. return nvme_ns_open(disk->private_data);
  1535. }
  1536. static void nvme_release(struct gendisk *disk)
  1537. {
  1538. nvme_ns_release(disk->private_data);
  1539. }
  1540. int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
  1541. {
  1542. /* some standard values */
  1543. geo->heads = 1 << 6;
  1544. geo->sectors = 1 << 5;
  1545. geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
  1546. return 0;
  1547. }
  1548. static bool nvme_init_integrity(struct nvme_ns_head *head,
  1549. struct queue_limits *lim, struct nvme_ns_info *info)
  1550. {
  1551. struct blk_integrity *bi = &lim->integrity;
  1552. memset(bi, 0, sizeof(*bi));
  1553. if (!head->ms)
  1554. return true;
  1555. /*
  1556. * PI can always be supported as we can ask the controller to simply
  1557. * insert/strip it, which is not possible for other kinds of metadata.
  1558. */
  1559. if (!IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) ||
  1560. !(head->features & NVME_NS_METADATA_SUPPORTED))
  1561. return nvme_ns_has_pi(head);
  1562. switch (head->pi_type) {
  1563. case NVME_NS_DPS_PI_TYPE3:
  1564. switch (head->guard_type) {
  1565. case NVME_NVM_NS_16B_GUARD:
  1566. bi->csum_type = BLK_INTEGRITY_CSUM_CRC;
  1567. bi->tag_size = sizeof(u16) + sizeof(u32);
  1568. bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
  1569. break;
  1570. case NVME_NVM_NS_64B_GUARD:
  1571. bi->csum_type = BLK_INTEGRITY_CSUM_CRC64;
  1572. bi->tag_size = sizeof(u16) + 6;
  1573. bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
  1574. break;
  1575. default:
  1576. break;
  1577. }
  1578. break;
  1579. case NVME_NS_DPS_PI_TYPE1:
  1580. case NVME_NS_DPS_PI_TYPE2:
  1581. switch (head->guard_type) {
  1582. case NVME_NVM_NS_16B_GUARD:
  1583. bi->csum_type = BLK_INTEGRITY_CSUM_CRC;
  1584. bi->tag_size = sizeof(u16);
  1585. bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE |
  1586. BLK_INTEGRITY_REF_TAG;
  1587. break;
  1588. case NVME_NVM_NS_64B_GUARD:
  1589. bi->csum_type = BLK_INTEGRITY_CSUM_CRC64;
  1590. bi->tag_size = sizeof(u16);
  1591. bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE |
  1592. BLK_INTEGRITY_REF_TAG;
  1593. break;
  1594. default:
  1595. break;
  1596. }
  1597. break;
  1598. default:
  1599. break;
  1600. }
  1601. bi->tuple_size = head->ms;
  1602. bi->pi_offset = info->pi_offset;
  1603. return true;
  1604. }
  1605. static void nvme_config_discard(struct nvme_ns *ns, struct queue_limits *lim)
  1606. {
  1607. struct nvme_ctrl *ctrl = ns->ctrl;
  1608. if (ctrl->dmrsl && ctrl->dmrsl <= nvme_sect_to_lba(ns->head, UINT_MAX))
  1609. lim->max_hw_discard_sectors =
  1610. nvme_lba_to_sect(ns->head, ctrl->dmrsl);
  1611. else if (ctrl->oncs & NVME_CTRL_ONCS_DSM)
  1612. lim->max_hw_discard_sectors = UINT_MAX;
  1613. else
  1614. lim->max_hw_discard_sectors = 0;
  1615. lim->discard_granularity = lim->logical_block_size;
  1616. if (ctrl->dmrl)
  1617. lim->max_discard_segments = ctrl->dmrl;
  1618. else
  1619. lim->max_discard_segments = NVME_DSM_MAX_RANGES;
  1620. }
  1621. static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
  1622. {
  1623. return uuid_equal(&a->uuid, &b->uuid) &&
  1624. memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
  1625. memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
  1626. a->csi == b->csi;
  1627. }
  1628. static int nvme_identify_ns_nvm(struct nvme_ctrl *ctrl, unsigned int nsid,
  1629. struct nvme_id_ns_nvm **nvmp)
  1630. {
  1631. struct nvme_command c = {
  1632. .identify.opcode = nvme_admin_identify,
  1633. .identify.nsid = cpu_to_le32(nsid),
  1634. .identify.cns = NVME_ID_CNS_CS_NS,
  1635. .identify.csi = NVME_CSI_NVM,
  1636. };
  1637. struct nvme_id_ns_nvm *nvm;
  1638. int ret;
  1639. nvm = kzalloc(sizeof(*nvm), GFP_KERNEL);
  1640. if (!nvm)
  1641. return -ENOMEM;
  1642. ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, nvm, sizeof(*nvm));
  1643. if (ret)
  1644. kfree(nvm);
  1645. else
  1646. *nvmp = nvm;
  1647. return ret;
  1648. }
  1649. static void nvme_configure_pi_elbas(struct nvme_ns_head *head,
  1650. struct nvme_id_ns *id, struct nvme_id_ns_nvm *nvm)
  1651. {
  1652. u32 elbaf = le32_to_cpu(nvm->elbaf[nvme_lbaf_index(id->flbas)]);
  1653. u8 guard_type;
  1654. /* no support for storage tag formats right now */
  1655. if (nvme_elbaf_sts(elbaf))
  1656. return;
  1657. guard_type = nvme_elbaf_guard_type(elbaf);
  1658. if ((nvm->pic & NVME_ID_NS_NVM_QPIFS) &&
  1659. guard_type == NVME_NVM_NS_QTYPE_GUARD)
  1660. guard_type = nvme_elbaf_qualified_guard_type(elbaf);
  1661. head->guard_type = guard_type;
  1662. switch (head->guard_type) {
  1663. case NVME_NVM_NS_64B_GUARD:
  1664. head->pi_size = sizeof(struct crc64_pi_tuple);
  1665. break;
  1666. case NVME_NVM_NS_16B_GUARD:
  1667. head->pi_size = sizeof(struct t10_pi_tuple);
  1668. break;
  1669. default:
  1670. break;
  1671. }
  1672. }
  1673. static void nvme_configure_metadata(struct nvme_ctrl *ctrl,
  1674. struct nvme_ns_head *head, struct nvme_id_ns *id,
  1675. struct nvme_id_ns_nvm *nvm, struct nvme_ns_info *info)
  1676. {
  1677. head->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
  1678. head->pi_type = 0;
  1679. head->pi_size = 0;
  1680. head->ms = le16_to_cpu(id->lbaf[nvme_lbaf_index(id->flbas)].ms);
  1681. if (!head->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
  1682. return;
  1683. if (nvm && (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)) {
  1684. nvme_configure_pi_elbas(head, id, nvm);
  1685. } else {
  1686. head->pi_size = sizeof(struct t10_pi_tuple);
  1687. head->guard_type = NVME_NVM_NS_16B_GUARD;
  1688. }
  1689. if (head->pi_size && head->ms >= head->pi_size)
  1690. head->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
  1691. if (!(id->dps & NVME_NS_DPS_PI_FIRST)) {
  1692. if (disable_pi_offsets)
  1693. head->pi_type = 0;
  1694. else
  1695. info->pi_offset = head->ms - head->pi_size;
  1696. }
  1697. if (ctrl->ops->flags & NVME_F_FABRICS) {
  1698. /*
  1699. * The NVMe over Fabrics specification only supports metadata as
  1700. * part of the extended data LBA. We rely on HCA/HBA support to
  1701. * remap the separate metadata buffer from the block layer.
  1702. */
  1703. if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
  1704. return;
  1705. head->features |= NVME_NS_EXT_LBAS;
  1706. /*
  1707. * The current fabrics transport drivers support namespace
  1708. * metadata formats only if nvme_ns_has_pi() returns true.
  1709. * Suppress support for all other formats so the namespace will
  1710. * have a 0 capacity and not be usable through the block stack.
  1711. *
  1712. * Note, this check will need to be modified if any drivers
  1713. * gain the ability to use other metadata formats.
  1714. */
  1715. if (ctrl->max_integrity_segments && nvme_ns_has_pi(head))
  1716. head->features |= NVME_NS_METADATA_SUPPORTED;
  1717. } else {
  1718. /*
  1719. * For PCIe controllers, we can't easily remap the separate
  1720. * metadata buffer from the block layer and thus require a
  1721. * separate metadata buffer for block layer metadata/PI support.
  1722. * We allow extended LBAs for the passthrough interface, though.
  1723. */
  1724. if (id->flbas & NVME_NS_FLBAS_META_EXT)
  1725. head->features |= NVME_NS_EXT_LBAS;
  1726. else
  1727. head->features |= NVME_NS_METADATA_SUPPORTED;
  1728. }
  1729. }
  1730. static void nvme_update_atomic_write_disk_info(struct nvme_ns *ns,
  1731. struct nvme_id_ns *id, struct queue_limits *lim,
  1732. u32 bs, u32 atomic_bs)
  1733. {
  1734. unsigned int boundary = 0;
  1735. if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf) {
  1736. if (le16_to_cpu(id->nabspf))
  1737. boundary = (le16_to_cpu(id->nabspf) + 1) * bs;
  1738. }
  1739. lim->atomic_write_hw_max = atomic_bs;
  1740. lim->atomic_write_hw_boundary = boundary;
  1741. lim->atomic_write_hw_unit_min = bs;
  1742. lim->atomic_write_hw_unit_max = rounddown_pow_of_two(atomic_bs);
  1743. }
  1744. static u32 nvme_max_drv_segments(struct nvme_ctrl *ctrl)
  1745. {
  1746. return ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> SECTOR_SHIFT) + 1;
  1747. }
  1748. static void nvme_set_ctrl_limits(struct nvme_ctrl *ctrl,
  1749. struct queue_limits *lim)
  1750. {
  1751. lim->max_hw_sectors = ctrl->max_hw_sectors;
  1752. lim->max_segments = min_t(u32, USHRT_MAX,
  1753. min_not_zero(nvme_max_drv_segments(ctrl), ctrl->max_segments));
  1754. lim->max_integrity_segments = ctrl->max_integrity_segments;
  1755. lim->virt_boundary_mask = NVME_CTRL_PAGE_SIZE - 1;
  1756. lim->max_segment_size = UINT_MAX;
  1757. lim->dma_alignment = 3;
  1758. }
  1759. static bool nvme_update_disk_info(struct nvme_ns *ns, struct nvme_id_ns *id,
  1760. struct queue_limits *lim)
  1761. {
  1762. struct nvme_ns_head *head = ns->head;
  1763. u32 bs = 1U << head->lba_shift;
  1764. u32 atomic_bs, phys_bs, io_opt = 0;
  1765. bool valid = true;
  1766. /*
  1767. * The block layer can't support LBA sizes larger than the page size
  1768. * or smaller than a sector size yet, so catch this early and don't
  1769. * allow block I/O.
  1770. */
  1771. if (head->lba_shift > PAGE_SHIFT || head->lba_shift < SECTOR_SHIFT) {
  1772. bs = (1 << 9);
  1773. valid = false;
  1774. }
  1775. atomic_bs = phys_bs = bs;
  1776. if (id->nabo == 0) {
  1777. /*
  1778. * Bit 1 indicates whether NAWUPF is defined for this namespace
  1779. * and whether it should be used instead of AWUPF. If NAWUPF ==
  1780. * 0 then AWUPF must be used instead.
  1781. */
  1782. if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
  1783. atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
  1784. else
  1785. atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
  1786. nvme_update_atomic_write_disk_info(ns, id, lim, bs, atomic_bs);
  1787. }
  1788. if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
  1789. /* NPWG = Namespace Preferred Write Granularity */
  1790. phys_bs = bs * (1 + le16_to_cpu(id->npwg));
  1791. /* NOWS = Namespace Optimal Write Size */
  1792. if (id->nows)
  1793. io_opt = bs * (1 + le16_to_cpu(id->nows));
  1794. }
  1795. /*
  1796. * Linux filesystems assume writing a single physical block is
  1797. * an atomic operation. Hence limit the physical block size to the
  1798. * value of the Atomic Write Unit Power Fail parameter.
  1799. */
  1800. lim->logical_block_size = bs;
  1801. lim->physical_block_size = min(phys_bs, atomic_bs);
  1802. lim->io_min = phys_bs;
  1803. lim->io_opt = io_opt;
  1804. if ((ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) &&
  1805. (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM))
  1806. lim->max_write_zeroes_sectors = UINT_MAX;
  1807. else
  1808. lim->max_write_zeroes_sectors = ns->ctrl->max_zeroes_sectors;
  1809. return valid;
  1810. }
  1811. static bool nvme_ns_is_readonly(struct nvme_ns *ns, struct nvme_ns_info *info)
  1812. {
  1813. return info->is_readonly || test_bit(NVME_NS_FORCE_RO, &ns->flags);
  1814. }
  1815. static inline bool nvme_first_scan(struct gendisk *disk)
  1816. {
  1817. /* nvme_alloc_ns() scans the disk prior to adding it */
  1818. return !disk_live(disk);
  1819. }
  1820. static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id,
  1821. struct queue_limits *lim)
  1822. {
  1823. struct nvme_ctrl *ctrl = ns->ctrl;
  1824. u32 iob;
  1825. if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
  1826. is_power_of_2(ctrl->max_hw_sectors))
  1827. iob = ctrl->max_hw_sectors;
  1828. else
  1829. iob = nvme_lba_to_sect(ns->head, le16_to_cpu(id->noiob));
  1830. if (!iob)
  1831. return;
  1832. if (!is_power_of_2(iob)) {
  1833. if (nvme_first_scan(ns->disk))
  1834. pr_warn("%s: ignoring unaligned IO boundary:%u\n",
  1835. ns->disk->disk_name, iob);
  1836. return;
  1837. }
  1838. if (blk_queue_is_zoned(ns->disk->queue)) {
  1839. if (nvme_first_scan(ns->disk))
  1840. pr_warn("%s: ignoring zoned namespace IO boundary\n",
  1841. ns->disk->disk_name);
  1842. return;
  1843. }
  1844. lim->chunk_sectors = iob;
  1845. }
  1846. static int nvme_update_ns_info_generic(struct nvme_ns *ns,
  1847. struct nvme_ns_info *info)
  1848. {
  1849. struct queue_limits lim;
  1850. int ret;
  1851. blk_mq_freeze_queue(ns->disk->queue);
  1852. lim = queue_limits_start_update(ns->disk->queue);
  1853. nvme_set_ctrl_limits(ns->ctrl, &lim);
  1854. ret = queue_limits_commit_update(ns->disk->queue, &lim);
  1855. set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
  1856. blk_mq_unfreeze_queue(ns->disk->queue);
  1857. /* Hide the block-interface for these devices */
  1858. if (!ret)
  1859. ret = -ENODEV;
  1860. return ret;
  1861. }
  1862. static int nvme_update_ns_info_block(struct nvme_ns *ns,
  1863. struct nvme_ns_info *info)
  1864. {
  1865. struct queue_limits lim;
  1866. struct nvme_id_ns_nvm *nvm = NULL;
  1867. struct nvme_zone_info zi = {};
  1868. struct nvme_id_ns *id;
  1869. sector_t capacity;
  1870. unsigned lbaf;
  1871. int ret;
  1872. ret = nvme_identify_ns(ns->ctrl, info->nsid, &id);
  1873. if (ret)
  1874. return ret;
  1875. if (id->ncap == 0) {
  1876. /* namespace not allocated or attached */
  1877. info->is_removed = true;
  1878. ret = -ENXIO;
  1879. goto out;
  1880. }
  1881. lbaf = nvme_lbaf_index(id->flbas);
  1882. if (ns->ctrl->ctratt & NVME_CTRL_ATTR_ELBAS) {
  1883. ret = nvme_identify_ns_nvm(ns->ctrl, info->nsid, &nvm);
  1884. if (ret < 0)
  1885. goto out;
  1886. }
  1887. if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
  1888. ns->head->ids.csi == NVME_CSI_ZNS) {
  1889. ret = nvme_query_zone_info(ns, lbaf, &zi);
  1890. if (ret < 0)
  1891. goto out;
  1892. }
  1893. blk_mq_freeze_queue(ns->disk->queue);
  1894. ns->head->lba_shift = id->lbaf[lbaf].ds;
  1895. ns->head->nuse = le64_to_cpu(id->nuse);
  1896. capacity = nvme_lba_to_sect(ns->head, le64_to_cpu(id->nsze));
  1897. lim = queue_limits_start_update(ns->disk->queue);
  1898. nvme_set_ctrl_limits(ns->ctrl, &lim);
  1899. nvme_configure_metadata(ns->ctrl, ns->head, id, nvm, info);
  1900. nvme_set_chunk_sectors(ns, id, &lim);
  1901. if (!nvme_update_disk_info(ns, id, &lim))
  1902. capacity = 0;
  1903. nvme_config_discard(ns, &lim);
  1904. if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
  1905. ns->head->ids.csi == NVME_CSI_ZNS)
  1906. nvme_update_zone_info(ns, &lim, &zi);
  1907. if (ns->ctrl->vwc & NVME_CTRL_VWC_PRESENT)
  1908. lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
  1909. else
  1910. lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
  1911. /*
  1912. * Register a metadata profile for PI, or the plain non-integrity NVMe
  1913. * metadata masquerading as Type 0 if supported, otherwise reject block
  1914. * I/O to namespaces with metadata except when the namespace supports
  1915. * PI, as it can strip/insert in that case.
  1916. */
  1917. if (!nvme_init_integrity(ns->head, &lim, info))
  1918. capacity = 0;
  1919. ret = queue_limits_commit_update(ns->disk->queue, &lim);
  1920. if (ret) {
  1921. blk_mq_unfreeze_queue(ns->disk->queue);
  1922. goto out;
  1923. }
  1924. set_capacity_and_notify(ns->disk, capacity);
  1925. /*
  1926. * Only set the DEAC bit if the device guarantees that reads from
  1927. * deallocated data return zeroes. While the DEAC bit does not
  1928. * require that, it must be a no-op if reads from deallocated data
  1929. * do not return zeroes.
  1930. */
  1931. if ((id->dlfeat & 0x7) == 0x1 && (id->dlfeat & (1 << 3)))
  1932. ns->head->features |= NVME_NS_DEAC;
  1933. set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
  1934. set_bit(NVME_NS_READY, &ns->flags);
  1935. blk_mq_unfreeze_queue(ns->disk->queue);
  1936. if (blk_queue_is_zoned(ns->queue)) {
  1937. ret = blk_revalidate_disk_zones(ns->disk);
  1938. if (ret && !nvme_first_scan(ns->disk))
  1939. goto out;
  1940. }
  1941. ret = 0;
  1942. out:
  1943. kfree(nvm);
  1944. kfree(id);
  1945. return ret;
  1946. }
  1947. static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_ns_info *info)
  1948. {
  1949. bool unsupported = false;
  1950. int ret;
  1951. switch (info->ids.csi) {
  1952. case NVME_CSI_ZNS:
  1953. if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
  1954. dev_info(ns->ctrl->device,
  1955. "block device for nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
  1956. info->nsid);
  1957. ret = nvme_update_ns_info_generic(ns, info);
  1958. break;
  1959. }
  1960. ret = nvme_update_ns_info_block(ns, info);
  1961. break;
  1962. case NVME_CSI_NVM:
  1963. ret = nvme_update_ns_info_block(ns, info);
  1964. break;
  1965. default:
  1966. dev_info(ns->ctrl->device,
  1967. "block device for nsid %u not supported (csi %u)\n",
  1968. info->nsid, info->ids.csi);
  1969. ret = nvme_update_ns_info_generic(ns, info);
  1970. break;
  1971. }
  1972. /*
  1973. * If probing fails due an unsupported feature, hide the block device,
  1974. * but still allow other access.
  1975. */
  1976. if (ret == -ENODEV) {
  1977. ns->disk->flags |= GENHD_FL_HIDDEN;
  1978. set_bit(NVME_NS_READY, &ns->flags);
  1979. unsupported = true;
  1980. ret = 0;
  1981. }
  1982. if (!ret && nvme_ns_head_multipath(ns->head)) {
  1983. struct queue_limits *ns_lim = &ns->disk->queue->limits;
  1984. struct queue_limits lim;
  1985. blk_mq_freeze_queue(ns->head->disk->queue);
  1986. /*
  1987. * queue_limits mixes values that are the hardware limitations
  1988. * for bio splitting with what is the device configuration.
  1989. *
  1990. * For NVMe the device configuration can change after e.g. a
  1991. * Format command, and we really want to pick up the new format
  1992. * value here. But we must still stack the queue limits to the
  1993. * least common denominator for multipathing to split the bios
  1994. * properly.
  1995. *
  1996. * To work around this, we explicitly set the device
  1997. * configuration to those that we just queried, but only stack
  1998. * the splitting limits in to make sure we still obey possibly
  1999. * lower limitations of other controllers.
  2000. */
  2001. lim = queue_limits_start_update(ns->head->disk->queue);
  2002. lim.logical_block_size = ns_lim->logical_block_size;
  2003. lim.physical_block_size = ns_lim->physical_block_size;
  2004. lim.io_min = ns_lim->io_min;
  2005. lim.io_opt = ns_lim->io_opt;
  2006. queue_limits_stack_bdev(&lim, ns->disk->part0, 0,
  2007. ns->head->disk->disk_name);
  2008. if (unsupported)
  2009. ns->head->disk->flags |= GENHD_FL_HIDDEN;
  2010. else
  2011. nvme_init_integrity(ns->head, &lim, info);
  2012. ret = queue_limits_commit_update(ns->head->disk->queue, &lim);
  2013. set_capacity_and_notify(ns->head->disk, get_capacity(ns->disk));
  2014. set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info));
  2015. nvme_mpath_revalidate_paths(ns);
  2016. blk_mq_unfreeze_queue(ns->head->disk->queue);
  2017. }
  2018. return ret;
  2019. }
  2020. int nvme_ns_get_unique_id(struct nvme_ns *ns, u8 id[16],
  2021. enum blk_unique_id type)
  2022. {
  2023. struct nvme_ns_ids *ids = &ns->head->ids;
  2024. if (type != BLK_UID_EUI64)
  2025. return -EINVAL;
  2026. if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) {
  2027. memcpy(id, &ids->nguid, sizeof(ids->nguid));
  2028. return sizeof(ids->nguid);
  2029. }
  2030. if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) {
  2031. memcpy(id, &ids->eui64, sizeof(ids->eui64));
  2032. return sizeof(ids->eui64);
  2033. }
  2034. return -EINVAL;
  2035. }
  2036. static int nvme_get_unique_id(struct gendisk *disk, u8 id[16],
  2037. enum blk_unique_id type)
  2038. {
  2039. return nvme_ns_get_unique_id(disk->private_data, id, type);
  2040. }
  2041. #ifdef CONFIG_BLK_SED_OPAL
  2042. static int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
  2043. bool send)
  2044. {
  2045. struct nvme_ctrl *ctrl = data;
  2046. struct nvme_command cmd = { };
  2047. if (send)
  2048. cmd.common.opcode = nvme_admin_security_send;
  2049. else
  2050. cmd.common.opcode = nvme_admin_security_recv;
  2051. cmd.common.nsid = 0;
  2052. cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
  2053. cmd.common.cdw11 = cpu_to_le32(len);
  2054. return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
  2055. NVME_QID_ANY, NVME_SUBMIT_AT_HEAD);
  2056. }
  2057. static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
  2058. {
  2059. if (ctrl->oacs & NVME_CTRL_OACS_SEC_SUPP) {
  2060. if (!ctrl->opal_dev)
  2061. ctrl->opal_dev = init_opal_dev(ctrl, &nvme_sec_submit);
  2062. else if (was_suspended)
  2063. opal_unlock_from_suspend(ctrl->opal_dev);
  2064. } else {
  2065. free_opal_dev(ctrl->opal_dev);
  2066. ctrl->opal_dev = NULL;
  2067. }
  2068. }
  2069. #else
  2070. static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
  2071. {
  2072. }
  2073. #endif /* CONFIG_BLK_SED_OPAL */
  2074. #ifdef CONFIG_BLK_DEV_ZONED
  2075. static int nvme_report_zones(struct gendisk *disk, sector_t sector,
  2076. unsigned int nr_zones, report_zones_cb cb, void *data)
  2077. {
  2078. return nvme_ns_report_zones(disk->private_data, sector, nr_zones, cb,
  2079. data);
  2080. }
  2081. #else
  2082. #define nvme_report_zones NULL
  2083. #endif /* CONFIG_BLK_DEV_ZONED */
  2084. const struct block_device_operations nvme_bdev_ops = {
  2085. .owner = THIS_MODULE,
  2086. .ioctl = nvme_ioctl,
  2087. .compat_ioctl = blkdev_compat_ptr_ioctl,
  2088. .open = nvme_open,
  2089. .release = nvme_release,
  2090. .getgeo = nvme_getgeo,
  2091. .get_unique_id = nvme_get_unique_id,
  2092. .report_zones = nvme_report_zones,
  2093. .pr_ops = &nvme_pr_ops,
  2094. };
  2095. static int nvme_wait_ready(struct nvme_ctrl *ctrl, u32 mask, u32 val,
  2096. u32 timeout, const char *op)
  2097. {
  2098. unsigned long timeout_jiffies = jiffies + timeout * HZ;
  2099. u32 csts;
  2100. int ret;
  2101. while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
  2102. if (csts == ~0)
  2103. return -ENODEV;
  2104. if ((csts & mask) == val)
  2105. break;
  2106. usleep_range(1000, 2000);
  2107. if (fatal_signal_pending(current))
  2108. return -EINTR;
  2109. if (time_after(jiffies, timeout_jiffies)) {
  2110. dev_err(ctrl->device,
  2111. "Device not ready; aborting %s, CSTS=0x%x\n",
  2112. op, csts);
  2113. return -ENODEV;
  2114. }
  2115. }
  2116. return ret;
  2117. }
  2118. int nvme_disable_ctrl(struct nvme_ctrl *ctrl, bool shutdown)
  2119. {
  2120. int ret;
  2121. ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
  2122. if (shutdown)
  2123. ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
  2124. else
  2125. ctrl->ctrl_config &= ~NVME_CC_ENABLE;
  2126. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  2127. if (ret)
  2128. return ret;
  2129. if (shutdown) {
  2130. return nvme_wait_ready(ctrl, NVME_CSTS_SHST_MASK,
  2131. NVME_CSTS_SHST_CMPLT,
  2132. ctrl->shutdown_timeout, "shutdown");
  2133. }
  2134. if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
  2135. msleep(NVME_QUIRK_DELAY_AMOUNT);
  2136. return nvme_wait_ready(ctrl, NVME_CSTS_RDY, 0,
  2137. (NVME_CAP_TIMEOUT(ctrl->cap) + 1) / 2, "reset");
  2138. }
  2139. EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
  2140. int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
  2141. {
  2142. unsigned dev_page_min;
  2143. u32 timeout;
  2144. int ret;
  2145. ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
  2146. if (ret) {
  2147. dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
  2148. return ret;
  2149. }
  2150. dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
  2151. if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
  2152. dev_err(ctrl->device,
  2153. "Minimum device page size %u too large for host (%u)\n",
  2154. 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
  2155. return -ENODEV;
  2156. }
  2157. if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
  2158. ctrl->ctrl_config = NVME_CC_CSS_CSI;
  2159. else
  2160. ctrl->ctrl_config = NVME_CC_CSS_NVM;
  2161. /*
  2162. * Setting CRIME results in CSTS.RDY before the media is ready. This
  2163. * makes it possible for media related commands to return the error
  2164. * NVME_SC_ADMIN_COMMAND_MEDIA_NOT_READY. Until the driver is
  2165. * restructured to handle retries, disable CC.CRIME.
  2166. */
  2167. ctrl->ctrl_config &= ~NVME_CC_CRIME;
  2168. ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
  2169. ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
  2170. ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
  2171. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  2172. if (ret)
  2173. return ret;
  2174. /* CAP value may change after initial CC write */
  2175. ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
  2176. if (ret)
  2177. return ret;
  2178. timeout = NVME_CAP_TIMEOUT(ctrl->cap);
  2179. if (ctrl->cap & NVME_CAP_CRMS_CRWMS) {
  2180. u32 crto, ready_timeout;
  2181. ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CRTO, &crto);
  2182. if (ret) {
  2183. dev_err(ctrl->device, "Reading CRTO failed (%d)\n",
  2184. ret);
  2185. return ret;
  2186. }
  2187. /*
  2188. * CRTO should always be greater or equal to CAP.TO, but some
  2189. * devices are known to get this wrong. Use the larger of the
  2190. * two values.
  2191. */
  2192. ready_timeout = NVME_CRTO_CRWMT(crto);
  2193. if (ready_timeout < timeout)
  2194. dev_warn_once(ctrl->device, "bad crto:%x cap:%llx\n",
  2195. crto, ctrl->cap);
  2196. else
  2197. timeout = ready_timeout;
  2198. }
  2199. ctrl->ctrl_config |= NVME_CC_ENABLE;
  2200. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  2201. if (ret)
  2202. return ret;
  2203. return nvme_wait_ready(ctrl, NVME_CSTS_RDY, NVME_CSTS_RDY,
  2204. (timeout + 1) / 2, "initialisation");
  2205. }
  2206. EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
  2207. static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
  2208. {
  2209. __le64 ts;
  2210. int ret;
  2211. if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
  2212. return 0;
  2213. ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
  2214. ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
  2215. NULL);
  2216. if (ret)
  2217. dev_warn_once(ctrl->device,
  2218. "could not set timestamp (%d)\n", ret);
  2219. return ret;
  2220. }
  2221. static int nvme_configure_host_options(struct nvme_ctrl *ctrl)
  2222. {
  2223. struct nvme_feat_host_behavior *host;
  2224. u8 acre = 0, lbafee = 0;
  2225. int ret;
  2226. /* Don't bother enabling the feature if retry delay is not reported */
  2227. if (ctrl->crdt[0])
  2228. acre = NVME_ENABLE_ACRE;
  2229. if (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)
  2230. lbafee = NVME_ENABLE_LBAFEE;
  2231. if (!acre && !lbafee)
  2232. return 0;
  2233. host = kzalloc(sizeof(*host), GFP_KERNEL);
  2234. if (!host)
  2235. return 0;
  2236. host->acre = acre;
  2237. host->lbafee = lbafee;
  2238. ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
  2239. host, sizeof(*host), NULL);
  2240. kfree(host);
  2241. return ret;
  2242. }
  2243. /*
  2244. * The function checks whether the given total (exlat + enlat) latency of
  2245. * a power state allows the latter to be used as an APST transition target.
  2246. * It does so by comparing the latency to the primary and secondary latency
  2247. * tolerances defined by module params. If there's a match, the corresponding
  2248. * timeout value is returned and the matching tolerance index (1 or 2) is
  2249. * reported.
  2250. */
  2251. static bool nvme_apst_get_transition_time(u64 total_latency,
  2252. u64 *transition_time, unsigned *last_index)
  2253. {
  2254. if (total_latency <= apst_primary_latency_tol_us) {
  2255. if (*last_index == 1)
  2256. return false;
  2257. *last_index = 1;
  2258. *transition_time = apst_primary_timeout_ms;
  2259. return true;
  2260. }
  2261. if (apst_secondary_timeout_ms &&
  2262. total_latency <= apst_secondary_latency_tol_us) {
  2263. if (*last_index <= 2)
  2264. return false;
  2265. *last_index = 2;
  2266. *transition_time = apst_secondary_timeout_ms;
  2267. return true;
  2268. }
  2269. return false;
  2270. }
  2271. /*
  2272. * APST (Autonomous Power State Transition) lets us program a table of power
  2273. * state transitions that the controller will perform automatically.
  2274. *
  2275. * Depending on module params, one of the two supported techniques will be used:
  2276. *
  2277. * - If the parameters provide explicit timeouts and tolerances, they will be
  2278. * used to build a table with up to 2 non-operational states to transition to.
  2279. * The default parameter values were selected based on the values used by
  2280. * Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic
  2281. * regeneration of the APST table in the event of switching between external
  2282. * and battery power, the timeouts and tolerances reflect a compromise
  2283. * between values used by Microsoft for AC and battery scenarios.
  2284. * - If not, we'll configure the table with a simple heuristic: we are willing
  2285. * to spend at most 2% of the time transitioning between power states.
  2286. * Therefore, when running in any given state, we will enter the next
  2287. * lower-power non-operational state after waiting 50 * (enlat + exlat)
  2288. * microseconds, as long as that state's exit latency is under the requested
  2289. * maximum latency.
  2290. *
  2291. * We will not autonomously enter any non-operational state for which the total
  2292. * latency exceeds ps_max_latency_us.
  2293. *
  2294. * Users can set ps_max_latency_us to zero to turn off APST.
  2295. */
  2296. static int nvme_configure_apst(struct nvme_ctrl *ctrl)
  2297. {
  2298. struct nvme_feat_auto_pst *table;
  2299. unsigned apste = 0;
  2300. u64 max_lat_us = 0;
  2301. __le64 target = 0;
  2302. int max_ps = -1;
  2303. int state;
  2304. int ret;
  2305. unsigned last_lt_index = UINT_MAX;
  2306. /*
  2307. * If APST isn't supported or if we haven't been initialized yet,
  2308. * then don't do anything.
  2309. */
  2310. if (!ctrl->apsta)
  2311. return 0;
  2312. if (ctrl->npss > 31) {
  2313. dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
  2314. return 0;
  2315. }
  2316. table = kzalloc(sizeof(*table), GFP_KERNEL);
  2317. if (!table)
  2318. return 0;
  2319. if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
  2320. /* Turn off APST. */
  2321. dev_dbg(ctrl->device, "APST disabled\n");
  2322. goto done;
  2323. }
  2324. /*
  2325. * Walk through all states from lowest- to highest-power.
  2326. * According to the spec, lower-numbered states use more power. NPSS,
  2327. * despite the name, is the index of the lowest-power state, not the
  2328. * number of states.
  2329. */
  2330. for (state = (int)ctrl->npss; state >= 0; state--) {
  2331. u64 total_latency_us, exit_latency_us, transition_ms;
  2332. if (target)
  2333. table->entries[state] = target;
  2334. /*
  2335. * Don't allow transitions to the deepest state if it's quirked
  2336. * off.
  2337. */
  2338. if (state == ctrl->npss &&
  2339. (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
  2340. continue;
  2341. /*
  2342. * Is this state a useful non-operational state for higher-power
  2343. * states to autonomously transition to?
  2344. */
  2345. if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
  2346. continue;
  2347. exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
  2348. if (exit_latency_us > ctrl->ps_max_latency_us)
  2349. continue;
  2350. total_latency_us = exit_latency_us +
  2351. le32_to_cpu(ctrl->psd[state].entry_lat);
  2352. /*
  2353. * This state is good. It can be used as the APST idle target
  2354. * for higher power states.
  2355. */
  2356. if (apst_primary_timeout_ms && apst_primary_latency_tol_us) {
  2357. if (!nvme_apst_get_transition_time(total_latency_us,
  2358. &transition_ms, &last_lt_index))
  2359. continue;
  2360. } else {
  2361. transition_ms = total_latency_us + 19;
  2362. do_div(transition_ms, 20);
  2363. if (transition_ms > (1 << 24) - 1)
  2364. transition_ms = (1 << 24) - 1;
  2365. }
  2366. target = cpu_to_le64((state << 3) | (transition_ms << 8));
  2367. if (max_ps == -1)
  2368. max_ps = state;
  2369. if (total_latency_us > max_lat_us)
  2370. max_lat_us = total_latency_us;
  2371. }
  2372. if (max_ps == -1)
  2373. dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
  2374. else
  2375. dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
  2376. max_ps, max_lat_us, (int)sizeof(*table), table);
  2377. apste = 1;
  2378. done:
  2379. ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
  2380. table, sizeof(*table), NULL);
  2381. if (ret)
  2382. dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
  2383. kfree(table);
  2384. return ret;
  2385. }
  2386. static void nvme_set_latency_tolerance(struct device *dev, s32 val)
  2387. {
  2388. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  2389. u64 latency;
  2390. switch (val) {
  2391. case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
  2392. case PM_QOS_LATENCY_ANY:
  2393. latency = U64_MAX;
  2394. break;
  2395. default:
  2396. latency = val;
  2397. }
  2398. if (ctrl->ps_max_latency_us != latency) {
  2399. ctrl->ps_max_latency_us = latency;
  2400. if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
  2401. nvme_configure_apst(ctrl);
  2402. }
  2403. }
  2404. struct nvme_core_quirk_entry {
  2405. /*
  2406. * NVMe model and firmware strings are padded with spaces. For
  2407. * simplicity, strings in the quirk table are padded with NULLs
  2408. * instead.
  2409. */
  2410. u16 vid;
  2411. const char *mn;
  2412. const char *fr;
  2413. unsigned long quirks;
  2414. };
  2415. static const struct nvme_core_quirk_entry core_quirks[] = {
  2416. {
  2417. /*
  2418. * This Toshiba device seems to die using any APST states. See:
  2419. * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
  2420. */
  2421. .vid = 0x1179,
  2422. .mn = "THNSF5256GPUK TOSHIBA",
  2423. .quirks = NVME_QUIRK_NO_APST,
  2424. },
  2425. {
  2426. /*
  2427. * This LiteON CL1-3D*-Q11 firmware version has a race
  2428. * condition associated with actions related to suspend to idle
  2429. * LiteON has resolved the problem in future firmware
  2430. */
  2431. .vid = 0x14a4,
  2432. .fr = "22301111",
  2433. .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
  2434. },
  2435. {
  2436. /*
  2437. * This Kioxia CD6-V Series / HPE PE8030 device times out and
  2438. * aborts I/O during any load, but more easily reproducible
  2439. * with discards (fstrim).
  2440. *
  2441. * The device is left in a state where it is also not possible
  2442. * to use "nvme set-feature" to disable APST, but booting with
  2443. * nvme_core.default_ps_max_latency=0 works.
  2444. */
  2445. .vid = 0x1e0f,
  2446. .mn = "KCD6XVUL6T40",
  2447. .quirks = NVME_QUIRK_NO_APST,
  2448. },
  2449. {
  2450. /*
  2451. * The external Samsung X5 SSD fails initialization without a
  2452. * delay before checking if it is ready and has a whole set of
  2453. * other problems. To make this even more interesting, it
  2454. * shares the PCI ID with internal Samsung 970 Evo Plus that
  2455. * does not need or want these quirks.
  2456. */
  2457. .vid = 0x144d,
  2458. .mn = "Samsung Portable SSD X5",
  2459. .quirks = NVME_QUIRK_DELAY_BEFORE_CHK_RDY |
  2460. NVME_QUIRK_NO_DEEPEST_PS |
  2461. NVME_QUIRK_IGNORE_DEV_SUBNQN,
  2462. }
  2463. };
  2464. /* match is null-terminated but idstr is space-padded. */
  2465. static bool string_matches(const char *idstr, const char *match, size_t len)
  2466. {
  2467. size_t matchlen;
  2468. if (!match)
  2469. return true;
  2470. matchlen = strlen(match);
  2471. WARN_ON_ONCE(matchlen > len);
  2472. if (memcmp(idstr, match, matchlen))
  2473. return false;
  2474. for (; matchlen < len; matchlen++)
  2475. if (idstr[matchlen] != ' ')
  2476. return false;
  2477. return true;
  2478. }
  2479. static bool quirk_matches(const struct nvme_id_ctrl *id,
  2480. const struct nvme_core_quirk_entry *q)
  2481. {
  2482. return q->vid == le16_to_cpu(id->vid) &&
  2483. string_matches(id->mn, q->mn, sizeof(id->mn)) &&
  2484. string_matches(id->fr, q->fr, sizeof(id->fr));
  2485. }
  2486. static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
  2487. struct nvme_id_ctrl *id)
  2488. {
  2489. size_t nqnlen;
  2490. int off;
  2491. if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
  2492. nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
  2493. if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
  2494. strscpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
  2495. return;
  2496. }
  2497. if (ctrl->vs >= NVME_VS(1, 2, 1))
  2498. dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
  2499. }
  2500. /*
  2501. * Generate a "fake" NQN similar to the one in Section 4.5 of the NVMe
  2502. * Base Specification 2.0. It is slightly different from the format
  2503. * specified there due to historic reasons, and we can't change it now.
  2504. */
  2505. off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
  2506. "nqn.2014.08.org.nvmexpress:%04x%04x",
  2507. le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
  2508. memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
  2509. off += sizeof(id->sn);
  2510. memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
  2511. off += sizeof(id->mn);
  2512. memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
  2513. }
  2514. static void nvme_release_subsystem(struct device *dev)
  2515. {
  2516. struct nvme_subsystem *subsys =
  2517. container_of(dev, struct nvme_subsystem, dev);
  2518. if (subsys->instance >= 0)
  2519. ida_free(&nvme_instance_ida, subsys->instance);
  2520. kfree(subsys);
  2521. }
  2522. static void nvme_destroy_subsystem(struct kref *ref)
  2523. {
  2524. struct nvme_subsystem *subsys =
  2525. container_of(ref, struct nvme_subsystem, ref);
  2526. mutex_lock(&nvme_subsystems_lock);
  2527. list_del(&subsys->entry);
  2528. mutex_unlock(&nvme_subsystems_lock);
  2529. ida_destroy(&subsys->ns_ida);
  2530. device_del(&subsys->dev);
  2531. put_device(&subsys->dev);
  2532. }
  2533. static void nvme_put_subsystem(struct nvme_subsystem *subsys)
  2534. {
  2535. kref_put(&subsys->ref, nvme_destroy_subsystem);
  2536. }
  2537. static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
  2538. {
  2539. struct nvme_subsystem *subsys;
  2540. lockdep_assert_held(&nvme_subsystems_lock);
  2541. /*
  2542. * Fail matches for discovery subsystems. This results
  2543. * in each discovery controller bound to a unique subsystem.
  2544. * This avoids issues with validating controller values
  2545. * that can only be true when there is a single unique subsystem.
  2546. * There may be multiple and completely independent entities
  2547. * that provide discovery controllers.
  2548. */
  2549. if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
  2550. return NULL;
  2551. list_for_each_entry(subsys, &nvme_subsystems, entry) {
  2552. if (strcmp(subsys->subnqn, subsysnqn))
  2553. continue;
  2554. if (!kref_get_unless_zero(&subsys->ref))
  2555. continue;
  2556. return subsys;
  2557. }
  2558. return NULL;
  2559. }
  2560. static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
  2561. {
  2562. return ctrl->opts && ctrl->opts->discovery_nqn;
  2563. }
  2564. static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
  2565. struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
  2566. {
  2567. struct nvme_ctrl *tmp;
  2568. lockdep_assert_held(&nvme_subsystems_lock);
  2569. list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
  2570. if (nvme_state_terminal(tmp))
  2571. continue;
  2572. if (tmp->cntlid == ctrl->cntlid) {
  2573. dev_err(ctrl->device,
  2574. "Duplicate cntlid %u with %s, subsys %s, rejecting\n",
  2575. ctrl->cntlid, dev_name(tmp->device),
  2576. subsys->subnqn);
  2577. return false;
  2578. }
  2579. if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
  2580. nvme_discovery_ctrl(ctrl))
  2581. continue;
  2582. dev_err(ctrl->device,
  2583. "Subsystem does not support multiple controllers\n");
  2584. return false;
  2585. }
  2586. return true;
  2587. }
  2588. static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
  2589. {
  2590. struct nvme_subsystem *subsys, *found;
  2591. int ret;
  2592. subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
  2593. if (!subsys)
  2594. return -ENOMEM;
  2595. subsys->instance = -1;
  2596. mutex_init(&subsys->lock);
  2597. kref_init(&subsys->ref);
  2598. INIT_LIST_HEAD(&subsys->ctrls);
  2599. INIT_LIST_HEAD(&subsys->nsheads);
  2600. nvme_init_subnqn(subsys, ctrl, id);
  2601. memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
  2602. memcpy(subsys->model, id->mn, sizeof(subsys->model));
  2603. subsys->vendor_id = le16_to_cpu(id->vid);
  2604. subsys->cmic = id->cmic;
  2605. /* Versions prior to 1.4 don't necessarily report a valid type */
  2606. if (id->cntrltype == NVME_CTRL_DISC ||
  2607. !strcmp(subsys->subnqn, NVME_DISC_SUBSYS_NAME))
  2608. subsys->subtype = NVME_NQN_DISC;
  2609. else
  2610. subsys->subtype = NVME_NQN_NVME;
  2611. if (nvme_discovery_ctrl(ctrl) && subsys->subtype != NVME_NQN_DISC) {
  2612. dev_err(ctrl->device,
  2613. "Subsystem %s is not a discovery controller",
  2614. subsys->subnqn);
  2615. kfree(subsys);
  2616. return -EINVAL;
  2617. }
  2618. subsys->awupf = le16_to_cpu(id->awupf);
  2619. nvme_mpath_default_iopolicy(subsys);
  2620. subsys->dev.class = &nvme_subsys_class;
  2621. subsys->dev.release = nvme_release_subsystem;
  2622. subsys->dev.groups = nvme_subsys_attrs_groups;
  2623. dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
  2624. device_initialize(&subsys->dev);
  2625. mutex_lock(&nvme_subsystems_lock);
  2626. found = __nvme_find_get_subsystem(subsys->subnqn);
  2627. if (found) {
  2628. put_device(&subsys->dev);
  2629. subsys = found;
  2630. if (!nvme_validate_cntlid(subsys, ctrl, id)) {
  2631. ret = -EINVAL;
  2632. goto out_put_subsystem;
  2633. }
  2634. } else {
  2635. ret = device_add(&subsys->dev);
  2636. if (ret) {
  2637. dev_err(ctrl->device,
  2638. "failed to register subsystem device.\n");
  2639. put_device(&subsys->dev);
  2640. goto out_unlock;
  2641. }
  2642. ida_init(&subsys->ns_ida);
  2643. list_add_tail(&subsys->entry, &nvme_subsystems);
  2644. }
  2645. ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
  2646. dev_name(ctrl->device));
  2647. if (ret) {
  2648. dev_err(ctrl->device,
  2649. "failed to create sysfs link from subsystem.\n");
  2650. goto out_put_subsystem;
  2651. }
  2652. if (!found)
  2653. subsys->instance = ctrl->instance;
  2654. ctrl->subsys = subsys;
  2655. list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
  2656. mutex_unlock(&nvme_subsystems_lock);
  2657. return 0;
  2658. out_put_subsystem:
  2659. nvme_put_subsystem(subsys);
  2660. out_unlock:
  2661. mutex_unlock(&nvme_subsystems_lock);
  2662. return ret;
  2663. }
  2664. int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
  2665. void *log, size_t size, u64 offset)
  2666. {
  2667. struct nvme_command c = { };
  2668. u32 dwlen = nvme_bytes_to_numd(size);
  2669. c.get_log_page.opcode = nvme_admin_get_log_page;
  2670. c.get_log_page.nsid = cpu_to_le32(nsid);
  2671. c.get_log_page.lid = log_page;
  2672. c.get_log_page.lsp = lsp;
  2673. c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
  2674. c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
  2675. c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
  2676. c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
  2677. c.get_log_page.csi = csi;
  2678. return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
  2679. }
  2680. static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
  2681. struct nvme_effects_log **log)
  2682. {
  2683. struct nvme_effects_log *old, *cel = xa_load(&ctrl->cels, csi);
  2684. int ret;
  2685. if (cel)
  2686. goto out;
  2687. cel = kzalloc(sizeof(*cel), GFP_KERNEL);
  2688. if (!cel)
  2689. return -ENOMEM;
  2690. ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
  2691. cel, sizeof(*cel), 0);
  2692. if (ret) {
  2693. kfree(cel);
  2694. return ret;
  2695. }
  2696. old = xa_store(&ctrl->cels, csi, cel, GFP_KERNEL);
  2697. if (xa_is_err(old)) {
  2698. kfree(cel);
  2699. return xa_err(old);
  2700. }
  2701. out:
  2702. *log = cel;
  2703. return 0;
  2704. }
  2705. static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
  2706. {
  2707. u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
  2708. if (check_shl_overflow(1U, units + page_shift - 9, &val))
  2709. return UINT_MAX;
  2710. return val;
  2711. }
  2712. static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
  2713. {
  2714. struct nvme_command c = { };
  2715. struct nvme_id_ctrl_nvm *id;
  2716. int ret;
  2717. /*
  2718. * Even though NVMe spec explicitly states that MDTS is not applicable
  2719. * to the write-zeroes, we are cautious and limit the size to the
  2720. * controllers max_hw_sectors value, which is based on the MDTS field
  2721. * and possibly other limiting factors.
  2722. */
  2723. if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
  2724. !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
  2725. ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
  2726. else
  2727. ctrl->max_zeroes_sectors = 0;
  2728. if (ctrl->subsys->subtype != NVME_NQN_NVME ||
  2729. !nvme_id_cns_ok(ctrl, NVME_ID_CNS_CS_CTRL) ||
  2730. test_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags))
  2731. return 0;
  2732. id = kzalloc(sizeof(*id), GFP_KERNEL);
  2733. if (!id)
  2734. return -ENOMEM;
  2735. c.identify.opcode = nvme_admin_identify;
  2736. c.identify.cns = NVME_ID_CNS_CS_CTRL;
  2737. c.identify.csi = NVME_CSI_NVM;
  2738. ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
  2739. if (ret)
  2740. goto free_data;
  2741. ctrl->dmrl = id->dmrl;
  2742. ctrl->dmrsl = le32_to_cpu(id->dmrsl);
  2743. if (id->wzsl)
  2744. ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
  2745. free_data:
  2746. if (ret > 0)
  2747. set_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags);
  2748. kfree(id);
  2749. return ret;
  2750. }
  2751. static int nvme_init_effects_log(struct nvme_ctrl *ctrl,
  2752. u8 csi, struct nvme_effects_log **log)
  2753. {
  2754. struct nvme_effects_log *effects, *old;
  2755. effects = kzalloc(sizeof(*effects), GFP_KERNEL);
  2756. if (!effects)
  2757. return -ENOMEM;
  2758. old = xa_store(&ctrl->cels, csi, effects, GFP_KERNEL);
  2759. if (xa_is_err(old)) {
  2760. kfree(effects);
  2761. return xa_err(old);
  2762. }
  2763. *log = effects;
  2764. return 0;
  2765. }
  2766. static void nvme_init_known_nvm_effects(struct nvme_ctrl *ctrl)
  2767. {
  2768. struct nvme_effects_log *log = ctrl->effects;
  2769. log->acs[nvme_admin_format_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
  2770. NVME_CMD_EFFECTS_NCC |
  2771. NVME_CMD_EFFECTS_CSE_MASK);
  2772. log->acs[nvme_admin_sanitize_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
  2773. NVME_CMD_EFFECTS_CSE_MASK);
  2774. /*
  2775. * The spec says the result of a security receive command depends on
  2776. * the previous security send command. As such, many vendors log this
  2777. * command as one to submitted only when no other commands to the same
  2778. * namespace are outstanding. The intention is to tell the host to
  2779. * prevent mixing security send and receive.
  2780. *
  2781. * This driver can only enforce such exclusive access against IO
  2782. * queues, though. We are not readily able to enforce such a rule for
  2783. * two commands to the admin queue, which is the only queue that
  2784. * matters for this command.
  2785. *
  2786. * Rather than blindly freezing the IO queues for this effect that
  2787. * doesn't even apply to IO, mask it off.
  2788. */
  2789. log->acs[nvme_admin_security_recv] &= cpu_to_le32(~NVME_CMD_EFFECTS_CSE_MASK);
  2790. log->iocs[nvme_cmd_write] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
  2791. log->iocs[nvme_cmd_write_zeroes] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
  2792. log->iocs[nvme_cmd_write_uncor] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
  2793. }
  2794. static int nvme_init_effects(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
  2795. {
  2796. int ret = 0;
  2797. if (ctrl->effects)
  2798. return 0;
  2799. if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
  2800. ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
  2801. if (ret < 0)
  2802. return ret;
  2803. }
  2804. if (!ctrl->effects) {
  2805. ret = nvme_init_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
  2806. if (ret < 0)
  2807. return ret;
  2808. }
  2809. nvme_init_known_nvm_effects(ctrl);
  2810. return 0;
  2811. }
  2812. static int nvme_check_ctrl_fabric_info(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
  2813. {
  2814. /*
  2815. * In fabrics we need to verify the cntlid matches the
  2816. * admin connect
  2817. */
  2818. if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
  2819. dev_err(ctrl->device,
  2820. "Mismatching cntlid: Connect %u vs Identify %u, rejecting\n",
  2821. ctrl->cntlid, le16_to_cpu(id->cntlid));
  2822. return -EINVAL;
  2823. }
  2824. if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
  2825. dev_err(ctrl->device,
  2826. "keep-alive support is mandatory for fabrics\n");
  2827. return -EINVAL;
  2828. }
  2829. if (!nvme_discovery_ctrl(ctrl) && ctrl->ioccsz < 4) {
  2830. dev_err(ctrl->device,
  2831. "I/O queue command capsule supported size %d < 4\n",
  2832. ctrl->ioccsz);
  2833. return -EINVAL;
  2834. }
  2835. if (!nvme_discovery_ctrl(ctrl) && ctrl->iorcsz < 1) {
  2836. dev_err(ctrl->device,
  2837. "I/O queue response capsule supported size %d < 1\n",
  2838. ctrl->iorcsz);
  2839. return -EINVAL;
  2840. }
  2841. if (!ctrl->maxcmd) {
  2842. dev_warn(ctrl->device,
  2843. "Firmware bug: maximum outstanding commands is 0\n");
  2844. ctrl->maxcmd = ctrl->sqsize + 1;
  2845. }
  2846. return 0;
  2847. }
  2848. static int nvme_init_identify(struct nvme_ctrl *ctrl)
  2849. {
  2850. struct queue_limits lim;
  2851. struct nvme_id_ctrl *id;
  2852. u32 max_hw_sectors;
  2853. bool prev_apst_enabled;
  2854. int ret;
  2855. ret = nvme_identify_ctrl(ctrl, &id);
  2856. if (ret) {
  2857. dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
  2858. return -EIO;
  2859. }
  2860. if (!(ctrl->ops->flags & NVME_F_FABRICS))
  2861. ctrl->cntlid = le16_to_cpu(id->cntlid);
  2862. if (!ctrl->identified) {
  2863. unsigned int i;
  2864. /*
  2865. * Check for quirks. Quirk can depend on firmware version,
  2866. * so, in principle, the set of quirks present can change
  2867. * across a reset. As a possible future enhancement, we
  2868. * could re-scan for quirks every time we reinitialize
  2869. * the device, but we'd have to make sure that the driver
  2870. * behaves intelligently if the quirks change.
  2871. */
  2872. for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
  2873. if (quirk_matches(id, &core_quirks[i]))
  2874. ctrl->quirks |= core_quirks[i].quirks;
  2875. }
  2876. ret = nvme_init_subsystem(ctrl, id);
  2877. if (ret)
  2878. goto out_free;
  2879. ret = nvme_init_effects(ctrl, id);
  2880. if (ret)
  2881. goto out_free;
  2882. }
  2883. memcpy(ctrl->subsys->firmware_rev, id->fr,
  2884. sizeof(ctrl->subsys->firmware_rev));
  2885. if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
  2886. dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
  2887. ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
  2888. }
  2889. ctrl->crdt[0] = le16_to_cpu(id->crdt1);
  2890. ctrl->crdt[1] = le16_to_cpu(id->crdt2);
  2891. ctrl->crdt[2] = le16_to_cpu(id->crdt3);
  2892. ctrl->oacs = le16_to_cpu(id->oacs);
  2893. ctrl->oncs = le16_to_cpu(id->oncs);
  2894. ctrl->mtfa = le16_to_cpu(id->mtfa);
  2895. ctrl->oaes = le32_to_cpu(id->oaes);
  2896. ctrl->wctemp = le16_to_cpu(id->wctemp);
  2897. ctrl->cctemp = le16_to_cpu(id->cctemp);
  2898. atomic_set(&ctrl->abort_limit, id->acl + 1);
  2899. ctrl->vwc = id->vwc;
  2900. if (id->mdts)
  2901. max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
  2902. else
  2903. max_hw_sectors = UINT_MAX;
  2904. ctrl->max_hw_sectors =
  2905. min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
  2906. lim = queue_limits_start_update(ctrl->admin_q);
  2907. nvme_set_ctrl_limits(ctrl, &lim);
  2908. ret = queue_limits_commit_update(ctrl->admin_q, &lim);
  2909. if (ret)
  2910. goto out_free;
  2911. ctrl->sgls = le32_to_cpu(id->sgls);
  2912. ctrl->kas = le16_to_cpu(id->kas);
  2913. ctrl->max_namespaces = le32_to_cpu(id->mnan);
  2914. ctrl->ctratt = le32_to_cpu(id->ctratt);
  2915. ctrl->cntrltype = id->cntrltype;
  2916. ctrl->dctype = id->dctype;
  2917. if (id->rtd3e) {
  2918. /* us -> s */
  2919. u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
  2920. ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
  2921. shutdown_timeout, 60);
  2922. if (ctrl->shutdown_timeout != shutdown_timeout)
  2923. dev_info(ctrl->device,
  2924. "D3 entry latency set to %u seconds\n",
  2925. ctrl->shutdown_timeout);
  2926. } else
  2927. ctrl->shutdown_timeout = shutdown_timeout;
  2928. ctrl->npss = id->npss;
  2929. ctrl->apsta = id->apsta;
  2930. prev_apst_enabled = ctrl->apst_enabled;
  2931. if (ctrl->quirks & NVME_QUIRK_NO_APST) {
  2932. if (force_apst && id->apsta) {
  2933. dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
  2934. ctrl->apst_enabled = true;
  2935. } else {
  2936. ctrl->apst_enabled = false;
  2937. }
  2938. } else {
  2939. ctrl->apst_enabled = id->apsta;
  2940. }
  2941. memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
  2942. if (ctrl->ops->flags & NVME_F_FABRICS) {
  2943. ctrl->icdoff = le16_to_cpu(id->icdoff);
  2944. ctrl->ioccsz = le32_to_cpu(id->ioccsz);
  2945. ctrl->iorcsz = le32_to_cpu(id->iorcsz);
  2946. ctrl->maxcmd = le16_to_cpu(id->maxcmd);
  2947. ret = nvme_check_ctrl_fabric_info(ctrl, id);
  2948. if (ret)
  2949. goto out_free;
  2950. } else {
  2951. ctrl->hmpre = le32_to_cpu(id->hmpre);
  2952. ctrl->hmmin = le32_to_cpu(id->hmmin);
  2953. ctrl->hmminds = le32_to_cpu(id->hmminds);
  2954. ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
  2955. }
  2956. ret = nvme_mpath_init_identify(ctrl, id);
  2957. if (ret < 0)
  2958. goto out_free;
  2959. if (ctrl->apst_enabled && !prev_apst_enabled)
  2960. dev_pm_qos_expose_latency_tolerance(ctrl->device);
  2961. else if (!ctrl->apst_enabled && prev_apst_enabled)
  2962. dev_pm_qos_hide_latency_tolerance(ctrl->device);
  2963. out_free:
  2964. kfree(id);
  2965. return ret;
  2966. }
  2967. /*
  2968. * Initialize the cached copies of the Identify data and various controller
  2969. * register in our nvme_ctrl structure. This should be called as soon as
  2970. * the admin queue is fully up and running.
  2971. */
  2972. int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl, bool was_suspended)
  2973. {
  2974. int ret;
  2975. ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
  2976. if (ret) {
  2977. dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
  2978. return ret;
  2979. }
  2980. ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
  2981. if (ctrl->vs >= NVME_VS(1, 1, 0))
  2982. ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
  2983. ret = nvme_init_identify(ctrl);
  2984. if (ret)
  2985. return ret;
  2986. ret = nvme_configure_apst(ctrl);
  2987. if (ret < 0)
  2988. return ret;
  2989. ret = nvme_configure_timestamp(ctrl);
  2990. if (ret < 0)
  2991. return ret;
  2992. ret = nvme_configure_host_options(ctrl);
  2993. if (ret < 0)
  2994. return ret;
  2995. nvme_configure_opal(ctrl, was_suspended);
  2996. if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
  2997. /*
  2998. * Do not return errors unless we are in a controller reset,
  2999. * the controller works perfectly fine without hwmon.
  3000. */
  3001. ret = nvme_hwmon_init(ctrl);
  3002. if (ret == -EINTR)
  3003. return ret;
  3004. }
  3005. clear_bit(NVME_CTRL_DIRTY_CAPABILITY, &ctrl->flags);
  3006. ctrl->identified = true;
  3007. nvme_start_keep_alive(ctrl);
  3008. return 0;
  3009. }
  3010. EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
  3011. static int nvme_dev_open(struct inode *inode, struct file *file)
  3012. {
  3013. struct nvme_ctrl *ctrl =
  3014. container_of(inode->i_cdev, struct nvme_ctrl, cdev);
  3015. switch (nvme_ctrl_state(ctrl)) {
  3016. case NVME_CTRL_LIVE:
  3017. break;
  3018. default:
  3019. return -EWOULDBLOCK;
  3020. }
  3021. nvme_get_ctrl(ctrl);
  3022. if (!try_module_get(ctrl->ops->module)) {
  3023. nvme_put_ctrl(ctrl);
  3024. return -EINVAL;
  3025. }
  3026. file->private_data = ctrl;
  3027. return 0;
  3028. }
  3029. static int nvme_dev_release(struct inode *inode, struct file *file)
  3030. {
  3031. struct nvme_ctrl *ctrl =
  3032. container_of(inode->i_cdev, struct nvme_ctrl, cdev);
  3033. module_put(ctrl->ops->module);
  3034. nvme_put_ctrl(ctrl);
  3035. return 0;
  3036. }
  3037. static const struct file_operations nvme_dev_fops = {
  3038. .owner = THIS_MODULE,
  3039. .open = nvme_dev_open,
  3040. .release = nvme_dev_release,
  3041. .unlocked_ioctl = nvme_dev_ioctl,
  3042. .compat_ioctl = compat_ptr_ioctl,
  3043. .uring_cmd = nvme_dev_uring_cmd,
  3044. };
  3045. static struct nvme_ns_head *nvme_find_ns_head(struct nvme_ctrl *ctrl,
  3046. unsigned nsid)
  3047. {
  3048. struct nvme_ns_head *h;
  3049. lockdep_assert_held(&ctrl->subsys->lock);
  3050. list_for_each_entry(h, &ctrl->subsys->nsheads, entry) {
  3051. /*
  3052. * Private namespaces can share NSIDs under some conditions.
  3053. * In that case we can't use the same ns_head for namespaces
  3054. * with the same NSID.
  3055. */
  3056. if (h->ns_id != nsid || !nvme_is_unique_nsid(ctrl, h))
  3057. continue;
  3058. if (!list_empty(&h->list) && nvme_tryget_ns_head(h))
  3059. return h;
  3060. }
  3061. return NULL;
  3062. }
  3063. static int nvme_subsys_check_duplicate_ids(struct nvme_subsystem *subsys,
  3064. struct nvme_ns_ids *ids)
  3065. {
  3066. bool has_uuid = !uuid_is_null(&ids->uuid);
  3067. bool has_nguid = memchr_inv(ids->nguid, 0, sizeof(ids->nguid));
  3068. bool has_eui64 = memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
  3069. struct nvme_ns_head *h;
  3070. lockdep_assert_held(&subsys->lock);
  3071. list_for_each_entry(h, &subsys->nsheads, entry) {
  3072. if (has_uuid && uuid_equal(&ids->uuid, &h->ids.uuid))
  3073. return -EINVAL;
  3074. if (has_nguid &&
  3075. memcmp(&ids->nguid, &h->ids.nguid, sizeof(ids->nguid)) == 0)
  3076. return -EINVAL;
  3077. if (has_eui64 &&
  3078. memcmp(&ids->eui64, &h->ids.eui64, sizeof(ids->eui64)) == 0)
  3079. return -EINVAL;
  3080. }
  3081. return 0;
  3082. }
  3083. static void nvme_cdev_rel(struct device *dev)
  3084. {
  3085. ida_free(&nvme_ns_chr_minor_ida, MINOR(dev->devt));
  3086. }
  3087. void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
  3088. {
  3089. cdev_device_del(cdev, cdev_device);
  3090. put_device(cdev_device);
  3091. }
  3092. int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
  3093. const struct file_operations *fops, struct module *owner)
  3094. {
  3095. int minor, ret;
  3096. minor = ida_alloc(&nvme_ns_chr_minor_ida, GFP_KERNEL);
  3097. if (minor < 0)
  3098. return minor;
  3099. cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
  3100. cdev_device->class = &nvme_ns_chr_class;
  3101. cdev_device->release = nvme_cdev_rel;
  3102. device_initialize(cdev_device);
  3103. cdev_init(cdev, fops);
  3104. cdev->owner = owner;
  3105. ret = cdev_device_add(cdev, cdev_device);
  3106. if (ret)
  3107. put_device(cdev_device);
  3108. return ret;
  3109. }
  3110. static int nvme_ns_chr_open(struct inode *inode, struct file *file)
  3111. {
  3112. return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
  3113. }
  3114. static int nvme_ns_chr_release(struct inode *inode, struct file *file)
  3115. {
  3116. nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
  3117. return 0;
  3118. }
  3119. static const struct file_operations nvme_ns_chr_fops = {
  3120. .owner = THIS_MODULE,
  3121. .open = nvme_ns_chr_open,
  3122. .release = nvme_ns_chr_release,
  3123. .unlocked_ioctl = nvme_ns_chr_ioctl,
  3124. .compat_ioctl = compat_ptr_ioctl,
  3125. .uring_cmd = nvme_ns_chr_uring_cmd,
  3126. .uring_cmd_iopoll = nvme_ns_chr_uring_cmd_iopoll,
  3127. };
  3128. static int nvme_add_ns_cdev(struct nvme_ns *ns)
  3129. {
  3130. int ret;
  3131. ns->cdev_device.parent = ns->ctrl->device;
  3132. ret = dev_set_name(&ns->cdev_device, "ng%dn%d",
  3133. ns->ctrl->instance, ns->head->instance);
  3134. if (ret)
  3135. return ret;
  3136. return nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops,
  3137. ns->ctrl->ops->module);
  3138. }
  3139. static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
  3140. struct nvme_ns_info *info)
  3141. {
  3142. struct nvme_ns_head *head;
  3143. size_t size = sizeof(*head);
  3144. int ret = -ENOMEM;
  3145. #ifdef CONFIG_NVME_MULTIPATH
  3146. size += num_possible_nodes() * sizeof(struct nvme_ns *);
  3147. #endif
  3148. head = kzalloc(size, GFP_KERNEL);
  3149. if (!head)
  3150. goto out;
  3151. ret = ida_alloc_min(&ctrl->subsys->ns_ida, 1, GFP_KERNEL);
  3152. if (ret < 0)
  3153. goto out_free_head;
  3154. head->instance = ret;
  3155. INIT_LIST_HEAD(&head->list);
  3156. ret = init_srcu_struct(&head->srcu);
  3157. if (ret)
  3158. goto out_ida_remove;
  3159. head->subsys = ctrl->subsys;
  3160. head->ns_id = info->nsid;
  3161. head->ids = info->ids;
  3162. head->shared = info->is_shared;
  3163. ratelimit_state_init(&head->rs_nuse, 5 * HZ, 1);
  3164. ratelimit_set_flags(&head->rs_nuse, RATELIMIT_MSG_ON_RELEASE);
  3165. kref_init(&head->ref);
  3166. if (head->ids.csi) {
  3167. ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
  3168. if (ret)
  3169. goto out_cleanup_srcu;
  3170. } else
  3171. head->effects = ctrl->effects;
  3172. ret = nvme_mpath_alloc_disk(ctrl, head);
  3173. if (ret)
  3174. goto out_cleanup_srcu;
  3175. list_add_tail(&head->entry, &ctrl->subsys->nsheads);
  3176. kref_get(&ctrl->subsys->ref);
  3177. return head;
  3178. out_cleanup_srcu:
  3179. cleanup_srcu_struct(&head->srcu);
  3180. out_ida_remove:
  3181. ida_free(&ctrl->subsys->ns_ida, head->instance);
  3182. out_free_head:
  3183. kfree(head);
  3184. out:
  3185. if (ret > 0)
  3186. ret = blk_status_to_errno(nvme_error_status(ret));
  3187. return ERR_PTR(ret);
  3188. }
  3189. static int nvme_global_check_duplicate_ids(struct nvme_subsystem *this,
  3190. struct nvme_ns_ids *ids)
  3191. {
  3192. struct nvme_subsystem *s;
  3193. int ret = 0;
  3194. /*
  3195. * Note that this check is racy as we try to avoid holding the global
  3196. * lock over the whole ns_head creation. But it is only intended as
  3197. * a sanity check anyway.
  3198. */
  3199. mutex_lock(&nvme_subsystems_lock);
  3200. list_for_each_entry(s, &nvme_subsystems, entry) {
  3201. if (s == this)
  3202. continue;
  3203. mutex_lock(&s->lock);
  3204. ret = nvme_subsys_check_duplicate_ids(s, ids);
  3205. mutex_unlock(&s->lock);
  3206. if (ret)
  3207. break;
  3208. }
  3209. mutex_unlock(&nvme_subsystems_lock);
  3210. return ret;
  3211. }
  3212. static int nvme_init_ns_head(struct nvme_ns *ns, struct nvme_ns_info *info)
  3213. {
  3214. struct nvme_ctrl *ctrl = ns->ctrl;
  3215. struct nvme_ns_head *head = NULL;
  3216. int ret;
  3217. ret = nvme_global_check_duplicate_ids(ctrl->subsys, &info->ids);
  3218. if (ret) {
  3219. /*
  3220. * We've found two different namespaces on two different
  3221. * subsystems that report the same ID. This is pretty nasty
  3222. * for anything that actually requires unique device
  3223. * identification. In the kernel we need this for multipathing,
  3224. * and in user space the /dev/disk/by-id/ links rely on it.
  3225. *
  3226. * If the device also claims to be multi-path capable back off
  3227. * here now and refuse the probe the second device as this is a
  3228. * recipe for data corruption. If not this is probably a
  3229. * cheap consumer device if on the PCIe bus, so let the user
  3230. * proceed and use the shiny toy, but warn that with changing
  3231. * probing order (which due to our async probing could just be
  3232. * device taking longer to startup) the other device could show
  3233. * up at any time.
  3234. */
  3235. nvme_print_device_info(ctrl);
  3236. if ((ns->ctrl->ops->flags & NVME_F_FABRICS) || /* !PCIe */
  3237. ((ns->ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) &&
  3238. info->is_shared)) {
  3239. dev_err(ctrl->device,
  3240. "ignoring nsid %d because of duplicate IDs\n",
  3241. info->nsid);
  3242. return ret;
  3243. }
  3244. dev_err(ctrl->device,
  3245. "clearing duplicate IDs for nsid %d\n", info->nsid);
  3246. dev_err(ctrl->device,
  3247. "use of /dev/disk/by-id/ may cause data corruption\n");
  3248. memset(&info->ids.nguid, 0, sizeof(info->ids.nguid));
  3249. memset(&info->ids.uuid, 0, sizeof(info->ids.uuid));
  3250. memset(&info->ids.eui64, 0, sizeof(info->ids.eui64));
  3251. ctrl->quirks |= NVME_QUIRK_BOGUS_NID;
  3252. }
  3253. mutex_lock(&ctrl->subsys->lock);
  3254. head = nvme_find_ns_head(ctrl, info->nsid);
  3255. if (!head) {
  3256. ret = nvme_subsys_check_duplicate_ids(ctrl->subsys, &info->ids);
  3257. if (ret) {
  3258. dev_err(ctrl->device,
  3259. "duplicate IDs in subsystem for nsid %d\n",
  3260. info->nsid);
  3261. goto out_unlock;
  3262. }
  3263. head = nvme_alloc_ns_head(ctrl, info);
  3264. if (IS_ERR(head)) {
  3265. ret = PTR_ERR(head);
  3266. goto out_unlock;
  3267. }
  3268. } else {
  3269. ret = -EINVAL;
  3270. if (!info->is_shared || !head->shared) {
  3271. dev_err(ctrl->device,
  3272. "Duplicate unshared namespace %d\n",
  3273. info->nsid);
  3274. goto out_put_ns_head;
  3275. }
  3276. if (!nvme_ns_ids_equal(&head->ids, &info->ids)) {
  3277. dev_err(ctrl->device,
  3278. "IDs don't match for shared namespace %d\n",
  3279. info->nsid);
  3280. goto out_put_ns_head;
  3281. }
  3282. if (!multipath) {
  3283. dev_warn(ctrl->device,
  3284. "Found shared namespace %d, but multipathing not supported.\n",
  3285. info->nsid);
  3286. dev_warn_once(ctrl->device,
  3287. "Support for shared namespaces without CONFIG_NVME_MULTIPATH is deprecated and will be removed in Linux 6.0.\n");
  3288. }
  3289. }
  3290. list_add_tail_rcu(&ns->siblings, &head->list);
  3291. ns->head = head;
  3292. mutex_unlock(&ctrl->subsys->lock);
  3293. return 0;
  3294. out_put_ns_head:
  3295. nvme_put_ns_head(head);
  3296. out_unlock:
  3297. mutex_unlock(&ctrl->subsys->lock);
  3298. return ret;
  3299. }
  3300. struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
  3301. {
  3302. struct nvme_ns *ns, *ret = NULL;
  3303. int srcu_idx;
  3304. srcu_idx = srcu_read_lock(&ctrl->srcu);
  3305. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  3306. srcu_read_lock_held(&ctrl->srcu)) {
  3307. if (ns->head->ns_id == nsid) {
  3308. if (!nvme_get_ns(ns))
  3309. continue;
  3310. ret = ns;
  3311. break;
  3312. }
  3313. if (ns->head->ns_id > nsid)
  3314. break;
  3315. }
  3316. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  3317. return ret;
  3318. }
  3319. EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
  3320. /*
  3321. * Add the namespace to the controller list while keeping the list ordered.
  3322. */
  3323. static void nvme_ns_add_to_ctrl_list(struct nvme_ns *ns)
  3324. {
  3325. struct nvme_ns *tmp;
  3326. list_for_each_entry_reverse(tmp, &ns->ctrl->namespaces, list) {
  3327. if (tmp->head->ns_id < ns->head->ns_id) {
  3328. list_add_rcu(&ns->list, &tmp->list);
  3329. return;
  3330. }
  3331. }
  3332. list_add_rcu(&ns->list, &ns->ctrl->namespaces);
  3333. }
  3334. static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info)
  3335. {
  3336. struct queue_limits lim = { };
  3337. struct nvme_ns *ns;
  3338. struct gendisk *disk;
  3339. int node = ctrl->numa_node;
  3340. ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
  3341. if (!ns)
  3342. return;
  3343. if (ctrl->opts && ctrl->opts->data_digest)
  3344. lim.features |= BLK_FEAT_STABLE_WRITES;
  3345. if (ctrl->ops->supports_pci_p2pdma &&
  3346. ctrl->ops->supports_pci_p2pdma(ctrl))
  3347. lim.features |= BLK_FEAT_PCI_P2PDMA;
  3348. disk = blk_mq_alloc_disk(ctrl->tagset, &lim, ns);
  3349. if (IS_ERR(disk))
  3350. goto out_free_ns;
  3351. disk->fops = &nvme_bdev_ops;
  3352. disk->private_data = ns;
  3353. ns->disk = disk;
  3354. ns->queue = disk->queue;
  3355. ns->ctrl = ctrl;
  3356. kref_init(&ns->kref);
  3357. if (nvme_init_ns_head(ns, info))
  3358. goto out_cleanup_disk;
  3359. /*
  3360. * If multipathing is enabled, the device name for all disks and not
  3361. * just those that represent shared namespaces needs to be based on the
  3362. * subsystem instance. Using the controller instance for private
  3363. * namespaces could lead to naming collisions between shared and private
  3364. * namespaces if they don't use a common numbering scheme.
  3365. *
  3366. * If multipathing is not enabled, disk names must use the controller
  3367. * instance as shared namespaces will show up as multiple block
  3368. * devices.
  3369. */
  3370. if (nvme_ns_head_multipath(ns->head)) {
  3371. sprintf(disk->disk_name, "nvme%dc%dn%d", ctrl->subsys->instance,
  3372. ctrl->instance, ns->head->instance);
  3373. disk->flags |= GENHD_FL_HIDDEN;
  3374. } else if (multipath) {
  3375. sprintf(disk->disk_name, "nvme%dn%d", ctrl->subsys->instance,
  3376. ns->head->instance);
  3377. } else {
  3378. sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
  3379. ns->head->instance);
  3380. }
  3381. if (nvme_update_ns_info(ns, info))
  3382. goto out_unlink_ns;
  3383. mutex_lock(&ctrl->namespaces_lock);
  3384. /*
  3385. * Ensure that no namespaces are added to the ctrl list after the queues
  3386. * are frozen, thereby avoiding a deadlock between scan and reset.
  3387. */
  3388. if (test_bit(NVME_CTRL_FROZEN, &ctrl->flags)) {
  3389. mutex_unlock(&ctrl->namespaces_lock);
  3390. goto out_unlink_ns;
  3391. }
  3392. nvme_ns_add_to_ctrl_list(ns);
  3393. mutex_unlock(&ctrl->namespaces_lock);
  3394. synchronize_srcu(&ctrl->srcu);
  3395. nvme_get_ctrl(ctrl);
  3396. if (device_add_disk(ctrl->device, ns->disk, nvme_ns_attr_groups))
  3397. goto out_cleanup_ns_from_list;
  3398. if (!nvme_ns_head_multipath(ns->head))
  3399. nvme_add_ns_cdev(ns);
  3400. nvme_mpath_add_disk(ns, info->anagrpid);
  3401. nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
  3402. /*
  3403. * Set ns->disk->device->driver_data to ns so we can access
  3404. * ns->head->passthru_err_log_enabled in
  3405. * nvme_io_passthru_err_log_enabled_[store | show]().
  3406. */
  3407. dev_set_drvdata(disk_to_dev(ns->disk), ns);
  3408. return;
  3409. out_cleanup_ns_from_list:
  3410. nvme_put_ctrl(ctrl);
  3411. mutex_lock(&ctrl->namespaces_lock);
  3412. list_del_rcu(&ns->list);
  3413. mutex_unlock(&ctrl->namespaces_lock);
  3414. synchronize_srcu(&ctrl->srcu);
  3415. out_unlink_ns:
  3416. mutex_lock(&ctrl->subsys->lock);
  3417. list_del_rcu(&ns->siblings);
  3418. if (list_empty(&ns->head->list))
  3419. list_del_init(&ns->head->entry);
  3420. mutex_unlock(&ctrl->subsys->lock);
  3421. nvme_put_ns_head(ns->head);
  3422. out_cleanup_disk:
  3423. put_disk(disk);
  3424. out_free_ns:
  3425. kfree(ns);
  3426. }
  3427. static void nvme_ns_remove(struct nvme_ns *ns)
  3428. {
  3429. bool last_path = false;
  3430. if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
  3431. return;
  3432. clear_bit(NVME_NS_READY, &ns->flags);
  3433. set_capacity(ns->disk, 0);
  3434. nvme_fault_inject_fini(&ns->fault_inject);
  3435. /*
  3436. * Ensure that !NVME_NS_READY is seen by other threads to prevent
  3437. * this ns going back into current_path.
  3438. */
  3439. synchronize_srcu(&ns->head->srcu);
  3440. /* wait for concurrent submissions */
  3441. if (nvme_mpath_clear_current_path(ns))
  3442. synchronize_srcu(&ns->head->srcu);
  3443. mutex_lock(&ns->ctrl->subsys->lock);
  3444. list_del_rcu(&ns->siblings);
  3445. if (list_empty(&ns->head->list)) {
  3446. list_del_init(&ns->head->entry);
  3447. last_path = true;
  3448. }
  3449. mutex_unlock(&ns->ctrl->subsys->lock);
  3450. /* guarantee not available in head->list */
  3451. synchronize_srcu(&ns->head->srcu);
  3452. if (!nvme_ns_head_multipath(ns->head))
  3453. nvme_cdev_del(&ns->cdev, &ns->cdev_device);
  3454. del_gendisk(ns->disk);
  3455. mutex_lock(&ns->ctrl->namespaces_lock);
  3456. list_del_rcu(&ns->list);
  3457. mutex_unlock(&ns->ctrl->namespaces_lock);
  3458. synchronize_srcu(&ns->ctrl->srcu);
  3459. if (last_path)
  3460. nvme_mpath_shutdown_disk(ns->head);
  3461. nvme_put_ns(ns);
  3462. }
  3463. static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
  3464. {
  3465. struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
  3466. if (ns) {
  3467. nvme_ns_remove(ns);
  3468. nvme_put_ns(ns);
  3469. }
  3470. }
  3471. static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_info *info)
  3472. {
  3473. int ret = NVME_SC_INVALID_NS | NVME_STATUS_DNR;
  3474. if (!nvme_ns_ids_equal(&ns->head->ids, &info->ids)) {
  3475. dev_err(ns->ctrl->device,
  3476. "identifiers changed for nsid %d\n", ns->head->ns_id);
  3477. goto out;
  3478. }
  3479. ret = nvme_update_ns_info(ns, info);
  3480. out:
  3481. /*
  3482. * Only remove the namespace if we got a fatal error back from the
  3483. * device, otherwise ignore the error and just move on.
  3484. *
  3485. * TODO: we should probably schedule a delayed retry here.
  3486. */
  3487. if (ret > 0 && (ret & NVME_STATUS_DNR))
  3488. nvme_ns_remove(ns);
  3489. }
  3490. static void nvme_scan_ns(struct nvme_ctrl *ctrl, unsigned nsid)
  3491. {
  3492. struct nvme_ns_info info = { .nsid = nsid };
  3493. struct nvme_ns *ns;
  3494. int ret;
  3495. if (nvme_identify_ns_descs(ctrl, &info))
  3496. return;
  3497. if (info.ids.csi != NVME_CSI_NVM && !nvme_multi_css(ctrl)) {
  3498. dev_warn(ctrl->device,
  3499. "command set not reported for nsid: %d\n", nsid);
  3500. return;
  3501. }
  3502. /*
  3503. * If available try to use the Command Set Idependent Identify Namespace
  3504. * data structure to find all the generic information that is needed to
  3505. * set up a namespace. If not fall back to the legacy version.
  3506. */
  3507. if ((ctrl->cap & NVME_CAP_CRMS_CRIMS) ||
  3508. (info.ids.csi != NVME_CSI_NVM && info.ids.csi != NVME_CSI_ZNS))
  3509. ret = nvme_ns_info_from_id_cs_indep(ctrl, &info);
  3510. else
  3511. ret = nvme_ns_info_from_identify(ctrl, &info);
  3512. if (info.is_removed)
  3513. nvme_ns_remove_by_nsid(ctrl, nsid);
  3514. /*
  3515. * Ignore the namespace if it is not ready. We will get an AEN once it
  3516. * becomes ready and restart the scan.
  3517. */
  3518. if (ret || !info.is_ready)
  3519. return;
  3520. ns = nvme_find_get_ns(ctrl, nsid);
  3521. if (ns) {
  3522. nvme_validate_ns(ns, &info);
  3523. nvme_put_ns(ns);
  3524. } else {
  3525. nvme_alloc_ns(ctrl, &info);
  3526. }
  3527. }
  3528. /**
  3529. * struct async_scan_info - keeps track of controller & NSIDs to scan
  3530. * @ctrl: Controller on which namespaces are being scanned
  3531. * @next_nsid: Index of next NSID to scan in ns_list
  3532. * @ns_list: Pointer to list of NSIDs to scan
  3533. *
  3534. * Note: There is a single async_scan_info structure shared by all instances
  3535. * of nvme_scan_ns_async() scanning a given controller, so the atomic
  3536. * operations on next_nsid are critical to ensure each instance scans a unique
  3537. * NSID.
  3538. */
  3539. struct async_scan_info {
  3540. struct nvme_ctrl *ctrl;
  3541. atomic_t next_nsid;
  3542. __le32 *ns_list;
  3543. };
  3544. static void nvme_scan_ns_async(void *data, async_cookie_t cookie)
  3545. {
  3546. struct async_scan_info *scan_info = data;
  3547. int idx;
  3548. u32 nsid;
  3549. idx = (u32)atomic_fetch_inc(&scan_info->next_nsid);
  3550. nsid = le32_to_cpu(scan_info->ns_list[idx]);
  3551. nvme_scan_ns(scan_info->ctrl, nsid);
  3552. }
  3553. static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
  3554. unsigned nsid)
  3555. {
  3556. struct nvme_ns *ns, *next;
  3557. LIST_HEAD(rm_list);
  3558. mutex_lock(&ctrl->namespaces_lock);
  3559. list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
  3560. if (ns->head->ns_id > nsid) {
  3561. list_del_rcu(&ns->list);
  3562. synchronize_srcu(&ctrl->srcu);
  3563. list_add_tail_rcu(&ns->list, &rm_list);
  3564. }
  3565. }
  3566. mutex_unlock(&ctrl->namespaces_lock);
  3567. list_for_each_entry_safe(ns, next, &rm_list, list)
  3568. nvme_ns_remove(ns);
  3569. }
  3570. static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
  3571. {
  3572. const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
  3573. __le32 *ns_list;
  3574. u32 prev = 0;
  3575. int ret = 0, i;
  3576. ASYNC_DOMAIN(domain);
  3577. struct async_scan_info scan_info;
  3578. ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
  3579. if (!ns_list)
  3580. return -ENOMEM;
  3581. scan_info.ctrl = ctrl;
  3582. scan_info.ns_list = ns_list;
  3583. for (;;) {
  3584. struct nvme_command cmd = {
  3585. .identify.opcode = nvme_admin_identify,
  3586. .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST,
  3587. .identify.nsid = cpu_to_le32(prev),
  3588. };
  3589. ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
  3590. NVME_IDENTIFY_DATA_SIZE);
  3591. if (ret) {
  3592. dev_warn(ctrl->device,
  3593. "Identify NS List failed (status=0x%x)\n", ret);
  3594. goto free;
  3595. }
  3596. atomic_set(&scan_info.next_nsid, 0);
  3597. for (i = 0; i < nr_entries; i++) {
  3598. u32 nsid = le32_to_cpu(ns_list[i]);
  3599. if (!nsid) /* end of the list? */
  3600. goto out;
  3601. async_schedule_domain(nvme_scan_ns_async, &scan_info,
  3602. &domain);
  3603. while (++prev < nsid)
  3604. nvme_ns_remove_by_nsid(ctrl, prev);
  3605. }
  3606. async_synchronize_full_domain(&domain);
  3607. }
  3608. out:
  3609. nvme_remove_invalid_namespaces(ctrl, prev);
  3610. free:
  3611. async_synchronize_full_domain(&domain);
  3612. kfree(ns_list);
  3613. return ret;
  3614. }
  3615. static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
  3616. {
  3617. struct nvme_id_ctrl *id;
  3618. u32 nn, i;
  3619. if (nvme_identify_ctrl(ctrl, &id))
  3620. return;
  3621. nn = le32_to_cpu(id->nn);
  3622. kfree(id);
  3623. for (i = 1; i <= nn; i++)
  3624. nvme_scan_ns(ctrl, i);
  3625. nvme_remove_invalid_namespaces(ctrl, nn);
  3626. }
  3627. static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
  3628. {
  3629. size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
  3630. __le32 *log;
  3631. int error;
  3632. log = kzalloc(log_size, GFP_KERNEL);
  3633. if (!log)
  3634. return;
  3635. /*
  3636. * We need to read the log to clear the AEN, but we don't want to rely
  3637. * on it for the changed namespace information as userspace could have
  3638. * raced with us in reading the log page, which could cause us to miss
  3639. * updates.
  3640. */
  3641. error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
  3642. NVME_CSI_NVM, log, log_size, 0);
  3643. if (error)
  3644. dev_warn(ctrl->device,
  3645. "reading changed ns log failed: %d\n", error);
  3646. kfree(log);
  3647. }
  3648. static void nvme_scan_work(struct work_struct *work)
  3649. {
  3650. struct nvme_ctrl *ctrl =
  3651. container_of(work, struct nvme_ctrl, scan_work);
  3652. int ret;
  3653. /* No tagset on a live ctrl means IO queues could not created */
  3654. if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE || !ctrl->tagset)
  3655. return;
  3656. /*
  3657. * Identify controller limits can change at controller reset due to
  3658. * new firmware download, even though it is not common we cannot ignore
  3659. * such scenario. Controller's non-mdts limits are reported in the unit
  3660. * of logical blocks that is dependent on the format of attached
  3661. * namespace. Hence re-read the limits at the time of ns allocation.
  3662. */
  3663. ret = nvme_init_non_mdts_limits(ctrl);
  3664. if (ret < 0) {
  3665. dev_warn(ctrl->device,
  3666. "reading non-mdts-limits failed: %d\n", ret);
  3667. return;
  3668. }
  3669. if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
  3670. dev_info(ctrl->device, "rescanning namespaces.\n");
  3671. nvme_clear_changed_ns_log(ctrl);
  3672. }
  3673. mutex_lock(&ctrl->scan_lock);
  3674. if (!nvme_id_cns_ok(ctrl, NVME_ID_CNS_NS_ACTIVE_LIST)) {
  3675. nvme_scan_ns_sequential(ctrl);
  3676. } else {
  3677. /*
  3678. * Fall back to sequential scan if DNR is set to handle broken
  3679. * devices which should support Identify NS List (as per the VS
  3680. * they report) but don't actually support it.
  3681. */
  3682. ret = nvme_scan_ns_list(ctrl);
  3683. if (ret > 0 && ret & NVME_STATUS_DNR)
  3684. nvme_scan_ns_sequential(ctrl);
  3685. }
  3686. mutex_unlock(&ctrl->scan_lock);
  3687. /* Requeue if we have missed AENs */
  3688. if (test_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events))
  3689. nvme_queue_scan(ctrl);
  3690. #ifdef CONFIG_NVME_MULTIPATH
  3691. else if (ctrl->ana_log_buf)
  3692. /* Re-read the ANA log page to not miss updates */
  3693. queue_work(nvme_wq, &ctrl->ana_work);
  3694. #endif
  3695. }
  3696. /*
  3697. * This function iterates the namespace list unlocked to allow recovery from
  3698. * controller failure. It is up to the caller to ensure the namespace list is
  3699. * not modified by scan work while this function is executing.
  3700. */
  3701. void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
  3702. {
  3703. struct nvme_ns *ns, *next;
  3704. LIST_HEAD(ns_list);
  3705. /*
  3706. * make sure to requeue I/O to all namespaces as these
  3707. * might result from the scan itself and must complete
  3708. * for the scan_work to make progress
  3709. */
  3710. nvme_mpath_clear_ctrl_paths(ctrl);
  3711. /*
  3712. * Unquiesce io queues so any pending IO won't hang, especially
  3713. * those submitted from scan work
  3714. */
  3715. nvme_unquiesce_io_queues(ctrl);
  3716. /* prevent racing with ns scanning */
  3717. flush_work(&ctrl->scan_work);
  3718. /*
  3719. * The dead states indicates the controller was not gracefully
  3720. * disconnected. In that case, we won't be able to flush any data while
  3721. * removing the namespaces' disks; fail all the queues now to avoid
  3722. * potentially having to clean up the failed sync later.
  3723. */
  3724. if (nvme_ctrl_state(ctrl) == NVME_CTRL_DEAD)
  3725. nvme_mark_namespaces_dead(ctrl);
  3726. /* this is a no-op when called from the controller reset handler */
  3727. nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
  3728. mutex_lock(&ctrl->namespaces_lock);
  3729. list_splice_init_rcu(&ctrl->namespaces, &ns_list, synchronize_rcu);
  3730. mutex_unlock(&ctrl->namespaces_lock);
  3731. synchronize_srcu(&ctrl->srcu);
  3732. list_for_each_entry_safe(ns, next, &ns_list, list)
  3733. nvme_ns_remove(ns);
  3734. }
  3735. EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
  3736. static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env)
  3737. {
  3738. const struct nvme_ctrl *ctrl =
  3739. container_of(dev, struct nvme_ctrl, ctrl_device);
  3740. struct nvmf_ctrl_options *opts = ctrl->opts;
  3741. int ret;
  3742. ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
  3743. if (ret)
  3744. return ret;
  3745. if (opts) {
  3746. ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
  3747. if (ret)
  3748. return ret;
  3749. ret = add_uevent_var(env, "NVME_TRSVCID=%s",
  3750. opts->trsvcid ?: "none");
  3751. if (ret)
  3752. return ret;
  3753. ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
  3754. opts->host_traddr ?: "none");
  3755. if (ret)
  3756. return ret;
  3757. ret = add_uevent_var(env, "NVME_HOST_IFACE=%s",
  3758. opts->host_iface ?: "none");
  3759. }
  3760. return ret;
  3761. }
  3762. static void nvme_change_uevent(struct nvme_ctrl *ctrl, char *envdata)
  3763. {
  3764. char *envp[2] = { envdata, NULL };
  3765. kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
  3766. }
  3767. static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
  3768. {
  3769. char *envp[2] = { NULL, NULL };
  3770. u32 aen_result = ctrl->aen_result;
  3771. ctrl->aen_result = 0;
  3772. if (!aen_result)
  3773. return;
  3774. envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
  3775. if (!envp[0])
  3776. return;
  3777. kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
  3778. kfree(envp[0]);
  3779. }
  3780. static void nvme_async_event_work(struct work_struct *work)
  3781. {
  3782. struct nvme_ctrl *ctrl =
  3783. container_of(work, struct nvme_ctrl, async_event_work);
  3784. nvme_aen_uevent(ctrl);
  3785. /*
  3786. * The transport drivers must guarantee AER submission here is safe by
  3787. * flushing ctrl async_event_work after changing the controller state
  3788. * from LIVE and before freeing the admin queue.
  3789. */
  3790. if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
  3791. ctrl->ops->submit_async_event(ctrl);
  3792. }
  3793. static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
  3794. {
  3795. u32 csts;
  3796. if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
  3797. return false;
  3798. if (csts == ~0)
  3799. return false;
  3800. return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
  3801. }
  3802. static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
  3803. {
  3804. struct nvme_fw_slot_info_log *log;
  3805. u8 next_fw_slot, cur_fw_slot;
  3806. log = kmalloc(sizeof(*log), GFP_KERNEL);
  3807. if (!log)
  3808. return;
  3809. if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
  3810. log, sizeof(*log), 0)) {
  3811. dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
  3812. goto out_free_log;
  3813. }
  3814. cur_fw_slot = log->afi & 0x7;
  3815. next_fw_slot = (log->afi & 0x70) >> 4;
  3816. if (!cur_fw_slot || (next_fw_slot && (cur_fw_slot != next_fw_slot))) {
  3817. dev_info(ctrl->device,
  3818. "Firmware is activated after next Controller Level Reset\n");
  3819. goto out_free_log;
  3820. }
  3821. memcpy(ctrl->subsys->firmware_rev, &log->frs[cur_fw_slot - 1],
  3822. sizeof(ctrl->subsys->firmware_rev));
  3823. out_free_log:
  3824. kfree(log);
  3825. }
  3826. static void nvme_fw_act_work(struct work_struct *work)
  3827. {
  3828. struct nvme_ctrl *ctrl = container_of(work,
  3829. struct nvme_ctrl, fw_act_work);
  3830. unsigned long fw_act_timeout;
  3831. nvme_auth_stop(ctrl);
  3832. if (ctrl->mtfa)
  3833. fw_act_timeout = jiffies +
  3834. msecs_to_jiffies(ctrl->mtfa * 100);
  3835. else
  3836. fw_act_timeout = jiffies +
  3837. msecs_to_jiffies(admin_timeout * 1000);
  3838. nvme_quiesce_io_queues(ctrl);
  3839. while (nvme_ctrl_pp_status(ctrl)) {
  3840. if (time_after(jiffies, fw_act_timeout)) {
  3841. dev_warn(ctrl->device,
  3842. "Fw activation timeout, reset controller\n");
  3843. nvme_try_sched_reset(ctrl);
  3844. return;
  3845. }
  3846. msleep(100);
  3847. }
  3848. if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING) ||
  3849. !nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
  3850. return;
  3851. nvme_unquiesce_io_queues(ctrl);
  3852. /* read FW slot information to clear the AER */
  3853. nvme_get_fw_slot_info(ctrl);
  3854. queue_work(nvme_wq, &ctrl->async_event_work);
  3855. }
  3856. static u32 nvme_aer_type(u32 result)
  3857. {
  3858. return result & 0x7;
  3859. }
  3860. static u32 nvme_aer_subtype(u32 result)
  3861. {
  3862. return (result & 0xff00) >> 8;
  3863. }
  3864. static bool nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
  3865. {
  3866. u32 aer_notice_type = nvme_aer_subtype(result);
  3867. bool requeue = true;
  3868. switch (aer_notice_type) {
  3869. case NVME_AER_NOTICE_NS_CHANGED:
  3870. set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
  3871. nvme_queue_scan(ctrl);
  3872. break;
  3873. case NVME_AER_NOTICE_FW_ACT_STARTING:
  3874. /*
  3875. * We are (ab)using the RESETTING state to prevent subsequent
  3876. * recovery actions from interfering with the controller's
  3877. * firmware activation.
  3878. */
  3879. if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) {
  3880. requeue = false;
  3881. queue_work(nvme_wq, &ctrl->fw_act_work);
  3882. }
  3883. break;
  3884. #ifdef CONFIG_NVME_MULTIPATH
  3885. case NVME_AER_NOTICE_ANA:
  3886. if (!ctrl->ana_log_buf)
  3887. break;
  3888. queue_work(nvme_wq, &ctrl->ana_work);
  3889. break;
  3890. #endif
  3891. case NVME_AER_NOTICE_DISC_CHANGED:
  3892. ctrl->aen_result = result;
  3893. break;
  3894. default:
  3895. dev_warn(ctrl->device, "async event result %08x\n", result);
  3896. }
  3897. return requeue;
  3898. }
  3899. static void nvme_handle_aer_persistent_error(struct nvme_ctrl *ctrl)
  3900. {
  3901. dev_warn(ctrl->device,
  3902. "resetting controller due to persistent internal error\n");
  3903. nvme_reset_ctrl(ctrl);
  3904. }
  3905. void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
  3906. volatile union nvme_result *res)
  3907. {
  3908. u32 result = le32_to_cpu(res->u32);
  3909. u32 aer_type = nvme_aer_type(result);
  3910. u32 aer_subtype = nvme_aer_subtype(result);
  3911. bool requeue = true;
  3912. if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
  3913. return;
  3914. trace_nvme_async_event(ctrl, result);
  3915. switch (aer_type) {
  3916. case NVME_AER_NOTICE:
  3917. requeue = nvme_handle_aen_notice(ctrl, result);
  3918. break;
  3919. case NVME_AER_ERROR:
  3920. /*
  3921. * For a persistent internal error, don't run async_event_work
  3922. * to submit a new AER. The controller reset will do it.
  3923. */
  3924. if (aer_subtype == NVME_AER_ERROR_PERSIST_INT_ERR) {
  3925. nvme_handle_aer_persistent_error(ctrl);
  3926. return;
  3927. }
  3928. fallthrough;
  3929. case NVME_AER_SMART:
  3930. case NVME_AER_CSS:
  3931. case NVME_AER_VS:
  3932. ctrl->aen_result = result;
  3933. break;
  3934. default:
  3935. break;
  3936. }
  3937. if (requeue)
  3938. queue_work(nvme_wq, &ctrl->async_event_work);
  3939. }
  3940. EXPORT_SYMBOL_GPL(nvme_complete_async_event);
  3941. int nvme_alloc_admin_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
  3942. const struct blk_mq_ops *ops, unsigned int cmd_size)
  3943. {
  3944. struct queue_limits lim = {};
  3945. int ret;
  3946. memset(set, 0, sizeof(*set));
  3947. set->ops = ops;
  3948. set->queue_depth = NVME_AQ_MQ_TAG_DEPTH;
  3949. if (ctrl->ops->flags & NVME_F_FABRICS)
  3950. /* Reserved for fabric connect and keep alive */
  3951. set->reserved_tags = 2;
  3952. set->numa_node = ctrl->numa_node;
  3953. set->flags = BLK_MQ_F_NO_SCHED;
  3954. if (ctrl->ops->flags & NVME_F_BLOCKING)
  3955. set->flags |= BLK_MQ_F_BLOCKING;
  3956. set->cmd_size = cmd_size;
  3957. set->driver_data = ctrl;
  3958. set->nr_hw_queues = 1;
  3959. set->timeout = NVME_ADMIN_TIMEOUT;
  3960. ret = blk_mq_alloc_tag_set(set);
  3961. if (ret)
  3962. return ret;
  3963. ctrl->admin_q = blk_mq_alloc_queue(set, &lim, NULL);
  3964. if (IS_ERR(ctrl->admin_q)) {
  3965. ret = PTR_ERR(ctrl->admin_q);
  3966. goto out_free_tagset;
  3967. }
  3968. if (ctrl->ops->flags & NVME_F_FABRICS) {
  3969. ctrl->fabrics_q = blk_mq_alloc_queue(set, NULL, NULL);
  3970. if (IS_ERR(ctrl->fabrics_q)) {
  3971. ret = PTR_ERR(ctrl->fabrics_q);
  3972. goto out_cleanup_admin_q;
  3973. }
  3974. }
  3975. ctrl->admin_tagset = set;
  3976. return 0;
  3977. out_cleanup_admin_q:
  3978. blk_mq_destroy_queue(ctrl->admin_q);
  3979. blk_put_queue(ctrl->admin_q);
  3980. out_free_tagset:
  3981. blk_mq_free_tag_set(set);
  3982. ctrl->admin_q = NULL;
  3983. ctrl->fabrics_q = NULL;
  3984. return ret;
  3985. }
  3986. EXPORT_SYMBOL_GPL(nvme_alloc_admin_tag_set);
  3987. void nvme_remove_admin_tag_set(struct nvme_ctrl *ctrl)
  3988. {
  3989. /*
  3990. * As we're about to destroy the queue and free tagset
  3991. * we can not have keep-alive work running.
  3992. */
  3993. nvme_stop_keep_alive(ctrl);
  3994. blk_mq_destroy_queue(ctrl->admin_q);
  3995. blk_put_queue(ctrl->admin_q);
  3996. if (ctrl->ops->flags & NVME_F_FABRICS) {
  3997. blk_mq_destroy_queue(ctrl->fabrics_q);
  3998. blk_put_queue(ctrl->fabrics_q);
  3999. }
  4000. blk_mq_free_tag_set(ctrl->admin_tagset);
  4001. }
  4002. EXPORT_SYMBOL_GPL(nvme_remove_admin_tag_set);
  4003. int nvme_alloc_io_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
  4004. const struct blk_mq_ops *ops, unsigned int nr_maps,
  4005. unsigned int cmd_size)
  4006. {
  4007. int ret;
  4008. memset(set, 0, sizeof(*set));
  4009. set->ops = ops;
  4010. set->queue_depth = min_t(unsigned, ctrl->sqsize, BLK_MQ_MAX_DEPTH - 1);
  4011. /*
  4012. * Some Apple controllers requires tags to be unique across admin and
  4013. * the (only) I/O queue, so reserve the first 32 tags of the I/O queue.
  4014. */
  4015. if (ctrl->quirks & NVME_QUIRK_SHARED_TAGS)
  4016. set->reserved_tags = NVME_AQ_DEPTH;
  4017. else if (ctrl->ops->flags & NVME_F_FABRICS)
  4018. /* Reserved for fabric connect */
  4019. set->reserved_tags = 1;
  4020. set->numa_node = ctrl->numa_node;
  4021. set->flags = BLK_MQ_F_SHOULD_MERGE;
  4022. if (ctrl->ops->flags & NVME_F_BLOCKING)
  4023. set->flags |= BLK_MQ_F_BLOCKING;
  4024. set->cmd_size = cmd_size;
  4025. set->driver_data = ctrl;
  4026. set->nr_hw_queues = ctrl->queue_count - 1;
  4027. set->timeout = NVME_IO_TIMEOUT;
  4028. set->nr_maps = nr_maps;
  4029. ret = blk_mq_alloc_tag_set(set);
  4030. if (ret)
  4031. return ret;
  4032. if (ctrl->ops->flags & NVME_F_FABRICS) {
  4033. struct queue_limits lim = {
  4034. .features = BLK_FEAT_SKIP_TAGSET_QUIESCE,
  4035. };
  4036. ctrl->connect_q = blk_mq_alloc_queue(set, &lim, NULL);
  4037. if (IS_ERR(ctrl->connect_q)) {
  4038. ret = PTR_ERR(ctrl->connect_q);
  4039. goto out_free_tag_set;
  4040. }
  4041. }
  4042. ctrl->tagset = set;
  4043. return 0;
  4044. out_free_tag_set:
  4045. blk_mq_free_tag_set(set);
  4046. ctrl->connect_q = NULL;
  4047. return ret;
  4048. }
  4049. EXPORT_SYMBOL_GPL(nvme_alloc_io_tag_set);
  4050. void nvme_remove_io_tag_set(struct nvme_ctrl *ctrl)
  4051. {
  4052. if (ctrl->ops->flags & NVME_F_FABRICS) {
  4053. blk_mq_destroy_queue(ctrl->connect_q);
  4054. blk_put_queue(ctrl->connect_q);
  4055. }
  4056. blk_mq_free_tag_set(ctrl->tagset);
  4057. }
  4058. EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set);
  4059. void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
  4060. {
  4061. nvme_mpath_stop(ctrl);
  4062. nvme_auth_stop(ctrl);
  4063. nvme_stop_failfast_work(ctrl);
  4064. flush_work(&ctrl->async_event_work);
  4065. cancel_work_sync(&ctrl->fw_act_work);
  4066. if (ctrl->ops->stop_ctrl)
  4067. ctrl->ops->stop_ctrl(ctrl);
  4068. }
  4069. EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
  4070. void nvme_start_ctrl(struct nvme_ctrl *ctrl)
  4071. {
  4072. nvme_enable_aen(ctrl);
  4073. /*
  4074. * persistent discovery controllers need to send indication to userspace
  4075. * to re-read the discovery log page to learn about possible changes
  4076. * that were missed. We identify persistent discovery controllers by
  4077. * checking that they started once before, hence are reconnecting back.
  4078. */
  4079. if (test_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags) &&
  4080. nvme_discovery_ctrl(ctrl))
  4081. nvme_change_uevent(ctrl, "NVME_EVENT=rediscover");
  4082. if (ctrl->queue_count > 1) {
  4083. nvme_queue_scan(ctrl);
  4084. nvme_unquiesce_io_queues(ctrl);
  4085. nvme_mpath_update(ctrl);
  4086. }
  4087. nvme_change_uevent(ctrl, "NVME_EVENT=connected");
  4088. set_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags);
  4089. }
  4090. EXPORT_SYMBOL_GPL(nvme_start_ctrl);
  4091. void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
  4092. {
  4093. nvme_stop_keep_alive(ctrl);
  4094. nvme_hwmon_exit(ctrl);
  4095. nvme_fault_inject_fini(&ctrl->fault_inject);
  4096. dev_pm_qos_hide_latency_tolerance(ctrl->device);
  4097. cdev_device_del(&ctrl->cdev, ctrl->device);
  4098. nvme_put_ctrl(ctrl);
  4099. }
  4100. EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
  4101. static void nvme_free_cels(struct nvme_ctrl *ctrl)
  4102. {
  4103. struct nvme_effects_log *cel;
  4104. unsigned long i;
  4105. xa_for_each(&ctrl->cels, i, cel) {
  4106. xa_erase(&ctrl->cels, i);
  4107. kfree(cel);
  4108. }
  4109. xa_destroy(&ctrl->cels);
  4110. }
  4111. static void nvme_free_ctrl(struct device *dev)
  4112. {
  4113. struct nvme_ctrl *ctrl =
  4114. container_of(dev, struct nvme_ctrl, ctrl_device);
  4115. struct nvme_subsystem *subsys = ctrl->subsys;
  4116. if (!subsys || ctrl->instance != subsys->instance)
  4117. ida_free(&nvme_instance_ida, ctrl->instance);
  4118. nvme_free_cels(ctrl);
  4119. nvme_mpath_uninit(ctrl);
  4120. cleanup_srcu_struct(&ctrl->srcu);
  4121. nvme_auth_stop(ctrl);
  4122. nvme_auth_free(ctrl);
  4123. __free_page(ctrl->discard_page);
  4124. free_opal_dev(ctrl->opal_dev);
  4125. if (subsys) {
  4126. mutex_lock(&nvme_subsystems_lock);
  4127. list_del(&ctrl->subsys_entry);
  4128. sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
  4129. mutex_unlock(&nvme_subsystems_lock);
  4130. }
  4131. ctrl->ops->free_ctrl(ctrl);
  4132. if (subsys)
  4133. nvme_put_subsystem(subsys);
  4134. }
  4135. /*
  4136. * Initialize a NVMe controller structures. This needs to be called during
  4137. * earliest initialization so that we have the initialized structured around
  4138. * during probing.
  4139. *
  4140. * On success, the caller must use the nvme_put_ctrl() to release this when
  4141. * needed, which also invokes the ops->free_ctrl() callback.
  4142. */
  4143. int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
  4144. const struct nvme_ctrl_ops *ops, unsigned long quirks)
  4145. {
  4146. int ret;
  4147. WRITE_ONCE(ctrl->state, NVME_CTRL_NEW);
  4148. ctrl->passthru_err_log_enabled = false;
  4149. clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
  4150. spin_lock_init(&ctrl->lock);
  4151. mutex_init(&ctrl->namespaces_lock);
  4152. ret = init_srcu_struct(&ctrl->srcu);
  4153. if (ret)
  4154. return ret;
  4155. mutex_init(&ctrl->scan_lock);
  4156. INIT_LIST_HEAD(&ctrl->namespaces);
  4157. xa_init(&ctrl->cels);
  4158. ctrl->dev = dev;
  4159. ctrl->ops = ops;
  4160. ctrl->quirks = quirks;
  4161. ctrl->numa_node = NUMA_NO_NODE;
  4162. INIT_WORK(&ctrl->scan_work, nvme_scan_work);
  4163. INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
  4164. INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
  4165. INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
  4166. init_waitqueue_head(&ctrl->state_wq);
  4167. INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
  4168. INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
  4169. memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
  4170. ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
  4171. ctrl->ka_last_check_time = jiffies;
  4172. BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
  4173. PAGE_SIZE);
  4174. ctrl->discard_page = alloc_page(GFP_KERNEL);
  4175. if (!ctrl->discard_page) {
  4176. ret = -ENOMEM;
  4177. goto out;
  4178. }
  4179. ret = ida_alloc(&nvme_instance_ida, GFP_KERNEL);
  4180. if (ret < 0)
  4181. goto out;
  4182. ctrl->instance = ret;
  4183. ret = nvme_auth_init_ctrl(ctrl);
  4184. if (ret)
  4185. goto out_release_instance;
  4186. nvme_mpath_init_ctrl(ctrl);
  4187. device_initialize(&ctrl->ctrl_device);
  4188. ctrl->device = &ctrl->ctrl_device;
  4189. ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
  4190. ctrl->instance);
  4191. ctrl->device->class = &nvme_class;
  4192. ctrl->device->parent = ctrl->dev;
  4193. if (ops->dev_attr_groups)
  4194. ctrl->device->groups = ops->dev_attr_groups;
  4195. else
  4196. ctrl->device->groups = nvme_dev_attr_groups;
  4197. ctrl->device->release = nvme_free_ctrl;
  4198. dev_set_drvdata(ctrl->device, ctrl);
  4199. return ret;
  4200. out_release_instance:
  4201. ida_free(&nvme_instance_ida, ctrl->instance);
  4202. out:
  4203. if (ctrl->discard_page)
  4204. __free_page(ctrl->discard_page);
  4205. cleanup_srcu_struct(&ctrl->srcu);
  4206. return ret;
  4207. }
  4208. EXPORT_SYMBOL_GPL(nvme_init_ctrl);
  4209. /*
  4210. * On success, returns with an elevated controller reference and caller must
  4211. * use nvme_uninit_ctrl() to properly free resources associated with the ctrl.
  4212. */
  4213. int nvme_add_ctrl(struct nvme_ctrl *ctrl)
  4214. {
  4215. int ret;
  4216. ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
  4217. if (ret)
  4218. return ret;
  4219. cdev_init(&ctrl->cdev, &nvme_dev_fops);
  4220. ctrl->cdev.owner = ctrl->ops->module;
  4221. ret = cdev_device_add(&ctrl->cdev, ctrl->device);
  4222. if (ret)
  4223. return ret;
  4224. /*
  4225. * Initialize latency tolerance controls. The sysfs files won't
  4226. * be visible to userspace unless the device actually supports APST.
  4227. */
  4228. ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
  4229. dev_pm_qos_update_user_latency_tolerance(ctrl->device,
  4230. min(default_ps_max_latency_us, (unsigned long)S32_MAX));
  4231. nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
  4232. nvme_get_ctrl(ctrl);
  4233. return 0;
  4234. }
  4235. EXPORT_SYMBOL_GPL(nvme_add_ctrl);
  4236. /* let I/O to all namespaces fail in preparation for surprise removal */
  4237. void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl)
  4238. {
  4239. struct nvme_ns *ns;
  4240. int srcu_idx;
  4241. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4242. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4243. srcu_read_lock_held(&ctrl->srcu))
  4244. blk_mark_disk_dead(ns->disk);
  4245. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4246. }
  4247. EXPORT_SYMBOL_GPL(nvme_mark_namespaces_dead);
  4248. void nvme_unfreeze(struct nvme_ctrl *ctrl)
  4249. {
  4250. struct nvme_ns *ns;
  4251. int srcu_idx;
  4252. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4253. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4254. srcu_read_lock_held(&ctrl->srcu))
  4255. blk_mq_unfreeze_queue(ns->queue);
  4256. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4257. clear_bit(NVME_CTRL_FROZEN, &ctrl->flags);
  4258. }
  4259. EXPORT_SYMBOL_GPL(nvme_unfreeze);
  4260. int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
  4261. {
  4262. struct nvme_ns *ns;
  4263. int srcu_idx;
  4264. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4265. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4266. srcu_read_lock_held(&ctrl->srcu)) {
  4267. timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
  4268. if (timeout <= 0)
  4269. break;
  4270. }
  4271. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4272. return timeout;
  4273. }
  4274. EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
  4275. void nvme_wait_freeze(struct nvme_ctrl *ctrl)
  4276. {
  4277. struct nvme_ns *ns;
  4278. int srcu_idx;
  4279. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4280. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4281. srcu_read_lock_held(&ctrl->srcu))
  4282. blk_mq_freeze_queue_wait(ns->queue);
  4283. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4284. }
  4285. EXPORT_SYMBOL_GPL(nvme_wait_freeze);
  4286. void nvme_start_freeze(struct nvme_ctrl *ctrl)
  4287. {
  4288. struct nvme_ns *ns;
  4289. int srcu_idx;
  4290. set_bit(NVME_CTRL_FROZEN, &ctrl->flags);
  4291. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4292. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4293. srcu_read_lock_held(&ctrl->srcu))
  4294. blk_freeze_queue_start(ns->queue);
  4295. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4296. }
  4297. EXPORT_SYMBOL_GPL(nvme_start_freeze);
  4298. void nvme_quiesce_io_queues(struct nvme_ctrl *ctrl)
  4299. {
  4300. if (!ctrl->tagset)
  4301. return;
  4302. if (!test_and_set_bit(NVME_CTRL_STOPPED, &ctrl->flags))
  4303. blk_mq_quiesce_tagset(ctrl->tagset);
  4304. else
  4305. blk_mq_wait_quiesce_done(ctrl->tagset);
  4306. }
  4307. EXPORT_SYMBOL_GPL(nvme_quiesce_io_queues);
  4308. void nvme_unquiesce_io_queues(struct nvme_ctrl *ctrl)
  4309. {
  4310. if (!ctrl->tagset)
  4311. return;
  4312. if (test_and_clear_bit(NVME_CTRL_STOPPED, &ctrl->flags))
  4313. blk_mq_unquiesce_tagset(ctrl->tagset);
  4314. }
  4315. EXPORT_SYMBOL_GPL(nvme_unquiesce_io_queues);
  4316. void nvme_quiesce_admin_queue(struct nvme_ctrl *ctrl)
  4317. {
  4318. if (!test_and_set_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
  4319. blk_mq_quiesce_queue(ctrl->admin_q);
  4320. else
  4321. blk_mq_wait_quiesce_done(ctrl->admin_q->tag_set);
  4322. }
  4323. EXPORT_SYMBOL_GPL(nvme_quiesce_admin_queue);
  4324. void nvme_unquiesce_admin_queue(struct nvme_ctrl *ctrl)
  4325. {
  4326. if (test_and_clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
  4327. blk_mq_unquiesce_queue(ctrl->admin_q);
  4328. }
  4329. EXPORT_SYMBOL_GPL(nvme_unquiesce_admin_queue);
  4330. void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
  4331. {
  4332. struct nvme_ns *ns;
  4333. int srcu_idx;
  4334. srcu_idx = srcu_read_lock(&ctrl->srcu);
  4335. list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
  4336. srcu_read_lock_held(&ctrl->srcu))
  4337. blk_sync_queue(ns->queue);
  4338. srcu_read_unlock(&ctrl->srcu, srcu_idx);
  4339. }
  4340. EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
  4341. void nvme_sync_queues(struct nvme_ctrl *ctrl)
  4342. {
  4343. nvme_sync_io_queues(ctrl);
  4344. if (ctrl->admin_q)
  4345. blk_sync_queue(ctrl->admin_q);
  4346. }
  4347. EXPORT_SYMBOL_GPL(nvme_sync_queues);
  4348. struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
  4349. {
  4350. if (file->f_op != &nvme_dev_fops)
  4351. return NULL;
  4352. return file->private_data;
  4353. }
  4354. EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU);
  4355. /*
  4356. * Check we didn't inadvertently grow the command structure sizes:
  4357. */
  4358. static inline void _nvme_check_size(void)
  4359. {
  4360. BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
  4361. BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
  4362. BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
  4363. BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
  4364. BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
  4365. BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
  4366. BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
  4367. BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
  4368. BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
  4369. BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
  4370. BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
  4371. BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
  4372. BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
  4373. BUILD_BUG_ON(sizeof(struct nvme_id_ns_cs_indep) !=
  4374. NVME_IDENTIFY_DATA_SIZE);
  4375. BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
  4376. BUILD_BUG_ON(sizeof(struct nvme_id_ns_nvm) != NVME_IDENTIFY_DATA_SIZE);
  4377. BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
  4378. BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
  4379. BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
  4380. BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
  4381. BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
  4382. BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
  4383. BUILD_BUG_ON(sizeof(struct nvme_feat_host_behavior) != 512);
  4384. }
  4385. static int __init nvme_core_init(void)
  4386. {
  4387. int result = -ENOMEM;
  4388. _nvme_check_size();
  4389. nvme_wq = alloc_workqueue("nvme-wq",
  4390. WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
  4391. if (!nvme_wq)
  4392. goto out;
  4393. nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
  4394. WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
  4395. if (!nvme_reset_wq)
  4396. goto destroy_wq;
  4397. nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
  4398. WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
  4399. if (!nvme_delete_wq)
  4400. goto destroy_reset_wq;
  4401. result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
  4402. NVME_MINORS, "nvme");
  4403. if (result < 0)
  4404. goto destroy_delete_wq;
  4405. result = class_register(&nvme_class);
  4406. if (result)
  4407. goto unregister_chrdev;
  4408. result = class_register(&nvme_subsys_class);
  4409. if (result)
  4410. goto destroy_class;
  4411. result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
  4412. "nvme-generic");
  4413. if (result < 0)
  4414. goto destroy_subsys_class;
  4415. result = class_register(&nvme_ns_chr_class);
  4416. if (result)
  4417. goto unregister_generic_ns;
  4418. result = nvme_init_auth();
  4419. if (result)
  4420. goto destroy_ns_chr;
  4421. return 0;
  4422. destroy_ns_chr:
  4423. class_unregister(&nvme_ns_chr_class);
  4424. unregister_generic_ns:
  4425. unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
  4426. destroy_subsys_class:
  4427. class_unregister(&nvme_subsys_class);
  4428. destroy_class:
  4429. class_unregister(&nvme_class);
  4430. unregister_chrdev:
  4431. unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
  4432. destroy_delete_wq:
  4433. destroy_workqueue(nvme_delete_wq);
  4434. destroy_reset_wq:
  4435. destroy_workqueue(nvme_reset_wq);
  4436. destroy_wq:
  4437. destroy_workqueue(nvme_wq);
  4438. out:
  4439. return result;
  4440. }
  4441. static void __exit nvme_core_exit(void)
  4442. {
  4443. nvme_exit_auth();
  4444. class_unregister(&nvme_ns_chr_class);
  4445. class_unregister(&nvme_subsys_class);
  4446. class_unregister(&nvme_class);
  4447. unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
  4448. unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
  4449. destroy_workqueue(nvme_delete_wq);
  4450. destroy_workqueue(nvme_reset_wq);
  4451. destroy_workqueue(nvme_wq);
  4452. ida_destroy(&nvme_ns_chr_minor_ida);
  4453. ida_destroy(&nvme_instance_ida);
  4454. }
  4455. MODULE_LICENSE("GPL");
  4456. MODULE_VERSION("1.0");
  4457. MODULE_DESCRIPTION("NVMe host core framework");
  4458. module_init(nvme_core_init);
  4459. module_exit(nvme_core_exit);