core.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723
  1. /*
  2. * NVM Express device driver
  3. * Copyright (c) 2011-2014, Intel Corporation.
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms and conditions of the GNU General Public License,
  7. * version 2, as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  12. * more details.
  13. */
  14. #include <linux/blkdev.h>
  15. #include <linux/blk-mq.h>
  16. #include <linux/delay.h>
  17. #include <linux/errno.h>
  18. #include <linux/hdreg.h>
  19. #include <linux/kernel.h>
  20. #include <linux/module.h>
  21. #include <linux/list_sort.h>
  22. #include <linux/slab.h>
  23. #include <linux/types.h>
  24. #include <linux/pr.h>
  25. #include <linux/ptrace.h>
  26. #include <linux/nvme_ioctl.h>
  27. #include <linux/t10-pi.h>
  28. #include <linux/pm_qos.h>
  29. #include <scsi/sg.h>
  30. #include <asm/unaligned.h>
  31. #include "nvme.h"
  32. #include "fabrics.h"
  33. #define NVME_MINORS (1U << MINORBITS)
  34. unsigned char admin_timeout = 60;
  35. module_param(admin_timeout, byte, 0644);
  36. MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
  37. EXPORT_SYMBOL_GPL(admin_timeout);
  38. unsigned char nvme_io_timeout = 30;
  39. module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
  40. MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
  41. EXPORT_SYMBOL_GPL(nvme_io_timeout);
  42. static unsigned char shutdown_timeout = 5;
  43. module_param(shutdown_timeout, byte, 0644);
  44. MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
  45. static u8 nvme_max_retries = 5;
  46. module_param_named(max_retries, nvme_max_retries, byte, 0644);
  47. MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
  48. static int nvme_char_major;
  49. module_param(nvme_char_major, int, 0);
  50. static unsigned long default_ps_max_latency_us = 100000;
  51. module_param(default_ps_max_latency_us, ulong, 0644);
  52. MODULE_PARM_DESC(default_ps_max_latency_us,
  53. "max power saving latency for new devices; use PM QOS to change per device");
  54. static bool force_apst;
  55. module_param(force_apst, bool, 0644);
  56. MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
  57. struct workqueue_struct *nvme_wq;
  58. EXPORT_SYMBOL_GPL(nvme_wq);
  59. static LIST_HEAD(nvme_ctrl_list);
  60. static DEFINE_SPINLOCK(dev_list_lock);
  61. static struct class *nvme_class;
  62. int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
  63. {
  64. if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
  65. return -EBUSY;
  66. if (!queue_work(nvme_wq, &ctrl->reset_work))
  67. return -EBUSY;
  68. return 0;
  69. }
  70. EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
  71. static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
  72. {
  73. int ret;
  74. ret = nvme_reset_ctrl(ctrl);
  75. if (!ret)
  76. flush_work(&ctrl->reset_work);
  77. return ret;
  78. }
  79. static blk_status_t nvme_error_status(struct request *req)
  80. {
  81. switch (nvme_req(req)->status & 0x7ff) {
  82. case NVME_SC_SUCCESS:
  83. return BLK_STS_OK;
  84. case NVME_SC_CAP_EXCEEDED:
  85. return BLK_STS_NOSPC;
  86. case NVME_SC_ONCS_NOT_SUPPORTED:
  87. return BLK_STS_NOTSUPP;
  88. case NVME_SC_WRITE_FAULT:
  89. case NVME_SC_READ_ERROR:
  90. case NVME_SC_UNWRITTEN_BLOCK:
  91. return BLK_STS_MEDIUM;
  92. default:
  93. return BLK_STS_IOERR;
  94. }
  95. }
  96. static inline bool nvme_req_needs_retry(struct request *req)
  97. {
  98. if (blk_noretry_request(req))
  99. return false;
  100. if (nvme_req(req)->status & NVME_SC_DNR)
  101. return false;
  102. if (jiffies - req->start_time >= req->timeout)
  103. return false;
  104. if (nvme_req(req)->retries >= nvme_max_retries)
  105. return false;
  106. return true;
  107. }
  108. void nvme_complete_rq(struct request *req)
  109. {
  110. if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
  111. nvme_req(req)->retries++;
  112. blk_mq_requeue_request(req, !blk_mq_queue_stopped(req->q));
  113. return;
  114. }
  115. blk_mq_end_request(req, nvme_error_status(req));
  116. }
  117. EXPORT_SYMBOL_GPL(nvme_complete_rq);
  118. void nvme_cancel_request(struct request *req, void *data, bool reserved)
  119. {
  120. int status;
  121. if (!blk_mq_request_started(req))
  122. return;
  123. dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
  124. "Cancelling I/O %d", req->tag);
  125. status = NVME_SC_ABORT_REQ;
  126. if (blk_queue_dying(req->q))
  127. status |= NVME_SC_DNR;
  128. nvme_req(req)->status = status;
  129. blk_mq_complete_request(req);
  130. }
  131. EXPORT_SYMBOL_GPL(nvme_cancel_request);
  132. bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
  133. enum nvme_ctrl_state new_state)
  134. {
  135. enum nvme_ctrl_state old_state;
  136. bool changed = false;
  137. spin_lock_irq(&ctrl->lock);
  138. old_state = ctrl->state;
  139. switch (new_state) {
  140. case NVME_CTRL_LIVE:
  141. switch (old_state) {
  142. case NVME_CTRL_NEW:
  143. case NVME_CTRL_RESETTING:
  144. case NVME_CTRL_RECONNECTING:
  145. changed = true;
  146. /* FALLTHRU */
  147. default:
  148. break;
  149. }
  150. break;
  151. case NVME_CTRL_RESETTING:
  152. switch (old_state) {
  153. case NVME_CTRL_NEW:
  154. case NVME_CTRL_LIVE:
  155. changed = true;
  156. /* FALLTHRU */
  157. default:
  158. break;
  159. }
  160. break;
  161. case NVME_CTRL_RECONNECTING:
  162. switch (old_state) {
  163. case NVME_CTRL_LIVE:
  164. changed = true;
  165. /* FALLTHRU */
  166. default:
  167. break;
  168. }
  169. break;
  170. case NVME_CTRL_DELETING:
  171. switch (old_state) {
  172. case NVME_CTRL_LIVE:
  173. case NVME_CTRL_RESETTING:
  174. case NVME_CTRL_RECONNECTING:
  175. changed = true;
  176. /* FALLTHRU */
  177. default:
  178. break;
  179. }
  180. break;
  181. case NVME_CTRL_DEAD:
  182. switch (old_state) {
  183. case NVME_CTRL_DELETING:
  184. changed = true;
  185. /* FALLTHRU */
  186. default:
  187. break;
  188. }
  189. break;
  190. default:
  191. break;
  192. }
  193. if (changed)
  194. ctrl->state = new_state;
  195. spin_unlock_irq(&ctrl->lock);
  196. return changed;
  197. }
  198. EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
  199. static void nvme_free_ns(struct kref *kref)
  200. {
  201. struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
  202. if (ns->ndev)
  203. nvme_nvm_unregister(ns);
  204. if (ns->disk) {
  205. spin_lock(&dev_list_lock);
  206. ns->disk->private_data = NULL;
  207. spin_unlock(&dev_list_lock);
  208. }
  209. put_disk(ns->disk);
  210. ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
  211. nvme_put_ctrl(ns->ctrl);
  212. kfree(ns);
  213. }
  214. static void nvme_put_ns(struct nvme_ns *ns)
  215. {
  216. kref_put(&ns->kref, nvme_free_ns);
  217. }
  218. static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
  219. {
  220. struct nvme_ns *ns;
  221. spin_lock(&dev_list_lock);
  222. ns = disk->private_data;
  223. if (ns) {
  224. if (!kref_get_unless_zero(&ns->kref))
  225. goto fail;
  226. if (!try_module_get(ns->ctrl->ops->module))
  227. goto fail_put_ns;
  228. }
  229. spin_unlock(&dev_list_lock);
  230. return ns;
  231. fail_put_ns:
  232. kref_put(&ns->kref, nvme_free_ns);
  233. fail:
  234. spin_unlock(&dev_list_lock);
  235. return NULL;
  236. }
  237. struct request *nvme_alloc_request(struct request_queue *q,
  238. struct nvme_command *cmd, unsigned int flags, int qid)
  239. {
  240. unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
  241. struct request *req;
  242. if (qid == NVME_QID_ANY) {
  243. req = blk_mq_alloc_request(q, op, flags);
  244. } else {
  245. req = blk_mq_alloc_request_hctx(q, op, flags,
  246. qid ? qid - 1 : 0);
  247. }
  248. if (IS_ERR(req))
  249. return req;
  250. req->cmd_flags |= REQ_FAILFAST_DRIVER;
  251. nvme_req(req)->cmd = cmd;
  252. return req;
  253. }
  254. EXPORT_SYMBOL_GPL(nvme_alloc_request);
  255. static inline void nvme_setup_flush(struct nvme_ns *ns,
  256. struct nvme_command *cmnd)
  257. {
  258. memset(cmnd, 0, sizeof(*cmnd));
  259. cmnd->common.opcode = nvme_cmd_flush;
  260. cmnd->common.nsid = cpu_to_le32(ns->ns_id);
  261. }
  262. static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
  263. struct nvme_command *cmnd)
  264. {
  265. unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
  266. struct nvme_dsm_range *range;
  267. struct bio *bio;
  268. range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
  269. if (!range)
  270. return BLK_STS_RESOURCE;
  271. __rq_for_each_bio(bio, req) {
  272. u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
  273. u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
  274. range[n].cattr = cpu_to_le32(0);
  275. range[n].nlb = cpu_to_le32(nlb);
  276. range[n].slba = cpu_to_le64(slba);
  277. n++;
  278. }
  279. if (WARN_ON_ONCE(n != segments)) {
  280. kfree(range);
  281. return BLK_STS_IOERR;
  282. }
  283. memset(cmnd, 0, sizeof(*cmnd));
  284. cmnd->dsm.opcode = nvme_cmd_dsm;
  285. cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
  286. cmnd->dsm.nr = cpu_to_le32(segments - 1);
  287. cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
  288. req->special_vec.bv_page = virt_to_page(range);
  289. req->special_vec.bv_offset = offset_in_page(range);
  290. req->special_vec.bv_len = sizeof(*range) * segments;
  291. req->rq_flags |= RQF_SPECIAL_PAYLOAD;
  292. return BLK_STS_OK;
  293. }
  294. static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
  295. struct request *req, struct nvme_command *cmnd)
  296. {
  297. u16 control = 0;
  298. u32 dsmgmt = 0;
  299. /*
  300. * If formated with metadata, require the block layer provide a buffer
  301. * unless this namespace is formated such that the metadata can be
  302. * stripped/generated by the controller with PRACT=1.
  303. */
  304. if (ns && ns->ms &&
  305. (!ns->pi_type || ns->ms != sizeof(struct t10_pi_tuple)) &&
  306. !blk_integrity_rq(req) && !blk_rq_is_passthrough(req))
  307. return BLK_STS_NOTSUPP;
  308. if (req->cmd_flags & REQ_FUA)
  309. control |= NVME_RW_FUA;
  310. if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
  311. control |= NVME_RW_LR;
  312. if (req->cmd_flags & REQ_RAHEAD)
  313. dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
  314. memset(cmnd, 0, sizeof(*cmnd));
  315. cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
  316. cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
  317. cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
  318. cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
  319. if (ns->ms) {
  320. switch (ns->pi_type) {
  321. case NVME_NS_DPS_PI_TYPE3:
  322. control |= NVME_RW_PRINFO_PRCHK_GUARD;
  323. break;
  324. case NVME_NS_DPS_PI_TYPE1:
  325. case NVME_NS_DPS_PI_TYPE2:
  326. control |= NVME_RW_PRINFO_PRCHK_GUARD |
  327. NVME_RW_PRINFO_PRCHK_REF;
  328. cmnd->rw.reftag = cpu_to_le32(
  329. nvme_block_nr(ns, blk_rq_pos(req)));
  330. break;
  331. }
  332. if (!blk_integrity_rq(req))
  333. control |= NVME_RW_PRINFO_PRACT;
  334. }
  335. cmnd->rw.control = cpu_to_le16(control);
  336. cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
  337. return 0;
  338. }
  339. blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
  340. struct nvme_command *cmd)
  341. {
  342. blk_status_t ret = BLK_STS_OK;
  343. if (!(req->rq_flags & RQF_DONTPREP)) {
  344. nvme_req(req)->retries = 0;
  345. nvme_req(req)->flags = 0;
  346. req->rq_flags |= RQF_DONTPREP;
  347. }
  348. switch (req_op(req)) {
  349. case REQ_OP_DRV_IN:
  350. case REQ_OP_DRV_OUT:
  351. memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
  352. break;
  353. case REQ_OP_FLUSH:
  354. nvme_setup_flush(ns, cmd);
  355. break;
  356. case REQ_OP_WRITE_ZEROES:
  357. /* currently only aliased to deallocate for a few ctrls: */
  358. case REQ_OP_DISCARD:
  359. ret = nvme_setup_discard(ns, req, cmd);
  360. break;
  361. case REQ_OP_READ:
  362. case REQ_OP_WRITE:
  363. ret = nvme_setup_rw(ns, req, cmd);
  364. break;
  365. default:
  366. WARN_ON_ONCE(1);
  367. return BLK_STS_IOERR;
  368. }
  369. cmd->common.command_id = req->tag;
  370. return ret;
  371. }
  372. EXPORT_SYMBOL_GPL(nvme_setup_cmd);
  373. /*
  374. * Returns 0 on success. If the result is negative, it's a Linux error code;
  375. * if the result is positive, it's an NVM Express status code
  376. */
  377. int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
  378. union nvme_result *result, void *buffer, unsigned bufflen,
  379. unsigned timeout, int qid, int at_head, int flags)
  380. {
  381. struct request *req;
  382. int ret;
  383. req = nvme_alloc_request(q, cmd, flags, qid);
  384. if (IS_ERR(req))
  385. return PTR_ERR(req);
  386. req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
  387. if (buffer && bufflen) {
  388. ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
  389. if (ret)
  390. goto out;
  391. }
  392. blk_execute_rq(req->q, NULL, req, at_head);
  393. if (result)
  394. *result = nvme_req(req)->result;
  395. if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
  396. ret = -EINTR;
  397. else
  398. ret = nvme_req(req)->status;
  399. out:
  400. blk_mq_free_request(req);
  401. return ret;
  402. }
  403. EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
  404. int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
  405. void *buffer, unsigned bufflen)
  406. {
  407. return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
  408. NVME_QID_ANY, 0, 0);
  409. }
  410. EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
  411. int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
  412. void __user *ubuffer, unsigned bufflen,
  413. void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
  414. u32 *result, unsigned timeout)
  415. {
  416. bool write = nvme_is_write(cmd);
  417. struct nvme_ns *ns = q->queuedata;
  418. struct gendisk *disk = ns ? ns->disk : NULL;
  419. struct request *req;
  420. struct bio *bio = NULL;
  421. void *meta = NULL;
  422. int ret;
  423. req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
  424. if (IS_ERR(req))
  425. return PTR_ERR(req);
  426. req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
  427. if (ubuffer && bufflen) {
  428. ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
  429. GFP_KERNEL);
  430. if (ret)
  431. goto out;
  432. bio = req->bio;
  433. if (!disk)
  434. goto submit;
  435. bio->bi_bdev = bdget_disk(disk, 0);
  436. if (!bio->bi_bdev) {
  437. ret = -ENODEV;
  438. goto out_unmap;
  439. }
  440. if (meta_buffer && meta_len) {
  441. struct bio_integrity_payload *bip;
  442. meta = kmalloc(meta_len, GFP_KERNEL);
  443. if (!meta) {
  444. ret = -ENOMEM;
  445. goto out_unmap;
  446. }
  447. if (write) {
  448. if (copy_from_user(meta, meta_buffer,
  449. meta_len)) {
  450. ret = -EFAULT;
  451. goto out_free_meta;
  452. }
  453. }
  454. bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
  455. if (IS_ERR(bip)) {
  456. ret = PTR_ERR(bip);
  457. goto out_free_meta;
  458. }
  459. bip->bip_iter.bi_size = meta_len;
  460. bip->bip_iter.bi_sector = meta_seed;
  461. ret = bio_integrity_add_page(bio, virt_to_page(meta),
  462. meta_len, offset_in_page(meta));
  463. if (ret != meta_len) {
  464. ret = -ENOMEM;
  465. goto out_free_meta;
  466. }
  467. }
  468. }
  469. submit:
  470. blk_execute_rq(req->q, disk, req, 0);
  471. if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
  472. ret = -EINTR;
  473. else
  474. ret = nvme_req(req)->status;
  475. if (result)
  476. *result = le32_to_cpu(nvme_req(req)->result.u32);
  477. if (meta && !ret && !write) {
  478. if (copy_to_user(meta_buffer, meta, meta_len))
  479. ret = -EFAULT;
  480. }
  481. out_free_meta:
  482. kfree(meta);
  483. out_unmap:
  484. if (bio) {
  485. if (disk && bio->bi_bdev)
  486. bdput(bio->bi_bdev);
  487. blk_rq_unmap_user(bio);
  488. }
  489. out:
  490. blk_mq_free_request(req);
  491. return ret;
  492. }
  493. int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
  494. void __user *ubuffer, unsigned bufflen, u32 *result,
  495. unsigned timeout)
  496. {
  497. return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
  498. result, timeout);
  499. }
  500. static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
  501. {
  502. struct nvme_ctrl *ctrl = rq->end_io_data;
  503. blk_mq_free_request(rq);
  504. if (status) {
  505. dev_err(ctrl->device,
  506. "failed nvme_keep_alive_end_io error=%d\n",
  507. status);
  508. return;
  509. }
  510. schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
  511. }
  512. static int nvme_keep_alive(struct nvme_ctrl *ctrl)
  513. {
  514. struct nvme_command c;
  515. struct request *rq;
  516. memset(&c, 0, sizeof(c));
  517. c.common.opcode = nvme_admin_keep_alive;
  518. rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
  519. NVME_QID_ANY);
  520. if (IS_ERR(rq))
  521. return PTR_ERR(rq);
  522. rq->timeout = ctrl->kato * HZ;
  523. rq->end_io_data = ctrl;
  524. blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
  525. return 0;
  526. }
  527. static void nvme_keep_alive_work(struct work_struct *work)
  528. {
  529. struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
  530. struct nvme_ctrl, ka_work);
  531. if (nvme_keep_alive(ctrl)) {
  532. /* allocation failure, reset the controller */
  533. dev_err(ctrl->device, "keep-alive failed\n");
  534. nvme_reset_ctrl(ctrl);
  535. return;
  536. }
  537. }
  538. void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
  539. {
  540. if (unlikely(ctrl->kato == 0))
  541. return;
  542. INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
  543. schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
  544. }
  545. EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
  546. void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
  547. {
  548. if (unlikely(ctrl->kato == 0))
  549. return;
  550. cancel_delayed_work_sync(&ctrl->ka_work);
  551. }
  552. EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
  553. int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
  554. {
  555. struct nvme_command c = { };
  556. int error;
  557. /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
  558. c.identify.opcode = nvme_admin_identify;
  559. c.identify.cns = NVME_ID_CNS_CTRL;
  560. *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
  561. if (!*id)
  562. return -ENOMEM;
  563. error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
  564. sizeof(struct nvme_id_ctrl));
  565. if (error)
  566. kfree(*id);
  567. return error;
  568. }
  569. static int nvme_identify_ns_descs(struct nvme_ns *ns, unsigned nsid)
  570. {
  571. struct nvme_command c = { };
  572. int status;
  573. void *data;
  574. int pos;
  575. int len;
  576. c.identify.opcode = nvme_admin_identify;
  577. c.identify.nsid = cpu_to_le32(nsid);
  578. c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
  579. data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
  580. if (!data)
  581. return -ENOMEM;
  582. status = nvme_submit_sync_cmd(ns->ctrl->admin_q, &c, data,
  583. NVME_IDENTIFY_DATA_SIZE);
  584. if (status)
  585. goto free_data;
  586. for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
  587. struct nvme_ns_id_desc *cur = data + pos;
  588. if (cur->nidl == 0)
  589. break;
  590. switch (cur->nidt) {
  591. case NVME_NIDT_EUI64:
  592. if (cur->nidl != NVME_NIDT_EUI64_LEN) {
  593. dev_warn(ns->ctrl->device,
  594. "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
  595. cur->nidl);
  596. goto free_data;
  597. }
  598. len = NVME_NIDT_EUI64_LEN;
  599. memcpy(ns->eui, data + pos + sizeof(*cur), len);
  600. break;
  601. case NVME_NIDT_NGUID:
  602. if (cur->nidl != NVME_NIDT_NGUID_LEN) {
  603. dev_warn(ns->ctrl->device,
  604. "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
  605. cur->nidl);
  606. goto free_data;
  607. }
  608. len = NVME_NIDT_NGUID_LEN;
  609. memcpy(ns->nguid, data + pos + sizeof(*cur), len);
  610. break;
  611. case NVME_NIDT_UUID:
  612. if (cur->nidl != NVME_NIDT_UUID_LEN) {
  613. dev_warn(ns->ctrl->device,
  614. "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
  615. cur->nidl);
  616. goto free_data;
  617. }
  618. len = NVME_NIDT_UUID_LEN;
  619. uuid_copy(&ns->uuid, data + pos + sizeof(*cur));
  620. break;
  621. default:
  622. /* Skip unnkown types */
  623. len = cur->nidl;
  624. break;
  625. }
  626. len += sizeof(*cur);
  627. }
  628. free_data:
  629. kfree(data);
  630. return status;
  631. }
  632. static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
  633. {
  634. struct nvme_command c = { };
  635. c.identify.opcode = nvme_admin_identify;
  636. c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
  637. c.identify.nsid = cpu_to_le32(nsid);
  638. return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
  639. }
  640. int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
  641. struct nvme_id_ns **id)
  642. {
  643. struct nvme_command c = { };
  644. int error;
  645. /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
  646. c.identify.opcode = nvme_admin_identify;
  647. c.identify.nsid = cpu_to_le32(nsid);
  648. c.identify.cns = NVME_ID_CNS_NS;
  649. *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
  650. if (!*id)
  651. return -ENOMEM;
  652. error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
  653. sizeof(struct nvme_id_ns));
  654. if (error)
  655. kfree(*id);
  656. return error;
  657. }
  658. int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
  659. void *buffer, size_t buflen, u32 *result)
  660. {
  661. struct nvme_command c;
  662. union nvme_result res;
  663. int ret;
  664. memset(&c, 0, sizeof(c));
  665. c.features.opcode = nvme_admin_get_features;
  666. c.features.nsid = cpu_to_le32(nsid);
  667. c.features.fid = cpu_to_le32(fid);
  668. ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, buffer, buflen, 0,
  669. NVME_QID_ANY, 0, 0);
  670. if (ret >= 0 && result)
  671. *result = le32_to_cpu(res.u32);
  672. return ret;
  673. }
  674. int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
  675. void *buffer, size_t buflen, u32 *result)
  676. {
  677. struct nvme_command c;
  678. union nvme_result res;
  679. int ret;
  680. memset(&c, 0, sizeof(c));
  681. c.features.opcode = nvme_admin_set_features;
  682. c.features.fid = cpu_to_le32(fid);
  683. c.features.dword11 = cpu_to_le32(dword11);
  684. ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
  685. buffer, buflen, 0, NVME_QID_ANY, 0, 0);
  686. if (ret >= 0 && result)
  687. *result = le32_to_cpu(res.u32);
  688. return ret;
  689. }
  690. int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
  691. {
  692. struct nvme_command c = { };
  693. int error;
  694. c.common.opcode = nvme_admin_get_log_page,
  695. c.common.nsid = cpu_to_le32(0xFFFFFFFF),
  696. c.common.cdw10[0] = cpu_to_le32(
  697. (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
  698. NVME_LOG_SMART),
  699. *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
  700. if (!*log)
  701. return -ENOMEM;
  702. error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
  703. sizeof(struct nvme_smart_log));
  704. if (error)
  705. kfree(*log);
  706. return error;
  707. }
  708. int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
  709. {
  710. u32 q_count = (*count - 1) | ((*count - 1) << 16);
  711. u32 result;
  712. int status, nr_io_queues;
  713. status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
  714. &result);
  715. if (status < 0)
  716. return status;
  717. /*
  718. * Degraded controllers might return an error when setting the queue
  719. * count. We still want to be able to bring them online and offer
  720. * access to the admin queue, as that might be only way to fix them up.
  721. */
  722. if (status > 0) {
  723. dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
  724. *count = 0;
  725. } else {
  726. nr_io_queues = min(result & 0xffff, result >> 16) + 1;
  727. *count = min(*count, nr_io_queues);
  728. }
  729. return 0;
  730. }
  731. EXPORT_SYMBOL_GPL(nvme_set_queue_count);
  732. static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
  733. {
  734. struct nvme_user_io io;
  735. struct nvme_command c;
  736. unsigned length, meta_len;
  737. void __user *metadata;
  738. if (copy_from_user(&io, uio, sizeof(io)))
  739. return -EFAULT;
  740. if (io.flags)
  741. return -EINVAL;
  742. switch (io.opcode) {
  743. case nvme_cmd_write:
  744. case nvme_cmd_read:
  745. case nvme_cmd_compare:
  746. break;
  747. default:
  748. return -EINVAL;
  749. }
  750. length = (io.nblocks + 1) << ns->lba_shift;
  751. meta_len = (io.nblocks + 1) * ns->ms;
  752. metadata = (void __user *)(uintptr_t)io.metadata;
  753. if (ns->ext) {
  754. length += meta_len;
  755. meta_len = 0;
  756. } else if (meta_len) {
  757. if ((io.metadata & 3) || !io.metadata)
  758. return -EINVAL;
  759. }
  760. memset(&c, 0, sizeof(c));
  761. c.rw.opcode = io.opcode;
  762. c.rw.flags = io.flags;
  763. c.rw.nsid = cpu_to_le32(ns->ns_id);
  764. c.rw.slba = cpu_to_le64(io.slba);
  765. c.rw.length = cpu_to_le16(io.nblocks);
  766. c.rw.control = cpu_to_le16(io.control);
  767. c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
  768. c.rw.reftag = cpu_to_le32(io.reftag);
  769. c.rw.apptag = cpu_to_le16(io.apptag);
  770. c.rw.appmask = cpu_to_le16(io.appmask);
  771. return __nvme_submit_user_cmd(ns->queue, &c,
  772. (void __user *)(uintptr_t)io.addr, length,
  773. metadata, meta_len, io.slba, NULL, 0);
  774. }
  775. static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
  776. struct nvme_passthru_cmd __user *ucmd)
  777. {
  778. struct nvme_passthru_cmd cmd;
  779. struct nvme_command c;
  780. unsigned timeout = 0;
  781. int status;
  782. if (!capable(CAP_SYS_ADMIN))
  783. return -EACCES;
  784. if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
  785. return -EFAULT;
  786. if (cmd.flags)
  787. return -EINVAL;
  788. memset(&c, 0, sizeof(c));
  789. c.common.opcode = cmd.opcode;
  790. c.common.flags = cmd.flags;
  791. c.common.nsid = cpu_to_le32(cmd.nsid);
  792. c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
  793. c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
  794. c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
  795. c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
  796. c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
  797. c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
  798. c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
  799. c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
  800. if (cmd.timeout_ms)
  801. timeout = msecs_to_jiffies(cmd.timeout_ms);
  802. status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
  803. (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
  804. &cmd.result, timeout);
  805. if (status >= 0) {
  806. if (put_user(cmd.result, &ucmd->result))
  807. return -EFAULT;
  808. }
  809. return status;
  810. }
  811. static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
  812. unsigned int cmd, unsigned long arg)
  813. {
  814. struct nvme_ns *ns = bdev->bd_disk->private_data;
  815. switch (cmd) {
  816. case NVME_IOCTL_ID:
  817. force_successful_syscall_return();
  818. return ns->ns_id;
  819. case NVME_IOCTL_ADMIN_CMD:
  820. return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
  821. case NVME_IOCTL_IO_CMD:
  822. return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
  823. case NVME_IOCTL_SUBMIT_IO:
  824. return nvme_submit_io(ns, (void __user *)arg);
  825. #ifdef CONFIG_BLK_DEV_NVME_SCSI
  826. case SG_GET_VERSION_NUM:
  827. return nvme_sg_get_version_num((void __user *)arg);
  828. case SG_IO:
  829. return nvme_sg_io(ns, (void __user *)arg);
  830. #endif
  831. default:
  832. #ifdef CONFIG_NVM
  833. if (ns->ndev)
  834. return nvme_nvm_ioctl(ns, cmd, arg);
  835. #endif
  836. if (is_sed_ioctl(cmd))
  837. return sed_ioctl(ns->ctrl->opal_dev, cmd,
  838. (void __user *) arg);
  839. return -ENOTTY;
  840. }
  841. }
  842. #ifdef CONFIG_COMPAT
  843. static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
  844. unsigned int cmd, unsigned long arg)
  845. {
  846. switch (cmd) {
  847. case SG_IO:
  848. return -ENOIOCTLCMD;
  849. }
  850. return nvme_ioctl(bdev, mode, cmd, arg);
  851. }
  852. #else
  853. #define nvme_compat_ioctl NULL
  854. #endif
  855. static int nvme_open(struct block_device *bdev, fmode_t mode)
  856. {
  857. return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
  858. }
  859. static void nvme_release(struct gendisk *disk, fmode_t mode)
  860. {
  861. struct nvme_ns *ns = disk->private_data;
  862. module_put(ns->ctrl->ops->module);
  863. nvme_put_ns(ns);
  864. }
  865. static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
  866. {
  867. /* some standard values */
  868. geo->heads = 1 << 6;
  869. geo->sectors = 1 << 5;
  870. geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
  871. return 0;
  872. }
  873. #ifdef CONFIG_BLK_DEV_INTEGRITY
  874. static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
  875. u16 bs)
  876. {
  877. struct nvme_ns *ns = disk->private_data;
  878. u16 old_ms = ns->ms;
  879. u8 pi_type = 0;
  880. ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
  881. ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
  882. /* PI implementation requires metadata equal t10 pi tuple size */
  883. if (ns->ms == sizeof(struct t10_pi_tuple))
  884. pi_type = id->dps & NVME_NS_DPS_PI_MASK;
  885. if (blk_get_integrity(disk) &&
  886. (ns->pi_type != pi_type || ns->ms != old_ms ||
  887. bs != queue_logical_block_size(disk->queue) ||
  888. (ns->ms && ns->ext)))
  889. blk_integrity_unregister(disk);
  890. ns->pi_type = pi_type;
  891. }
  892. static void nvme_init_integrity(struct nvme_ns *ns)
  893. {
  894. struct blk_integrity integrity;
  895. memset(&integrity, 0, sizeof(integrity));
  896. switch (ns->pi_type) {
  897. case NVME_NS_DPS_PI_TYPE3:
  898. integrity.profile = &t10_pi_type3_crc;
  899. integrity.tag_size = sizeof(u16) + sizeof(u32);
  900. integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
  901. break;
  902. case NVME_NS_DPS_PI_TYPE1:
  903. case NVME_NS_DPS_PI_TYPE2:
  904. integrity.profile = &t10_pi_type1_crc;
  905. integrity.tag_size = sizeof(u16);
  906. integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
  907. break;
  908. default:
  909. integrity.profile = NULL;
  910. break;
  911. }
  912. integrity.tuple_size = ns->ms;
  913. blk_integrity_register(ns->disk, &integrity);
  914. blk_queue_max_integrity_segments(ns->queue, 1);
  915. }
  916. #else
  917. static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
  918. u16 bs)
  919. {
  920. }
  921. static void nvme_init_integrity(struct nvme_ns *ns)
  922. {
  923. }
  924. #endif /* CONFIG_BLK_DEV_INTEGRITY */
  925. static void nvme_set_chunk_size(struct nvme_ns *ns)
  926. {
  927. u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
  928. blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
  929. }
  930. static void nvme_config_discard(struct nvme_ns *ns)
  931. {
  932. struct nvme_ctrl *ctrl = ns->ctrl;
  933. u32 logical_block_size = queue_logical_block_size(ns->queue);
  934. BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
  935. NVME_DSM_MAX_RANGES);
  936. ns->queue->limits.discard_alignment = logical_block_size;
  937. ns->queue->limits.discard_granularity = logical_block_size;
  938. blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
  939. blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
  940. queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
  941. if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
  942. blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
  943. }
  944. static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
  945. {
  946. if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
  947. dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
  948. return -ENODEV;
  949. }
  950. if ((*id)->ncap == 0) {
  951. kfree(*id);
  952. return -ENODEV;
  953. }
  954. if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
  955. memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
  956. if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
  957. memcpy(ns->nguid, (*id)->nguid, sizeof(ns->nguid));
  958. if (ns->ctrl->vs >= NVME_VS(1, 3, 0)) {
  959. /* Don't treat error as fatal we potentially
  960. * already have a NGUID or EUI-64
  961. */
  962. if (nvme_identify_ns_descs(ns, ns->ns_id))
  963. dev_warn(ns->ctrl->device,
  964. "%s: Identify Descriptors failed\n", __func__);
  965. }
  966. return 0;
  967. }
  968. static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
  969. {
  970. struct nvme_ns *ns = disk->private_data;
  971. u16 bs;
  972. /*
  973. * If identify namespace failed, use default 512 byte block size so
  974. * block layer can use before failing read/write for 0 capacity.
  975. */
  976. ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
  977. if (ns->lba_shift == 0)
  978. ns->lba_shift = 9;
  979. bs = 1 << ns->lba_shift;
  980. ns->noiob = le16_to_cpu(id->noiob);
  981. blk_mq_freeze_queue(disk->queue);
  982. if (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
  983. nvme_prep_integrity(disk, id, bs);
  984. blk_queue_logical_block_size(ns->queue, bs);
  985. if (ns->noiob)
  986. nvme_set_chunk_size(ns);
  987. if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
  988. nvme_init_integrity(ns);
  989. if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
  990. set_capacity(disk, 0);
  991. else
  992. set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
  993. if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
  994. nvme_config_discard(ns);
  995. blk_mq_unfreeze_queue(disk->queue);
  996. }
  997. static int nvme_revalidate_disk(struct gendisk *disk)
  998. {
  999. struct nvme_ns *ns = disk->private_data;
  1000. struct nvme_id_ns *id = NULL;
  1001. int ret;
  1002. if (test_bit(NVME_NS_DEAD, &ns->flags)) {
  1003. set_capacity(disk, 0);
  1004. return -ENODEV;
  1005. }
  1006. ret = nvme_revalidate_ns(ns, &id);
  1007. if (ret)
  1008. return ret;
  1009. __nvme_revalidate_disk(disk, id);
  1010. kfree(id);
  1011. return 0;
  1012. }
  1013. static char nvme_pr_type(enum pr_type type)
  1014. {
  1015. switch (type) {
  1016. case PR_WRITE_EXCLUSIVE:
  1017. return 1;
  1018. case PR_EXCLUSIVE_ACCESS:
  1019. return 2;
  1020. case PR_WRITE_EXCLUSIVE_REG_ONLY:
  1021. return 3;
  1022. case PR_EXCLUSIVE_ACCESS_REG_ONLY:
  1023. return 4;
  1024. case PR_WRITE_EXCLUSIVE_ALL_REGS:
  1025. return 5;
  1026. case PR_EXCLUSIVE_ACCESS_ALL_REGS:
  1027. return 6;
  1028. default:
  1029. return 0;
  1030. }
  1031. };
  1032. static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
  1033. u64 key, u64 sa_key, u8 op)
  1034. {
  1035. struct nvme_ns *ns = bdev->bd_disk->private_data;
  1036. struct nvme_command c;
  1037. u8 data[16] = { 0, };
  1038. put_unaligned_le64(key, &data[0]);
  1039. put_unaligned_le64(sa_key, &data[8]);
  1040. memset(&c, 0, sizeof(c));
  1041. c.common.opcode = op;
  1042. c.common.nsid = cpu_to_le32(ns->ns_id);
  1043. c.common.cdw10[0] = cpu_to_le32(cdw10);
  1044. return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
  1045. }
  1046. static int nvme_pr_register(struct block_device *bdev, u64 old,
  1047. u64 new, unsigned flags)
  1048. {
  1049. u32 cdw10;
  1050. if (flags & ~PR_FL_IGNORE_KEY)
  1051. return -EOPNOTSUPP;
  1052. cdw10 = old ? 2 : 0;
  1053. cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
  1054. cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
  1055. return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
  1056. }
  1057. static int nvme_pr_reserve(struct block_device *bdev, u64 key,
  1058. enum pr_type type, unsigned flags)
  1059. {
  1060. u32 cdw10;
  1061. if (flags & ~PR_FL_IGNORE_KEY)
  1062. return -EOPNOTSUPP;
  1063. cdw10 = nvme_pr_type(type) << 8;
  1064. cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
  1065. return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
  1066. }
  1067. static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
  1068. enum pr_type type, bool abort)
  1069. {
  1070. u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
  1071. return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
  1072. }
  1073. static int nvme_pr_clear(struct block_device *bdev, u64 key)
  1074. {
  1075. u32 cdw10 = 1 | (key ? 1 << 3 : 0);
  1076. return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
  1077. }
  1078. static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
  1079. {
  1080. u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
  1081. return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
  1082. }
  1083. static const struct pr_ops nvme_pr_ops = {
  1084. .pr_register = nvme_pr_register,
  1085. .pr_reserve = nvme_pr_reserve,
  1086. .pr_release = nvme_pr_release,
  1087. .pr_preempt = nvme_pr_preempt,
  1088. .pr_clear = nvme_pr_clear,
  1089. };
  1090. #ifdef CONFIG_BLK_SED_OPAL
  1091. int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
  1092. bool send)
  1093. {
  1094. struct nvme_ctrl *ctrl = data;
  1095. struct nvme_command cmd;
  1096. memset(&cmd, 0, sizeof(cmd));
  1097. if (send)
  1098. cmd.common.opcode = nvme_admin_security_send;
  1099. else
  1100. cmd.common.opcode = nvme_admin_security_recv;
  1101. cmd.common.nsid = 0;
  1102. cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
  1103. cmd.common.cdw10[1] = cpu_to_le32(len);
  1104. return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
  1105. ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
  1106. }
  1107. EXPORT_SYMBOL_GPL(nvme_sec_submit);
  1108. #endif /* CONFIG_BLK_SED_OPAL */
  1109. static const struct block_device_operations nvme_fops = {
  1110. .owner = THIS_MODULE,
  1111. .ioctl = nvme_ioctl,
  1112. .compat_ioctl = nvme_compat_ioctl,
  1113. .open = nvme_open,
  1114. .release = nvme_release,
  1115. .getgeo = nvme_getgeo,
  1116. .revalidate_disk= nvme_revalidate_disk,
  1117. .pr_ops = &nvme_pr_ops,
  1118. };
  1119. static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
  1120. {
  1121. unsigned long timeout =
  1122. ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
  1123. u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
  1124. int ret;
  1125. while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
  1126. if (csts == ~0)
  1127. return -ENODEV;
  1128. if ((csts & NVME_CSTS_RDY) == bit)
  1129. break;
  1130. msleep(100);
  1131. if (fatal_signal_pending(current))
  1132. return -EINTR;
  1133. if (time_after(jiffies, timeout)) {
  1134. dev_err(ctrl->device,
  1135. "Device not ready; aborting %s\n", enabled ?
  1136. "initialisation" : "reset");
  1137. return -ENODEV;
  1138. }
  1139. }
  1140. return ret;
  1141. }
  1142. /*
  1143. * If the device has been passed off to us in an enabled state, just clear
  1144. * the enabled bit. The spec says we should set the 'shutdown notification
  1145. * bits', but doing so may cause the device to complete commands to the
  1146. * admin queue ... and we don't know what memory that might be pointing at!
  1147. */
  1148. int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
  1149. {
  1150. int ret;
  1151. ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
  1152. ctrl->ctrl_config &= ~NVME_CC_ENABLE;
  1153. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  1154. if (ret)
  1155. return ret;
  1156. if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
  1157. msleep(NVME_QUIRK_DELAY_AMOUNT);
  1158. return nvme_wait_ready(ctrl, cap, false);
  1159. }
  1160. EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
  1161. int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
  1162. {
  1163. /*
  1164. * Default to a 4K page size, with the intention to update this
  1165. * path in the future to accomodate architectures with differing
  1166. * kernel and IO page sizes.
  1167. */
  1168. unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
  1169. int ret;
  1170. if (page_shift < dev_page_min) {
  1171. dev_err(ctrl->device,
  1172. "Minimum device page size %u too large for host (%u)\n",
  1173. 1 << dev_page_min, 1 << page_shift);
  1174. return -ENODEV;
  1175. }
  1176. ctrl->page_size = 1 << page_shift;
  1177. ctrl->ctrl_config = NVME_CC_CSS_NVM;
  1178. ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
  1179. ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
  1180. ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
  1181. ctrl->ctrl_config |= NVME_CC_ENABLE;
  1182. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  1183. if (ret)
  1184. return ret;
  1185. return nvme_wait_ready(ctrl, cap, true);
  1186. }
  1187. EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
  1188. int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
  1189. {
  1190. unsigned long timeout = jiffies + (shutdown_timeout * HZ);
  1191. u32 csts;
  1192. int ret;
  1193. ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
  1194. ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
  1195. ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
  1196. if (ret)
  1197. return ret;
  1198. while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
  1199. if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
  1200. break;
  1201. msleep(100);
  1202. if (fatal_signal_pending(current))
  1203. return -EINTR;
  1204. if (time_after(jiffies, timeout)) {
  1205. dev_err(ctrl->device,
  1206. "Device shutdown incomplete; abort shutdown\n");
  1207. return -ENODEV;
  1208. }
  1209. }
  1210. return ret;
  1211. }
  1212. EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
  1213. static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
  1214. struct request_queue *q)
  1215. {
  1216. bool vwc = false;
  1217. if (ctrl->max_hw_sectors) {
  1218. u32 max_segments =
  1219. (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
  1220. blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
  1221. blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
  1222. }
  1223. if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
  1224. blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
  1225. blk_queue_virt_boundary(q, ctrl->page_size - 1);
  1226. if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
  1227. vwc = true;
  1228. blk_queue_write_cache(q, vwc, vwc);
  1229. }
  1230. static void nvme_configure_apst(struct nvme_ctrl *ctrl)
  1231. {
  1232. /*
  1233. * APST (Autonomous Power State Transition) lets us program a
  1234. * table of power state transitions that the controller will
  1235. * perform automatically. We configure it with a simple
  1236. * heuristic: we are willing to spend at most 2% of the time
  1237. * transitioning between power states. Therefore, when running
  1238. * in any given state, we will enter the next lower-power
  1239. * non-operational state after waiting 50 * (enlat + exlat)
  1240. * microseconds, as long as that state's exit latency is under
  1241. * the requested maximum latency.
  1242. *
  1243. * We will not autonomously enter any non-operational state for
  1244. * which the total latency exceeds ps_max_latency_us. Users
  1245. * can set ps_max_latency_us to zero to turn off APST.
  1246. */
  1247. unsigned apste;
  1248. struct nvme_feat_auto_pst *table;
  1249. u64 max_lat_us = 0;
  1250. int max_ps = -1;
  1251. int ret;
  1252. /*
  1253. * If APST isn't supported or if we haven't been initialized yet,
  1254. * then don't do anything.
  1255. */
  1256. if (!ctrl->apsta)
  1257. return;
  1258. if (ctrl->npss > 31) {
  1259. dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
  1260. return;
  1261. }
  1262. table = kzalloc(sizeof(*table), GFP_KERNEL);
  1263. if (!table)
  1264. return;
  1265. if (ctrl->ps_max_latency_us == 0) {
  1266. /* Turn off APST. */
  1267. apste = 0;
  1268. dev_dbg(ctrl->device, "APST disabled\n");
  1269. } else {
  1270. __le64 target = cpu_to_le64(0);
  1271. int state;
  1272. /*
  1273. * Walk through all states from lowest- to highest-power.
  1274. * According to the spec, lower-numbered states use more
  1275. * power. NPSS, despite the name, is the index of the
  1276. * lowest-power state, not the number of states.
  1277. */
  1278. for (state = (int)ctrl->npss; state >= 0; state--) {
  1279. u64 total_latency_us, exit_latency_us, transition_ms;
  1280. if (target)
  1281. table->entries[state] = target;
  1282. /*
  1283. * Don't allow transitions to the deepest state
  1284. * if it's quirked off.
  1285. */
  1286. if (state == ctrl->npss &&
  1287. (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
  1288. continue;
  1289. /*
  1290. * Is this state a useful non-operational state for
  1291. * higher-power states to autonomously transition to?
  1292. */
  1293. if (!(ctrl->psd[state].flags &
  1294. NVME_PS_FLAGS_NON_OP_STATE))
  1295. continue;
  1296. exit_latency_us =
  1297. (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
  1298. if (exit_latency_us > ctrl->ps_max_latency_us)
  1299. continue;
  1300. total_latency_us =
  1301. exit_latency_us +
  1302. le32_to_cpu(ctrl->psd[state].entry_lat);
  1303. /*
  1304. * This state is good. Use it as the APST idle
  1305. * target for higher power states.
  1306. */
  1307. transition_ms = total_latency_us + 19;
  1308. do_div(transition_ms, 20);
  1309. if (transition_ms > (1 << 24) - 1)
  1310. transition_ms = (1 << 24) - 1;
  1311. target = cpu_to_le64((state << 3) |
  1312. (transition_ms << 8));
  1313. if (max_ps == -1)
  1314. max_ps = state;
  1315. if (total_latency_us > max_lat_us)
  1316. max_lat_us = total_latency_us;
  1317. }
  1318. apste = 1;
  1319. if (max_ps == -1) {
  1320. dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
  1321. } else {
  1322. dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
  1323. max_ps, max_lat_us, (int)sizeof(*table), table);
  1324. }
  1325. }
  1326. ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
  1327. table, sizeof(*table), NULL);
  1328. if (ret)
  1329. dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
  1330. kfree(table);
  1331. }
  1332. static void nvme_set_latency_tolerance(struct device *dev, s32 val)
  1333. {
  1334. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1335. u64 latency;
  1336. switch (val) {
  1337. case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
  1338. case PM_QOS_LATENCY_ANY:
  1339. latency = U64_MAX;
  1340. break;
  1341. default:
  1342. latency = val;
  1343. }
  1344. if (ctrl->ps_max_latency_us != latency) {
  1345. ctrl->ps_max_latency_us = latency;
  1346. nvme_configure_apst(ctrl);
  1347. }
  1348. }
  1349. struct nvme_core_quirk_entry {
  1350. /*
  1351. * NVMe model and firmware strings are padded with spaces. For
  1352. * simplicity, strings in the quirk table are padded with NULLs
  1353. * instead.
  1354. */
  1355. u16 vid;
  1356. const char *mn;
  1357. const char *fr;
  1358. unsigned long quirks;
  1359. };
  1360. static const struct nvme_core_quirk_entry core_quirks[] = {
  1361. {
  1362. /*
  1363. * This Toshiba device seems to die using any APST states. See:
  1364. * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
  1365. */
  1366. .vid = 0x1179,
  1367. .mn = "THNSF5256GPUK TOSHIBA",
  1368. .quirks = NVME_QUIRK_NO_APST,
  1369. }
  1370. };
  1371. /* match is null-terminated but idstr is space-padded. */
  1372. static bool string_matches(const char *idstr, const char *match, size_t len)
  1373. {
  1374. size_t matchlen;
  1375. if (!match)
  1376. return true;
  1377. matchlen = strlen(match);
  1378. WARN_ON_ONCE(matchlen > len);
  1379. if (memcmp(idstr, match, matchlen))
  1380. return false;
  1381. for (; matchlen < len; matchlen++)
  1382. if (idstr[matchlen] != ' ')
  1383. return false;
  1384. return true;
  1385. }
  1386. static bool quirk_matches(const struct nvme_id_ctrl *id,
  1387. const struct nvme_core_quirk_entry *q)
  1388. {
  1389. return q->vid == le16_to_cpu(id->vid) &&
  1390. string_matches(id->mn, q->mn, sizeof(id->mn)) &&
  1391. string_matches(id->fr, q->fr, sizeof(id->fr));
  1392. }
  1393. /*
  1394. * Initialize the cached copies of the Identify data and various controller
  1395. * register in our nvme_ctrl structure. This should be called as soon as
  1396. * the admin queue is fully up and running.
  1397. */
  1398. int nvme_init_identify(struct nvme_ctrl *ctrl)
  1399. {
  1400. struct nvme_id_ctrl *id;
  1401. u64 cap;
  1402. int ret, page_shift;
  1403. u32 max_hw_sectors;
  1404. u8 prev_apsta;
  1405. ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
  1406. if (ret) {
  1407. dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
  1408. return ret;
  1409. }
  1410. ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
  1411. if (ret) {
  1412. dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
  1413. return ret;
  1414. }
  1415. page_shift = NVME_CAP_MPSMIN(cap) + 12;
  1416. if (ctrl->vs >= NVME_VS(1, 1, 0))
  1417. ctrl->subsystem = NVME_CAP_NSSRC(cap);
  1418. ret = nvme_identify_ctrl(ctrl, &id);
  1419. if (ret) {
  1420. dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
  1421. return -EIO;
  1422. }
  1423. if (!ctrl->identified) {
  1424. /*
  1425. * Check for quirks. Quirk can depend on firmware version,
  1426. * so, in principle, the set of quirks present can change
  1427. * across a reset. As a possible future enhancement, we
  1428. * could re-scan for quirks every time we reinitialize
  1429. * the device, but we'd have to make sure that the driver
  1430. * behaves intelligently if the quirks change.
  1431. */
  1432. int i;
  1433. for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
  1434. if (quirk_matches(id, &core_quirks[i]))
  1435. ctrl->quirks |= core_quirks[i].quirks;
  1436. }
  1437. }
  1438. if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
  1439. dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
  1440. ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
  1441. }
  1442. ctrl->oacs = le16_to_cpu(id->oacs);
  1443. ctrl->vid = le16_to_cpu(id->vid);
  1444. ctrl->oncs = le16_to_cpup(&id->oncs);
  1445. atomic_set(&ctrl->abort_limit, id->acl + 1);
  1446. ctrl->vwc = id->vwc;
  1447. ctrl->cntlid = le16_to_cpup(&id->cntlid);
  1448. memcpy(ctrl->serial, id->sn, sizeof(id->sn));
  1449. memcpy(ctrl->model, id->mn, sizeof(id->mn));
  1450. memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
  1451. if (id->mdts)
  1452. max_hw_sectors = 1 << (id->mdts + page_shift - 9);
  1453. else
  1454. max_hw_sectors = UINT_MAX;
  1455. ctrl->max_hw_sectors =
  1456. min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
  1457. nvme_set_queue_limits(ctrl, ctrl->admin_q);
  1458. ctrl->sgls = le32_to_cpu(id->sgls);
  1459. ctrl->kas = le16_to_cpu(id->kas);
  1460. ctrl->npss = id->npss;
  1461. prev_apsta = ctrl->apsta;
  1462. if (ctrl->quirks & NVME_QUIRK_NO_APST) {
  1463. if (force_apst && id->apsta) {
  1464. dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
  1465. ctrl->apsta = 1;
  1466. } else {
  1467. ctrl->apsta = 0;
  1468. }
  1469. } else {
  1470. ctrl->apsta = id->apsta;
  1471. }
  1472. memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
  1473. if (ctrl->ops->flags & NVME_F_FABRICS) {
  1474. ctrl->icdoff = le16_to_cpu(id->icdoff);
  1475. ctrl->ioccsz = le32_to_cpu(id->ioccsz);
  1476. ctrl->iorcsz = le32_to_cpu(id->iorcsz);
  1477. ctrl->maxcmd = le16_to_cpu(id->maxcmd);
  1478. /*
  1479. * In fabrics we need to verify the cntlid matches the
  1480. * admin connect
  1481. */
  1482. if (ctrl->cntlid != le16_to_cpu(id->cntlid))
  1483. ret = -EINVAL;
  1484. if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
  1485. dev_err(ctrl->device,
  1486. "keep-alive support is mandatory for fabrics\n");
  1487. ret = -EINVAL;
  1488. }
  1489. } else {
  1490. ctrl->cntlid = le16_to_cpu(id->cntlid);
  1491. ctrl->hmpre = le32_to_cpu(id->hmpre);
  1492. ctrl->hmmin = le32_to_cpu(id->hmmin);
  1493. }
  1494. kfree(id);
  1495. if (ctrl->apsta && !prev_apsta)
  1496. dev_pm_qos_expose_latency_tolerance(ctrl->device);
  1497. else if (!ctrl->apsta && prev_apsta)
  1498. dev_pm_qos_hide_latency_tolerance(ctrl->device);
  1499. nvme_configure_apst(ctrl);
  1500. ctrl->identified = true;
  1501. return ret;
  1502. }
  1503. EXPORT_SYMBOL_GPL(nvme_init_identify);
  1504. static int nvme_dev_open(struct inode *inode, struct file *file)
  1505. {
  1506. struct nvme_ctrl *ctrl;
  1507. int instance = iminor(inode);
  1508. int ret = -ENODEV;
  1509. spin_lock(&dev_list_lock);
  1510. list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
  1511. if (ctrl->instance != instance)
  1512. continue;
  1513. if (!ctrl->admin_q) {
  1514. ret = -EWOULDBLOCK;
  1515. break;
  1516. }
  1517. if (!kref_get_unless_zero(&ctrl->kref))
  1518. break;
  1519. file->private_data = ctrl;
  1520. ret = 0;
  1521. break;
  1522. }
  1523. spin_unlock(&dev_list_lock);
  1524. return ret;
  1525. }
  1526. static int nvme_dev_release(struct inode *inode, struct file *file)
  1527. {
  1528. nvme_put_ctrl(file->private_data);
  1529. return 0;
  1530. }
  1531. static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
  1532. {
  1533. struct nvme_ns *ns;
  1534. int ret;
  1535. mutex_lock(&ctrl->namespaces_mutex);
  1536. if (list_empty(&ctrl->namespaces)) {
  1537. ret = -ENOTTY;
  1538. goto out_unlock;
  1539. }
  1540. ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
  1541. if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
  1542. dev_warn(ctrl->device,
  1543. "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
  1544. ret = -EINVAL;
  1545. goto out_unlock;
  1546. }
  1547. dev_warn(ctrl->device,
  1548. "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
  1549. kref_get(&ns->kref);
  1550. mutex_unlock(&ctrl->namespaces_mutex);
  1551. ret = nvme_user_cmd(ctrl, ns, argp);
  1552. nvme_put_ns(ns);
  1553. return ret;
  1554. out_unlock:
  1555. mutex_unlock(&ctrl->namespaces_mutex);
  1556. return ret;
  1557. }
  1558. static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
  1559. unsigned long arg)
  1560. {
  1561. struct nvme_ctrl *ctrl = file->private_data;
  1562. void __user *argp = (void __user *)arg;
  1563. switch (cmd) {
  1564. case NVME_IOCTL_ADMIN_CMD:
  1565. return nvme_user_cmd(ctrl, NULL, argp);
  1566. case NVME_IOCTL_IO_CMD:
  1567. return nvme_dev_user_cmd(ctrl, argp);
  1568. case NVME_IOCTL_RESET:
  1569. dev_warn(ctrl->device, "resetting controller\n");
  1570. return nvme_reset_ctrl_sync(ctrl);
  1571. case NVME_IOCTL_SUBSYS_RESET:
  1572. return nvme_reset_subsystem(ctrl);
  1573. case NVME_IOCTL_RESCAN:
  1574. nvme_queue_scan(ctrl);
  1575. return 0;
  1576. default:
  1577. return -ENOTTY;
  1578. }
  1579. }
  1580. static const struct file_operations nvme_dev_fops = {
  1581. .owner = THIS_MODULE,
  1582. .open = nvme_dev_open,
  1583. .release = nvme_dev_release,
  1584. .unlocked_ioctl = nvme_dev_ioctl,
  1585. .compat_ioctl = nvme_dev_ioctl,
  1586. };
  1587. static ssize_t nvme_sysfs_reset(struct device *dev,
  1588. struct device_attribute *attr, const char *buf,
  1589. size_t count)
  1590. {
  1591. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1592. int ret;
  1593. ret = nvme_reset_ctrl_sync(ctrl);
  1594. if (ret < 0)
  1595. return ret;
  1596. return count;
  1597. }
  1598. static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
  1599. static ssize_t nvme_sysfs_rescan(struct device *dev,
  1600. struct device_attribute *attr, const char *buf,
  1601. size_t count)
  1602. {
  1603. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1604. nvme_queue_scan(ctrl);
  1605. return count;
  1606. }
  1607. static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
  1608. static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
  1609. char *buf)
  1610. {
  1611. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1612. struct nvme_ctrl *ctrl = ns->ctrl;
  1613. int serial_len = sizeof(ctrl->serial);
  1614. int model_len = sizeof(ctrl->model);
  1615. if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
  1616. return sprintf(buf, "eui.%16phN\n", ns->nguid);
  1617. if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
  1618. return sprintf(buf, "eui.%8phN\n", ns->eui);
  1619. while (ctrl->serial[serial_len - 1] == ' ')
  1620. serial_len--;
  1621. while (ctrl->model[model_len - 1] == ' ')
  1622. model_len--;
  1623. return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
  1624. serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
  1625. }
  1626. static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
  1627. static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
  1628. char *buf)
  1629. {
  1630. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1631. return sprintf(buf, "%pU\n", ns->nguid);
  1632. }
  1633. static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
  1634. static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
  1635. char *buf)
  1636. {
  1637. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1638. /* For backward compatibility expose the NGUID to userspace if
  1639. * we have no UUID set
  1640. */
  1641. if (uuid_is_null(&ns->uuid)) {
  1642. printk_ratelimited(KERN_WARNING
  1643. "No UUID available providing old NGUID\n");
  1644. return sprintf(buf, "%pU\n", ns->nguid);
  1645. }
  1646. return sprintf(buf, "%pU\n", &ns->uuid);
  1647. }
  1648. static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
  1649. static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
  1650. char *buf)
  1651. {
  1652. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1653. return sprintf(buf, "%8phd\n", ns->eui);
  1654. }
  1655. static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
  1656. static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
  1657. char *buf)
  1658. {
  1659. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1660. return sprintf(buf, "%d\n", ns->ns_id);
  1661. }
  1662. static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
  1663. static struct attribute *nvme_ns_attrs[] = {
  1664. &dev_attr_wwid.attr,
  1665. &dev_attr_uuid.attr,
  1666. &dev_attr_nguid.attr,
  1667. &dev_attr_eui.attr,
  1668. &dev_attr_nsid.attr,
  1669. NULL,
  1670. };
  1671. static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
  1672. struct attribute *a, int n)
  1673. {
  1674. struct device *dev = container_of(kobj, struct device, kobj);
  1675. struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
  1676. if (a == &dev_attr_uuid.attr) {
  1677. if (uuid_is_null(&ns->uuid) ||
  1678. !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
  1679. return 0;
  1680. }
  1681. if (a == &dev_attr_nguid.attr) {
  1682. if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
  1683. return 0;
  1684. }
  1685. if (a == &dev_attr_eui.attr) {
  1686. if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
  1687. return 0;
  1688. }
  1689. return a->mode;
  1690. }
  1691. static const struct attribute_group nvme_ns_attr_group = {
  1692. .attrs = nvme_ns_attrs,
  1693. .is_visible = nvme_ns_attrs_are_visible,
  1694. };
  1695. #define nvme_show_str_function(field) \
  1696. static ssize_t field##_show(struct device *dev, \
  1697. struct device_attribute *attr, char *buf) \
  1698. { \
  1699. struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
  1700. return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
  1701. } \
  1702. static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
  1703. #define nvme_show_int_function(field) \
  1704. static ssize_t field##_show(struct device *dev, \
  1705. struct device_attribute *attr, char *buf) \
  1706. { \
  1707. struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
  1708. return sprintf(buf, "%d\n", ctrl->field); \
  1709. } \
  1710. static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
  1711. nvme_show_str_function(model);
  1712. nvme_show_str_function(serial);
  1713. nvme_show_str_function(firmware_rev);
  1714. nvme_show_int_function(cntlid);
  1715. static ssize_t nvme_sysfs_delete(struct device *dev,
  1716. struct device_attribute *attr, const char *buf,
  1717. size_t count)
  1718. {
  1719. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1720. if (device_remove_file_self(dev, attr))
  1721. ctrl->ops->delete_ctrl(ctrl);
  1722. return count;
  1723. }
  1724. static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
  1725. static ssize_t nvme_sysfs_show_transport(struct device *dev,
  1726. struct device_attribute *attr,
  1727. char *buf)
  1728. {
  1729. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1730. return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
  1731. }
  1732. static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
  1733. static ssize_t nvme_sysfs_show_state(struct device *dev,
  1734. struct device_attribute *attr,
  1735. char *buf)
  1736. {
  1737. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1738. static const char *const state_name[] = {
  1739. [NVME_CTRL_NEW] = "new",
  1740. [NVME_CTRL_LIVE] = "live",
  1741. [NVME_CTRL_RESETTING] = "resetting",
  1742. [NVME_CTRL_RECONNECTING]= "reconnecting",
  1743. [NVME_CTRL_DELETING] = "deleting",
  1744. [NVME_CTRL_DEAD] = "dead",
  1745. };
  1746. if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
  1747. state_name[ctrl->state])
  1748. return sprintf(buf, "%s\n", state_name[ctrl->state]);
  1749. return sprintf(buf, "unknown state\n");
  1750. }
  1751. static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
  1752. static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
  1753. struct device_attribute *attr,
  1754. char *buf)
  1755. {
  1756. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1757. return snprintf(buf, PAGE_SIZE, "%s\n",
  1758. ctrl->ops->get_subsysnqn(ctrl));
  1759. }
  1760. static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
  1761. static ssize_t nvme_sysfs_show_address(struct device *dev,
  1762. struct device_attribute *attr,
  1763. char *buf)
  1764. {
  1765. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1766. return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
  1767. }
  1768. static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
  1769. static struct attribute *nvme_dev_attrs[] = {
  1770. &dev_attr_reset_controller.attr,
  1771. &dev_attr_rescan_controller.attr,
  1772. &dev_attr_model.attr,
  1773. &dev_attr_serial.attr,
  1774. &dev_attr_firmware_rev.attr,
  1775. &dev_attr_cntlid.attr,
  1776. &dev_attr_delete_controller.attr,
  1777. &dev_attr_transport.attr,
  1778. &dev_attr_subsysnqn.attr,
  1779. &dev_attr_address.attr,
  1780. &dev_attr_state.attr,
  1781. NULL
  1782. };
  1783. #define CHECK_ATTR(ctrl, a, name) \
  1784. if ((a) == &dev_attr_##name.attr && \
  1785. !(ctrl)->ops->get_##name) \
  1786. return 0
  1787. static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
  1788. struct attribute *a, int n)
  1789. {
  1790. struct device *dev = container_of(kobj, struct device, kobj);
  1791. struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
  1792. if (a == &dev_attr_delete_controller.attr) {
  1793. if (!ctrl->ops->delete_ctrl)
  1794. return 0;
  1795. }
  1796. CHECK_ATTR(ctrl, a, subsysnqn);
  1797. CHECK_ATTR(ctrl, a, address);
  1798. return a->mode;
  1799. }
  1800. static struct attribute_group nvme_dev_attrs_group = {
  1801. .attrs = nvme_dev_attrs,
  1802. .is_visible = nvme_dev_attrs_are_visible,
  1803. };
  1804. static const struct attribute_group *nvme_dev_attr_groups[] = {
  1805. &nvme_dev_attrs_group,
  1806. NULL,
  1807. };
  1808. static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
  1809. {
  1810. struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
  1811. struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
  1812. return nsa->ns_id - nsb->ns_id;
  1813. }
  1814. static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
  1815. {
  1816. struct nvme_ns *ns, *ret = NULL;
  1817. mutex_lock(&ctrl->namespaces_mutex);
  1818. list_for_each_entry(ns, &ctrl->namespaces, list) {
  1819. if (ns->ns_id == nsid) {
  1820. kref_get(&ns->kref);
  1821. ret = ns;
  1822. break;
  1823. }
  1824. if (ns->ns_id > nsid)
  1825. break;
  1826. }
  1827. mutex_unlock(&ctrl->namespaces_mutex);
  1828. return ret;
  1829. }
  1830. static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
  1831. {
  1832. struct nvme_ns *ns;
  1833. struct gendisk *disk;
  1834. struct nvme_id_ns *id;
  1835. char disk_name[DISK_NAME_LEN];
  1836. int node = dev_to_node(ctrl->dev);
  1837. ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
  1838. if (!ns)
  1839. return;
  1840. ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
  1841. if (ns->instance < 0)
  1842. goto out_free_ns;
  1843. ns->queue = blk_mq_init_queue(ctrl->tagset);
  1844. if (IS_ERR(ns->queue))
  1845. goto out_release_instance;
  1846. queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
  1847. ns->queue->queuedata = ns;
  1848. ns->ctrl = ctrl;
  1849. kref_init(&ns->kref);
  1850. ns->ns_id = nsid;
  1851. ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
  1852. blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
  1853. nvme_set_queue_limits(ctrl, ns->queue);
  1854. sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
  1855. if (nvme_revalidate_ns(ns, &id))
  1856. goto out_free_queue;
  1857. if (nvme_nvm_ns_supported(ns, id) &&
  1858. nvme_nvm_register(ns, disk_name, node)) {
  1859. dev_warn(ctrl->device, "%s: LightNVM init failure\n", __func__);
  1860. goto out_free_id;
  1861. }
  1862. disk = alloc_disk_node(0, node);
  1863. if (!disk)
  1864. goto out_free_id;
  1865. disk->fops = &nvme_fops;
  1866. disk->private_data = ns;
  1867. disk->queue = ns->queue;
  1868. disk->flags = GENHD_FL_EXT_DEVT;
  1869. memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
  1870. ns->disk = disk;
  1871. __nvme_revalidate_disk(disk, id);
  1872. mutex_lock(&ctrl->namespaces_mutex);
  1873. list_add_tail(&ns->list, &ctrl->namespaces);
  1874. mutex_unlock(&ctrl->namespaces_mutex);
  1875. kref_get(&ctrl->kref);
  1876. kfree(id);
  1877. device_add_disk(ctrl->device, ns->disk);
  1878. if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
  1879. &nvme_ns_attr_group))
  1880. pr_warn("%s: failed to create sysfs group for identification\n",
  1881. ns->disk->disk_name);
  1882. if (ns->ndev && nvme_nvm_register_sysfs(ns))
  1883. pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
  1884. ns->disk->disk_name);
  1885. return;
  1886. out_free_id:
  1887. kfree(id);
  1888. out_free_queue:
  1889. blk_cleanup_queue(ns->queue);
  1890. out_release_instance:
  1891. ida_simple_remove(&ctrl->ns_ida, ns->instance);
  1892. out_free_ns:
  1893. kfree(ns);
  1894. }
  1895. static void nvme_ns_remove(struct nvme_ns *ns)
  1896. {
  1897. if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
  1898. return;
  1899. if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
  1900. if (blk_get_integrity(ns->disk))
  1901. blk_integrity_unregister(ns->disk);
  1902. sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
  1903. &nvme_ns_attr_group);
  1904. if (ns->ndev)
  1905. nvme_nvm_unregister_sysfs(ns);
  1906. del_gendisk(ns->disk);
  1907. blk_cleanup_queue(ns->queue);
  1908. }
  1909. mutex_lock(&ns->ctrl->namespaces_mutex);
  1910. list_del_init(&ns->list);
  1911. mutex_unlock(&ns->ctrl->namespaces_mutex);
  1912. nvme_put_ns(ns);
  1913. }
  1914. static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
  1915. {
  1916. struct nvme_ns *ns;
  1917. ns = nvme_find_get_ns(ctrl, nsid);
  1918. if (ns) {
  1919. if (ns->disk && revalidate_disk(ns->disk))
  1920. nvme_ns_remove(ns);
  1921. nvme_put_ns(ns);
  1922. } else
  1923. nvme_alloc_ns(ctrl, nsid);
  1924. }
  1925. static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
  1926. unsigned nsid)
  1927. {
  1928. struct nvme_ns *ns, *next;
  1929. list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
  1930. if (ns->ns_id > nsid)
  1931. nvme_ns_remove(ns);
  1932. }
  1933. }
  1934. static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
  1935. {
  1936. struct nvme_ns *ns;
  1937. __le32 *ns_list;
  1938. unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
  1939. int ret = 0;
  1940. ns_list = kzalloc(0x1000, GFP_KERNEL);
  1941. if (!ns_list)
  1942. return -ENOMEM;
  1943. for (i = 0; i < num_lists; i++) {
  1944. ret = nvme_identify_ns_list(ctrl, prev, ns_list);
  1945. if (ret)
  1946. goto free;
  1947. for (j = 0; j < min(nn, 1024U); j++) {
  1948. nsid = le32_to_cpu(ns_list[j]);
  1949. if (!nsid)
  1950. goto out;
  1951. nvme_validate_ns(ctrl, nsid);
  1952. while (++prev < nsid) {
  1953. ns = nvme_find_get_ns(ctrl, prev);
  1954. if (ns) {
  1955. nvme_ns_remove(ns);
  1956. nvme_put_ns(ns);
  1957. }
  1958. }
  1959. }
  1960. nn -= j;
  1961. }
  1962. out:
  1963. nvme_remove_invalid_namespaces(ctrl, prev);
  1964. free:
  1965. kfree(ns_list);
  1966. return ret;
  1967. }
  1968. static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
  1969. {
  1970. unsigned i;
  1971. for (i = 1; i <= nn; i++)
  1972. nvme_validate_ns(ctrl, i);
  1973. nvme_remove_invalid_namespaces(ctrl, nn);
  1974. }
  1975. static void nvme_scan_work(struct work_struct *work)
  1976. {
  1977. struct nvme_ctrl *ctrl =
  1978. container_of(work, struct nvme_ctrl, scan_work);
  1979. struct nvme_id_ctrl *id;
  1980. unsigned nn;
  1981. if (ctrl->state != NVME_CTRL_LIVE)
  1982. return;
  1983. if (nvme_identify_ctrl(ctrl, &id))
  1984. return;
  1985. nn = le32_to_cpu(id->nn);
  1986. if (ctrl->vs >= NVME_VS(1, 1, 0) &&
  1987. !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
  1988. if (!nvme_scan_ns_list(ctrl, nn))
  1989. goto done;
  1990. }
  1991. nvme_scan_ns_sequential(ctrl, nn);
  1992. done:
  1993. mutex_lock(&ctrl->namespaces_mutex);
  1994. list_sort(NULL, &ctrl->namespaces, ns_cmp);
  1995. mutex_unlock(&ctrl->namespaces_mutex);
  1996. kfree(id);
  1997. }
  1998. void nvme_queue_scan(struct nvme_ctrl *ctrl)
  1999. {
  2000. /*
  2001. * Do not queue new scan work when a controller is reset during
  2002. * removal.
  2003. */
  2004. if (ctrl->state == NVME_CTRL_LIVE)
  2005. queue_work(nvme_wq, &ctrl->scan_work);
  2006. }
  2007. EXPORT_SYMBOL_GPL(nvme_queue_scan);
  2008. /*
  2009. * This function iterates the namespace list unlocked to allow recovery from
  2010. * controller failure. It is up to the caller to ensure the namespace list is
  2011. * not modified by scan work while this function is executing.
  2012. */
  2013. void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
  2014. {
  2015. struct nvme_ns *ns, *next;
  2016. /*
  2017. * The dead states indicates the controller was not gracefully
  2018. * disconnected. In that case, we won't be able to flush any data while
  2019. * removing the namespaces' disks; fail all the queues now to avoid
  2020. * potentially having to clean up the failed sync later.
  2021. */
  2022. if (ctrl->state == NVME_CTRL_DEAD)
  2023. nvme_kill_queues(ctrl);
  2024. list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
  2025. nvme_ns_remove(ns);
  2026. }
  2027. EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
  2028. static void nvme_async_event_work(struct work_struct *work)
  2029. {
  2030. struct nvme_ctrl *ctrl =
  2031. container_of(work, struct nvme_ctrl, async_event_work);
  2032. spin_lock_irq(&ctrl->lock);
  2033. while (ctrl->event_limit > 0) {
  2034. int aer_idx = --ctrl->event_limit;
  2035. spin_unlock_irq(&ctrl->lock);
  2036. ctrl->ops->submit_async_event(ctrl, aer_idx);
  2037. spin_lock_irq(&ctrl->lock);
  2038. }
  2039. spin_unlock_irq(&ctrl->lock);
  2040. }
  2041. void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
  2042. union nvme_result *res)
  2043. {
  2044. u32 result = le32_to_cpu(res->u32);
  2045. bool done = true;
  2046. switch (le16_to_cpu(status) >> 1) {
  2047. case NVME_SC_SUCCESS:
  2048. done = false;
  2049. /*FALLTHRU*/
  2050. case NVME_SC_ABORT_REQ:
  2051. ++ctrl->event_limit;
  2052. queue_work(nvme_wq, &ctrl->async_event_work);
  2053. break;
  2054. default:
  2055. break;
  2056. }
  2057. if (done)
  2058. return;
  2059. switch (result & 0xff07) {
  2060. case NVME_AER_NOTICE_NS_CHANGED:
  2061. dev_info(ctrl->device, "rescanning\n");
  2062. nvme_queue_scan(ctrl);
  2063. break;
  2064. default:
  2065. dev_warn(ctrl->device, "async event result %08x\n", result);
  2066. }
  2067. }
  2068. EXPORT_SYMBOL_GPL(nvme_complete_async_event);
  2069. void nvme_queue_async_events(struct nvme_ctrl *ctrl)
  2070. {
  2071. ctrl->event_limit = NVME_NR_AERS;
  2072. queue_work(nvme_wq, &ctrl->async_event_work);
  2073. }
  2074. EXPORT_SYMBOL_GPL(nvme_queue_async_events);
  2075. static DEFINE_IDA(nvme_instance_ida);
  2076. static int nvme_set_instance(struct nvme_ctrl *ctrl)
  2077. {
  2078. int instance, error;
  2079. do {
  2080. if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
  2081. return -ENODEV;
  2082. spin_lock(&dev_list_lock);
  2083. error = ida_get_new(&nvme_instance_ida, &instance);
  2084. spin_unlock(&dev_list_lock);
  2085. } while (error == -EAGAIN);
  2086. if (error)
  2087. return -ENODEV;
  2088. ctrl->instance = instance;
  2089. return 0;
  2090. }
  2091. static void nvme_release_instance(struct nvme_ctrl *ctrl)
  2092. {
  2093. spin_lock(&dev_list_lock);
  2094. ida_remove(&nvme_instance_ida, ctrl->instance);
  2095. spin_unlock(&dev_list_lock);
  2096. }
  2097. void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
  2098. {
  2099. flush_work(&ctrl->async_event_work);
  2100. flush_work(&ctrl->scan_work);
  2101. nvme_remove_namespaces(ctrl);
  2102. device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
  2103. spin_lock(&dev_list_lock);
  2104. list_del(&ctrl->node);
  2105. spin_unlock(&dev_list_lock);
  2106. }
  2107. EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
  2108. static void nvme_free_ctrl(struct kref *kref)
  2109. {
  2110. struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
  2111. put_device(ctrl->device);
  2112. nvme_release_instance(ctrl);
  2113. ida_destroy(&ctrl->ns_ida);
  2114. ctrl->ops->free_ctrl(ctrl);
  2115. }
  2116. void nvme_put_ctrl(struct nvme_ctrl *ctrl)
  2117. {
  2118. kref_put(&ctrl->kref, nvme_free_ctrl);
  2119. }
  2120. EXPORT_SYMBOL_GPL(nvme_put_ctrl);
  2121. /*
  2122. * Initialize a NVMe controller structures. This needs to be called during
  2123. * earliest initialization so that we have the initialized structured around
  2124. * during probing.
  2125. */
  2126. int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
  2127. const struct nvme_ctrl_ops *ops, unsigned long quirks)
  2128. {
  2129. int ret;
  2130. ctrl->state = NVME_CTRL_NEW;
  2131. spin_lock_init(&ctrl->lock);
  2132. INIT_LIST_HEAD(&ctrl->namespaces);
  2133. mutex_init(&ctrl->namespaces_mutex);
  2134. kref_init(&ctrl->kref);
  2135. ctrl->dev = dev;
  2136. ctrl->ops = ops;
  2137. ctrl->quirks = quirks;
  2138. INIT_WORK(&ctrl->scan_work, nvme_scan_work);
  2139. INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
  2140. ret = nvme_set_instance(ctrl);
  2141. if (ret)
  2142. goto out;
  2143. ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
  2144. MKDEV(nvme_char_major, ctrl->instance),
  2145. ctrl, nvme_dev_attr_groups,
  2146. "nvme%d", ctrl->instance);
  2147. if (IS_ERR(ctrl->device)) {
  2148. ret = PTR_ERR(ctrl->device);
  2149. goto out_release_instance;
  2150. }
  2151. get_device(ctrl->device);
  2152. ida_init(&ctrl->ns_ida);
  2153. spin_lock(&dev_list_lock);
  2154. list_add_tail(&ctrl->node, &nvme_ctrl_list);
  2155. spin_unlock(&dev_list_lock);
  2156. /*
  2157. * Initialize latency tolerance controls. The sysfs files won't
  2158. * be visible to userspace unless the device actually supports APST.
  2159. */
  2160. ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
  2161. dev_pm_qos_update_user_latency_tolerance(ctrl->device,
  2162. min(default_ps_max_latency_us, (unsigned long)S32_MAX));
  2163. return 0;
  2164. out_release_instance:
  2165. nvme_release_instance(ctrl);
  2166. out:
  2167. return ret;
  2168. }
  2169. EXPORT_SYMBOL_GPL(nvme_init_ctrl);
  2170. /**
  2171. * nvme_kill_queues(): Ends all namespace queues
  2172. * @ctrl: the dead controller that needs to end
  2173. *
  2174. * Call this function when the driver determines it is unable to get the
  2175. * controller in a state capable of servicing IO.
  2176. */
  2177. void nvme_kill_queues(struct nvme_ctrl *ctrl)
  2178. {
  2179. struct nvme_ns *ns;
  2180. mutex_lock(&ctrl->namespaces_mutex);
  2181. /* Forcibly start all queues to avoid having stuck requests */
  2182. blk_mq_start_hw_queues(ctrl->admin_q);
  2183. list_for_each_entry(ns, &ctrl->namespaces, list) {
  2184. /*
  2185. * Revalidating a dead namespace sets capacity to 0. This will
  2186. * end buffered writers dirtying pages that can't be synced.
  2187. */
  2188. if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
  2189. continue;
  2190. revalidate_disk(ns->disk);
  2191. blk_set_queue_dying(ns->queue);
  2192. /*
  2193. * Forcibly start all queues to avoid having stuck requests.
  2194. * Note that we must ensure the queues are not stopped
  2195. * when the final removal happens.
  2196. */
  2197. blk_mq_start_hw_queues(ns->queue);
  2198. /* draining requests in requeue list */
  2199. blk_mq_kick_requeue_list(ns->queue);
  2200. }
  2201. mutex_unlock(&ctrl->namespaces_mutex);
  2202. }
  2203. EXPORT_SYMBOL_GPL(nvme_kill_queues);
  2204. void nvme_unfreeze(struct nvme_ctrl *ctrl)
  2205. {
  2206. struct nvme_ns *ns;
  2207. mutex_lock(&ctrl->namespaces_mutex);
  2208. list_for_each_entry(ns, &ctrl->namespaces, list)
  2209. blk_mq_unfreeze_queue(ns->queue);
  2210. mutex_unlock(&ctrl->namespaces_mutex);
  2211. }
  2212. EXPORT_SYMBOL_GPL(nvme_unfreeze);
  2213. void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
  2214. {
  2215. struct nvme_ns *ns;
  2216. mutex_lock(&ctrl->namespaces_mutex);
  2217. list_for_each_entry(ns, &ctrl->namespaces, list) {
  2218. timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
  2219. if (timeout <= 0)
  2220. break;
  2221. }
  2222. mutex_unlock(&ctrl->namespaces_mutex);
  2223. }
  2224. EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
  2225. void nvme_wait_freeze(struct nvme_ctrl *ctrl)
  2226. {
  2227. struct nvme_ns *ns;
  2228. mutex_lock(&ctrl->namespaces_mutex);
  2229. list_for_each_entry(ns, &ctrl->namespaces, list)
  2230. blk_mq_freeze_queue_wait(ns->queue);
  2231. mutex_unlock(&ctrl->namespaces_mutex);
  2232. }
  2233. EXPORT_SYMBOL_GPL(nvme_wait_freeze);
  2234. void nvme_start_freeze(struct nvme_ctrl *ctrl)
  2235. {
  2236. struct nvme_ns *ns;
  2237. mutex_lock(&ctrl->namespaces_mutex);
  2238. list_for_each_entry(ns, &ctrl->namespaces, list)
  2239. blk_freeze_queue_start(ns->queue);
  2240. mutex_unlock(&ctrl->namespaces_mutex);
  2241. }
  2242. EXPORT_SYMBOL_GPL(nvme_start_freeze);
  2243. void nvme_stop_queues(struct nvme_ctrl *ctrl)
  2244. {
  2245. struct nvme_ns *ns;
  2246. mutex_lock(&ctrl->namespaces_mutex);
  2247. list_for_each_entry(ns, &ctrl->namespaces, list)
  2248. blk_mq_quiesce_queue(ns->queue);
  2249. mutex_unlock(&ctrl->namespaces_mutex);
  2250. }
  2251. EXPORT_SYMBOL_GPL(nvme_stop_queues);
  2252. void nvme_start_queues(struct nvme_ctrl *ctrl)
  2253. {
  2254. struct nvme_ns *ns;
  2255. mutex_lock(&ctrl->namespaces_mutex);
  2256. list_for_each_entry(ns, &ctrl->namespaces, list) {
  2257. blk_mq_start_stopped_hw_queues(ns->queue, true);
  2258. blk_mq_kick_requeue_list(ns->queue);
  2259. }
  2260. mutex_unlock(&ctrl->namespaces_mutex);
  2261. }
  2262. EXPORT_SYMBOL_GPL(nvme_start_queues);
  2263. int __init nvme_core_init(void)
  2264. {
  2265. int result;
  2266. nvme_wq = alloc_workqueue("nvme-wq",
  2267. WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
  2268. if (!nvme_wq)
  2269. return -ENOMEM;
  2270. result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
  2271. &nvme_dev_fops);
  2272. if (result < 0)
  2273. goto destroy_wq;
  2274. else if (result > 0)
  2275. nvme_char_major = result;
  2276. nvme_class = class_create(THIS_MODULE, "nvme");
  2277. if (IS_ERR(nvme_class)) {
  2278. result = PTR_ERR(nvme_class);
  2279. goto unregister_chrdev;
  2280. }
  2281. return 0;
  2282. unregister_chrdev:
  2283. __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
  2284. destroy_wq:
  2285. destroy_workqueue(nvme_wq);
  2286. return result;
  2287. }
  2288. void nvme_core_exit(void)
  2289. {
  2290. class_destroy(nvme_class);
  2291. __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
  2292. destroy_workqueue(nvme_wq);
  2293. }
  2294. MODULE_LICENSE("GPL");
  2295. MODULE_VERSION("1.0");
  2296. module_init(nvme_core_init);
  2297. module_exit(nvme_core_exit);