scsi_lib.c 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 1999 Eric Youngdale
  4. * Copyright (C) 2014 Christoph Hellwig
  5. *
  6. * SCSI queueing library.
  7. * Initial versions: Eric Youngdale (eric@andante.org).
  8. * Based upon conversations with large numbers
  9. * of people at Linux Expo.
  10. */
  11. #include <linux/bio.h>
  12. #include <linux/bitops.h>
  13. #include <linux/blkdev.h>
  14. #include <linux/completion.h>
  15. #include <linux/kernel.h>
  16. #include <linux/export.h>
  17. #include <linux/init.h>
  18. #include <linux/pci.h>
  19. #include <linux/delay.h>
  20. #include <linux/hardirq.h>
  21. #include <linux/scatterlist.h>
  22. #include <linux/blk-mq.h>
  23. #include <linux/ratelimit.h>
  24. #include <asm/unaligned.h>
  25. #include <scsi/scsi.h>
  26. #include <scsi/scsi_cmnd.h>
  27. #include <scsi/scsi_dbg.h>
  28. #include <scsi/scsi_device.h>
  29. #include <scsi/scsi_driver.h>
  30. #include <scsi/scsi_eh.h>
  31. #include <scsi/scsi_host.h>
  32. #include <scsi/scsi_transport.h> /* __scsi_init_queue() */
  33. #include <scsi/scsi_dh.h>
  34. #include <trace/events/scsi.h>
  35. #include "scsi_debugfs.h"
  36. #include "scsi_priv.h"
  37. #include "scsi_logging.h"
  38. /*
  39. * Size of integrity metadata is usually small, 1 inline sg should
  40. * cover normal cases.
  41. */
  42. #ifdef CONFIG_ARCH_NO_SG_CHAIN
  43. #define SCSI_INLINE_PROT_SG_CNT 0
  44. #define SCSI_INLINE_SG_CNT 0
  45. #else
  46. #define SCSI_INLINE_PROT_SG_CNT 1
  47. #define SCSI_INLINE_SG_CNT 2
  48. #endif
  49. static struct kmem_cache *scsi_sense_cache;
  50. static struct kmem_cache *scsi_sense_isadma_cache;
  51. static DEFINE_MUTEX(scsi_sense_cache_mutex);
  52. static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd);
  53. static inline struct kmem_cache *
  54. scsi_select_sense_cache(bool unchecked_isa_dma)
  55. {
  56. return unchecked_isa_dma ? scsi_sense_isadma_cache : scsi_sense_cache;
  57. }
  58. static void scsi_free_sense_buffer(bool unchecked_isa_dma,
  59. unsigned char *sense_buffer)
  60. {
  61. kmem_cache_free(scsi_select_sense_cache(unchecked_isa_dma),
  62. sense_buffer);
  63. }
  64. static unsigned char *scsi_alloc_sense_buffer(bool unchecked_isa_dma,
  65. gfp_t gfp_mask, int numa_node)
  66. {
  67. return kmem_cache_alloc_node(scsi_select_sense_cache(unchecked_isa_dma),
  68. gfp_mask, numa_node);
  69. }
  70. int scsi_init_sense_cache(struct Scsi_Host *shost)
  71. {
  72. struct kmem_cache *cache;
  73. int ret = 0;
  74. mutex_lock(&scsi_sense_cache_mutex);
  75. cache = scsi_select_sense_cache(shost->unchecked_isa_dma);
  76. if (cache)
  77. goto exit;
  78. if (shost->unchecked_isa_dma) {
  79. scsi_sense_isadma_cache =
  80. kmem_cache_create("scsi_sense_cache(DMA)",
  81. SCSI_SENSE_BUFFERSIZE, 0,
  82. SLAB_HWCACHE_ALIGN | SLAB_CACHE_DMA, NULL);
  83. if (!scsi_sense_isadma_cache)
  84. ret = -ENOMEM;
  85. } else {
  86. scsi_sense_cache =
  87. kmem_cache_create_usercopy("scsi_sense_cache",
  88. SCSI_SENSE_BUFFERSIZE, 0, SLAB_HWCACHE_ALIGN,
  89. 0, SCSI_SENSE_BUFFERSIZE, NULL);
  90. if (!scsi_sense_cache)
  91. ret = -ENOMEM;
  92. }
  93. exit:
  94. mutex_unlock(&scsi_sense_cache_mutex);
  95. return ret;
  96. }
  97. /*
  98. * When to reinvoke queueing after a resource shortage. It's 3 msecs to
  99. * not change behaviour from the previous unplug mechanism, experimentation
  100. * may prove this needs changing.
  101. */
  102. #define SCSI_QUEUE_DELAY 3
  103. static void
  104. scsi_set_blocked(struct scsi_cmnd *cmd, int reason)
  105. {
  106. struct Scsi_Host *host = cmd->device->host;
  107. struct scsi_device *device = cmd->device;
  108. struct scsi_target *starget = scsi_target(device);
  109. /*
  110. * Set the appropriate busy bit for the device/host.
  111. *
  112. * If the host/device isn't busy, assume that something actually
  113. * completed, and that we should be able to queue a command now.
  114. *
  115. * Note that the prior mid-layer assumption that any host could
  116. * always queue at least one command is now broken. The mid-layer
  117. * will implement a user specifiable stall (see
  118. * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
  119. * if a command is requeued with no other commands outstanding
  120. * either for the device or for the host.
  121. */
  122. switch (reason) {
  123. case SCSI_MLQUEUE_HOST_BUSY:
  124. atomic_set(&host->host_blocked, host->max_host_blocked);
  125. break;
  126. case SCSI_MLQUEUE_DEVICE_BUSY:
  127. case SCSI_MLQUEUE_EH_RETRY:
  128. atomic_set(&device->device_blocked,
  129. device->max_device_blocked);
  130. break;
  131. case SCSI_MLQUEUE_TARGET_BUSY:
  132. atomic_set(&starget->target_blocked,
  133. starget->max_target_blocked);
  134. break;
  135. }
  136. }
  137. static void scsi_mq_requeue_cmd(struct scsi_cmnd *cmd)
  138. {
  139. if (cmd->request->rq_flags & RQF_DONTPREP) {
  140. cmd->request->rq_flags &= ~RQF_DONTPREP;
  141. scsi_mq_uninit_cmd(cmd);
  142. } else {
  143. WARN_ON_ONCE(true);
  144. }
  145. blk_mq_requeue_request(cmd->request, true);
  146. }
  147. /**
  148. * __scsi_queue_insert - private queue insertion
  149. * @cmd: The SCSI command being requeued
  150. * @reason: The reason for the requeue
  151. * @unbusy: Whether the queue should be unbusied
  152. *
  153. * This is a private queue insertion. The public interface
  154. * scsi_queue_insert() always assumes the queue should be unbusied
  155. * because it's always called before the completion. This function is
  156. * for a requeue after completion, which should only occur in this
  157. * file.
  158. */
  159. static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, bool unbusy)
  160. {
  161. struct scsi_device *device = cmd->device;
  162. SCSI_LOG_MLQUEUE(1, scmd_printk(KERN_INFO, cmd,
  163. "Inserting command %p into mlqueue\n", cmd));
  164. scsi_set_blocked(cmd, reason);
  165. /*
  166. * Decrement the counters, since these commands are no longer
  167. * active on the host/device.
  168. */
  169. if (unbusy)
  170. scsi_device_unbusy(device, cmd);
  171. /*
  172. * Requeue this command. It will go before all other commands
  173. * that are already in the queue. Schedule requeue work under
  174. * lock such that the kblockd_schedule_work() call happens
  175. * before blk_cleanup_queue() finishes.
  176. */
  177. cmd->result = 0;
  178. blk_mq_requeue_request(cmd->request, true);
  179. }
  180. /**
  181. * scsi_queue_insert - Reinsert a command in the queue.
  182. * @cmd: command that we are adding to queue.
  183. * @reason: why we are inserting command to queue.
  184. *
  185. * We do this for one of two cases. Either the host is busy and it cannot accept
  186. * any more commands for the time being, or the device returned QUEUE_FULL and
  187. * can accept no more commands.
  188. *
  189. * Context: This could be called either from an interrupt context or a normal
  190. * process context.
  191. */
  192. void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
  193. {
  194. __scsi_queue_insert(cmd, reason, true);
  195. }
  196. /**
  197. * __scsi_execute - insert request and wait for the result
  198. * @sdev: scsi device
  199. * @cmd: scsi command
  200. * @data_direction: data direction
  201. * @buffer: data buffer
  202. * @bufflen: len of buffer
  203. * @sense: optional sense buffer
  204. * @sshdr: optional decoded sense header
  205. * @timeout: request timeout in seconds
  206. * @retries: number of times to retry request
  207. * @flags: flags for ->cmd_flags
  208. * @rq_flags: flags for ->rq_flags
  209. * @resid: optional residual length
  210. *
  211. * Returns the scsi_cmnd result field if a command was executed, or a negative
  212. * Linux error code if we didn't get that far.
  213. */
  214. int __scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
  215. int data_direction, void *buffer, unsigned bufflen,
  216. unsigned char *sense, struct scsi_sense_hdr *sshdr,
  217. int timeout, int retries, u64 flags, req_flags_t rq_flags,
  218. int *resid)
  219. {
  220. struct request *req;
  221. struct scsi_request *rq;
  222. int ret = DRIVER_ERROR << 24;
  223. req = blk_get_request(sdev->request_queue,
  224. data_direction == DMA_TO_DEVICE ?
  225. REQ_OP_SCSI_OUT : REQ_OP_SCSI_IN,
  226. rq_flags & RQF_PM ? BLK_MQ_REQ_PM : 0);
  227. if (IS_ERR(req))
  228. return ret;
  229. rq = scsi_req(req);
  230. if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
  231. buffer, bufflen, GFP_NOIO))
  232. goto out;
  233. rq->cmd_len = COMMAND_SIZE(cmd[0]);
  234. memcpy(rq->cmd, cmd, rq->cmd_len);
  235. rq->retries = retries;
  236. req->timeout = timeout;
  237. req->cmd_flags |= flags;
  238. req->rq_flags |= rq_flags | RQF_QUIET;
  239. /*
  240. * head injection *required* here otherwise quiesce won't work
  241. */
  242. blk_execute_rq(req->q, NULL, req, 1);
  243. /*
  244. * Some devices (USB mass-storage in particular) may transfer
  245. * garbage data together with a residue indicating that the data
  246. * is invalid. Prevent the garbage from being misinterpreted
  247. * and prevent security leaks by zeroing out the excess data.
  248. */
  249. if (unlikely(rq->resid_len > 0 && rq->resid_len <= bufflen))
  250. memset(buffer + (bufflen - rq->resid_len), 0, rq->resid_len);
  251. if (resid)
  252. *resid = rq->resid_len;
  253. if (sense && rq->sense_len)
  254. memcpy(sense, rq->sense, SCSI_SENSE_BUFFERSIZE);
  255. if (sshdr)
  256. scsi_normalize_sense(rq->sense, rq->sense_len, sshdr);
  257. ret = rq->result;
  258. out:
  259. blk_put_request(req);
  260. return ret;
  261. }
  262. EXPORT_SYMBOL(__scsi_execute);
  263. /*
  264. * Wake up the error handler if necessary. Avoid as follows that the error
  265. * handler is not woken up if host in-flight requests number ==
  266. * shost->host_failed: use call_rcu() in scsi_eh_scmd_add() in combination
  267. * with an RCU read lock in this function to ensure that this function in
  268. * its entirety either finishes before scsi_eh_scmd_add() increases the
  269. * host_failed counter or that it notices the shost state change made by
  270. * scsi_eh_scmd_add().
  271. */
  272. static void scsi_dec_host_busy(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
  273. {
  274. unsigned long flags;
  275. rcu_read_lock();
  276. __clear_bit(SCMD_STATE_INFLIGHT, &cmd->state);
  277. if (unlikely(scsi_host_in_recovery(shost))) {
  278. spin_lock_irqsave(shost->host_lock, flags);
  279. if (shost->host_failed || shost->host_eh_scheduled)
  280. scsi_eh_wakeup(shost);
  281. spin_unlock_irqrestore(shost->host_lock, flags);
  282. }
  283. rcu_read_unlock();
  284. }
  285. void scsi_device_unbusy(struct scsi_device *sdev, struct scsi_cmnd *cmd)
  286. {
  287. struct Scsi_Host *shost = sdev->host;
  288. struct scsi_target *starget = scsi_target(sdev);
  289. scsi_dec_host_busy(shost, cmd);
  290. if (starget->can_queue > 0)
  291. atomic_dec(&starget->target_busy);
  292. atomic_dec(&sdev->device_busy);
  293. }
  294. static void scsi_kick_queue(struct request_queue *q)
  295. {
  296. blk_mq_run_hw_queues(q, false);
  297. }
  298. /*
  299. * Called for single_lun devices on IO completion. Clear starget_sdev_user,
  300. * and call blk_run_queue for all the scsi_devices on the target -
  301. * including current_sdev first.
  302. *
  303. * Called with *no* scsi locks held.
  304. */
  305. static void scsi_single_lun_run(struct scsi_device *current_sdev)
  306. {
  307. struct Scsi_Host *shost = current_sdev->host;
  308. struct scsi_device *sdev, *tmp;
  309. struct scsi_target *starget = scsi_target(current_sdev);
  310. unsigned long flags;
  311. spin_lock_irqsave(shost->host_lock, flags);
  312. starget->starget_sdev_user = NULL;
  313. spin_unlock_irqrestore(shost->host_lock, flags);
  314. /*
  315. * Call blk_run_queue for all LUNs on the target, starting with
  316. * current_sdev. We race with others (to set starget_sdev_user),
  317. * but in most cases, we will be first. Ideally, each LU on the
  318. * target would get some limited time or requests on the target.
  319. */
  320. scsi_kick_queue(current_sdev->request_queue);
  321. spin_lock_irqsave(shost->host_lock, flags);
  322. if (starget->starget_sdev_user)
  323. goto out;
  324. list_for_each_entry_safe(sdev, tmp, &starget->devices,
  325. same_target_siblings) {
  326. if (sdev == current_sdev)
  327. continue;
  328. if (scsi_device_get(sdev))
  329. continue;
  330. spin_unlock_irqrestore(shost->host_lock, flags);
  331. scsi_kick_queue(sdev->request_queue);
  332. spin_lock_irqsave(shost->host_lock, flags);
  333. scsi_device_put(sdev);
  334. }
  335. out:
  336. spin_unlock_irqrestore(shost->host_lock, flags);
  337. }
  338. static inline bool scsi_device_is_busy(struct scsi_device *sdev)
  339. {
  340. if (atomic_read(&sdev->device_busy) >= sdev->queue_depth)
  341. return true;
  342. if (atomic_read(&sdev->device_blocked) > 0)
  343. return true;
  344. return false;
  345. }
  346. static inline bool scsi_target_is_busy(struct scsi_target *starget)
  347. {
  348. if (starget->can_queue > 0) {
  349. if (atomic_read(&starget->target_busy) >= starget->can_queue)
  350. return true;
  351. if (atomic_read(&starget->target_blocked) > 0)
  352. return true;
  353. }
  354. return false;
  355. }
  356. static inline bool scsi_host_is_busy(struct Scsi_Host *shost)
  357. {
  358. if (atomic_read(&shost->host_blocked) > 0)
  359. return true;
  360. if (shost->host_self_blocked)
  361. return true;
  362. return false;
  363. }
  364. static void scsi_starved_list_run(struct Scsi_Host *shost)
  365. {
  366. LIST_HEAD(starved_list);
  367. struct scsi_device *sdev;
  368. unsigned long flags;
  369. spin_lock_irqsave(shost->host_lock, flags);
  370. list_splice_init(&shost->starved_list, &starved_list);
  371. while (!list_empty(&starved_list)) {
  372. struct request_queue *slq;
  373. /*
  374. * As long as shost is accepting commands and we have
  375. * starved queues, call blk_run_queue. scsi_request_fn
  376. * drops the queue_lock and can add us back to the
  377. * starved_list.
  378. *
  379. * host_lock protects the starved_list and starved_entry.
  380. * scsi_request_fn must get the host_lock before checking
  381. * or modifying starved_list or starved_entry.
  382. */
  383. if (scsi_host_is_busy(shost))
  384. break;
  385. sdev = list_entry(starved_list.next,
  386. struct scsi_device, starved_entry);
  387. list_del_init(&sdev->starved_entry);
  388. if (scsi_target_is_busy(scsi_target(sdev))) {
  389. list_move_tail(&sdev->starved_entry,
  390. &shost->starved_list);
  391. continue;
  392. }
  393. /*
  394. * Once we drop the host lock, a racing scsi_remove_device()
  395. * call may remove the sdev from the starved list and destroy
  396. * it and the queue. Mitigate by taking a reference to the
  397. * queue and never touching the sdev again after we drop the
  398. * host lock. Note: if __scsi_remove_device() invokes
  399. * blk_cleanup_queue() before the queue is run from this
  400. * function then blk_run_queue() will return immediately since
  401. * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
  402. */
  403. slq = sdev->request_queue;
  404. if (!blk_get_queue(slq))
  405. continue;
  406. spin_unlock_irqrestore(shost->host_lock, flags);
  407. scsi_kick_queue(slq);
  408. blk_put_queue(slq);
  409. spin_lock_irqsave(shost->host_lock, flags);
  410. }
  411. /* put any unprocessed entries back */
  412. list_splice(&starved_list, &shost->starved_list);
  413. spin_unlock_irqrestore(shost->host_lock, flags);
  414. }
  415. /**
  416. * scsi_run_queue - Select a proper request queue to serve next.
  417. * @q: last request's queue
  418. *
  419. * The previous command was completely finished, start a new one if possible.
  420. */
  421. static void scsi_run_queue(struct request_queue *q)
  422. {
  423. struct scsi_device *sdev = q->queuedata;
  424. if (scsi_target(sdev)->single_lun)
  425. scsi_single_lun_run(sdev);
  426. if (!list_empty(&sdev->host->starved_list))
  427. scsi_starved_list_run(sdev->host);
  428. blk_mq_run_hw_queues(q, false);
  429. }
  430. void scsi_requeue_run_queue(struct work_struct *work)
  431. {
  432. struct scsi_device *sdev;
  433. struct request_queue *q;
  434. sdev = container_of(work, struct scsi_device, requeue_work);
  435. q = sdev->request_queue;
  436. scsi_run_queue(q);
  437. }
  438. void scsi_run_host_queues(struct Scsi_Host *shost)
  439. {
  440. struct scsi_device *sdev;
  441. shost_for_each_device(sdev, shost)
  442. scsi_run_queue(sdev->request_queue);
  443. }
  444. static void scsi_uninit_cmd(struct scsi_cmnd *cmd)
  445. {
  446. if (!blk_rq_is_passthrough(cmd->request)) {
  447. struct scsi_driver *drv = scsi_cmd_to_driver(cmd);
  448. if (drv->uninit_command)
  449. drv->uninit_command(cmd);
  450. }
  451. }
  452. void scsi_free_sgtables(struct scsi_cmnd *cmd)
  453. {
  454. if (cmd->sdb.table.nents)
  455. sg_free_table_chained(&cmd->sdb.table,
  456. SCSI_INLINE_SG_CNT);
  457. if (scsi_prot_sg_count(cmd))
  458. sg_free_table_chained(&cmd->prot_sdb->table,
  459. SCSI_INLINE_PROT_SG_CNT);
  460. }
  461. EXPORT_SYMBOL_GPL(scsi_free_sgtables);
  462. static void scsi_mq_uninit_cmd(struct scsi_cmnd *cmd)
  463. {
  464. scsi_free_sgtables(cmd);
  465. scsi_uninit_cmd(cmd);
  466. }
  467. static void scsi_run_queue_async(struct scsi_device *sdev)
  468. {
  469. if (scsi_target(sdev)->single_lun ||
  470. !list_empty(&sdev->host->starved_list)) {
  471. kblockd_schedule_work(&sdev->requeue_work);
  472. } else {
  473. /*
  474. * smp_mb() present in sbitmap_queue_clear() or implied in
  475. * .end_io is for ordering writing .device_busy in
  476. * scsi_device_unbusy() and reading sdev->restarts.
  477. */
  478. int old = atomic_read(&sdev->restarts);
  479. /*
  480. * ->restarts has to be kept as non-zero if new budget
  481. * contention occurs.
  482. *
  483. * No need to run queue when either another re-run
  484. * queue wins in updating ->restarts or a new budget
  485. * contention occurs.
  486. */
  487. if (old && atomic_cmpxchg(&sdev->restarts, old, 0) == old)
  488. blk_mq_run_hw_queues(sdev->request_queue, true);
  489. }
  490. }
  491. /* Returns false when no more bytes to process, true if there are more */
  492. static bool scsi_end_request(struct request *req, blk_status_t error,
  493. unsigned int bytes)
  494. {
  495. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
  496. struct scsi_device *sdev = cmd->device;
  497. struct request_queue *q = sdev->request_queue;
  498. if (blk_update_request(req, error, bytes))
  499. return true;
  500. if (blk_queue_add_random(q))
  501. add_disk_randomness(req->rq_disk);
  502. if (!blk_rq_is_scsi(req)) {
  503. WARN_ON_ONCE(!(cmd->flags & SCMD_INITIALIZED));
  504. cmd->flags &= ~SCMD_INITIALIZED;
  505. }
  506. /*
  507. * Calling rcu_barrier() is not necessary here because the
  508. * SCSI error handler guarantees that the function called by
  509. * call_rcu() has been called before scsi_end_request() is
  510. * called.
  511. */
  512. destroy_rcu_head(&cmd->rcu);
  513. /*
  514. * In the MQ case the command gets freed by __blk_mq_end_request,
  515. * so we have to do all cleanup that depends on it earlier.
  516. *
  517. * We also can't kick the queues from irq context, so we
  518. * will have to defer it to a workqueue.
  519. */
  520. scsi_mq_uninit_cmd(cmd);
  521. /*
  522. * queue is still alive, so grab the ref for preventing it
  523. * from being cleaned up during running queue.
  524. */
  525. percpu_ref_get(&q->q_usage_counter);
  526. __blk_mq_end_request(req, error);
  527. scsi_run_queue_async(sdev);
  528. percpu_ref_put(&q->q_usage_counter);
  529. return false;
  530. }
  531. /**
  532. * scsi_result_to_blk_status - translate a SCSI result code into blk_status_t
  533. * @cmd: SCSI command
  534. * @result: scsi error code
  535. *
  536. * Translate a SCSI result code into a blk_status_t value. May reset the host
  537. * byte of @cmd->result.
  538. */
  539. static blk_status_t scsi_result_to_blk_status(struct scsi_cmnd *cmd, int result)
  540. {
  541. switch (host_byte(result)) {
  542. case DID_OK:
  543. /*
  544. * Also check the other bytes than the status byte in result
  545. * to handle the case when a SCSI LLD sets result to
  546. * DRIVER_SENSE << 24 without setting SAM_STAT_CHECK_CONDITION.
  547. */
  548. if (scsi_status_is_good(result) && (result & ~0xff) == 0)
  549. return BLK_STS_OK;
  550. return BLK_STS_IOERR;
  551. case DID_TRANSPORT_FAILFAST:
  552. return BLK_STS_TRANSPORT;
  553. case DID_TARGET_FAILURE:
  554. set_host_byte(cmd, DID_OK);
  555. return BLK_STS_TARGET;
  556. case DID_NEXUS_FAILURE:
  557. set_host_byte(cmd, DID_OK);
  558. return BLK_STS_NEXUS;
  559. case DID_ALLOC_FAILURE:
  560. set_host_byte(cmd, DID_OK);
  561. return BLK_STS_NOSPC;
  562. case DID_MEDIUM_ERROR:
  563. set_host_byte(cmd, DID_OK);
  564. return BLK_STS_MEDIUM;
  565. default:
  566. return BLK_STS_IOERR;
  567. }
  568. }
  569. /* Helper for scsi_io_completion() when "reprep" action required. */
  570. static void scsi_io_completion_reprep(struct scsi_cmnd *cmd,
  571. struct request_queue *q)
  572. {
  573. /* A new command will be prepared and issued. */
  574. scsi_mq_requeue_cmd(cmd);
  575. }
  576. static bool scsi_cmd_runtime_exceeced(struct scsi_cmnd *cmd)
  577. {
  578. struct request *req = cmd->request;
  579. unsigned long wait_for;
  580. if (cmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT)
  581. return false;
  582. wait_for = (cmd->allowed + 1) * req->timeout;
  583. if (time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
  584. scmd_printk(KERN_ERR, cmd, "timing out command, waited %lus\n",
  585. wait_for/HZ);
  586. return true;
  587. }
  588. return false;
  589. }
  590. /* Helper for scsi_io_completion() when special action required. */
  591. static void scsi_io_completion_action(struct scsi_cmnd *cmd, int result)
  592. {
  593. struct request_queue *q = cmd->device->request_queue;
  594. struct request *req = cmd->request;
  595. int level = 0;
  596. enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
  597. ACTION_DELAYED_RETRY} action;
  598. struct scsi_sense_hdr sshdr;
  599. bool sense_valid;
  600. bool sense_current = true; /* false implies "deferred sense" */
  601. blk_status_t blk_stat;
  602. sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
  603. if (sense_valid)
  604. sense_current = !scsi_sense_is_deferred(&sshdr);
  605. blk_stat = scsi_result_to_blk_status(cmd, result);
  606. if (host_byte(result) == DID_RESET) {
  607. /* Third party bus reset or reset for error recovery
  608. * reasons. Just retry the command and see what
  609. * happens.
  610. */
  611. action = ACTION_RETRY;
  612. } else if (sense_valid && sense_current) {
  613. switch (sshdr.sense_key) {
  614. case UNIT_ATTENTION:
  615. if (cmd->device->removable) {
  616. /* Detected disc change. Set a bit
  617. * and quietly refuse further access.
  618. */
  619. cmd->device->changed = 1;
  620. action = ACTION_FAIL;
  621. } else {
  622. /* Must have been a power glitch, or a
  623. * bus reset. Could not have been a
  624. * media change, so we just retry the
  625. * command and see what happens.
  626. */
  627. action = ACTION_RETRY;
  628. }
  629. break;
  630. case ILLEGAL_REQUEST:
  631. /* If we had an ILLEGAL REQUEST returned, then
  632. * we may have performed an unsupported
  633. * command. The only thing this should be
  634. * would be a ten byte read where only a six
  635. * byte read was supported. Also, on a system
  636. * where READ CAPACITY failed, we may have
  637. * read past the end of the disk.
  638. */
  639. if ((cmd->device->use_10_for_rw &&
  640. sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
  641. (cmd->cmnd[0] == READ_10 ||
  642. cmd->cmnd[0] == WRITE_10)) {
  643. /* This will issue a new 6-byte command. */
  644. cmd->device->use_10_for_rw = 0;
  645. action = ACTION_REPREP;
  646. } else if (sshdr.asc == 0x10) /* DIX */ {
  647. action = ACTION_FAIL;
  648. blk_stat = BLK_STS_PROTECTION;
  649. /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
  650. } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
  651. action = ACTION_FAIL;
  652. blk_stat = BLK_STS_TARGET;
  653. } else
  654. action = ACTION_FAIL;
  655. break;
  656. case ABORTED_COMMAND:
  657. action = ACTION_FAIL;
  658. if (sshdr.asc == 0x10) /* DIF */
  659. blk_stat = BLK_STS_PROTECTION;
  660. break;
  661. case NOT_READY:
  662. /* If the device is in the process of becoming
  663. * ready, or has a temporary blockage, retry.
  664. */
  665. if (sshdr.asc == 0x04) {
  666. switch (sshdr.ascq) {
  667. case 0x01: /* becoming ready */
  668. case 0x04: /* format in progress */
  669. case 0x05: /* rebuild in progress */
  670. case 0x06: /* recalculation in progress */
  671. case 0x07: /* operation in progress */
  672. case 0x08: /* Long write in progress */
  673. case 0x09: /* self test in progress */
  674. case 0x11: /* notify (enable spinup) required */
  675. case 0x14: /* space allocation in progress */
  676. case 0x1a: /* start stop unit in progress */
  677. case 0x1b: /* sanitize in progress */
  678. case 0x1d: /* configuration in progress */
  679. case 0x24: /* depopulation in progress */
  680. action = ACTION_DELAYED_RETRY;
  681. break;
  682. default:
  683. action = ACTION_FAIL;
  684. break;
  685. }
  686. } else
  687. action = ACTION_FAIL;
  688. break;
  689. case VOLUME_OVERFLOW:
  690. /* See SSC3rXX or current. */
  691. action = ACTION_FAIL;
  692. break;
  693. case DATA_PROTECT:
  694. action = ACTION_FAIL;
  695. if ((sshdr.asc == 0x0C && sshdr.ascq == 0x12) ||
  696. (sshdr.asc == 0x55 &&
  697. (sshdr.ascq == 0x0E || sshdr.ascq == 0x0F))) {
  698. /* Insufficient zone resources */
  699. blk_stat = BLK_STS_ZONE_OPEN_RESOURCE;
  700. }
  701. break;
  702. default:
  703. action = ACTION_FAIL;
  704. break;
  705. }
  706. } else
  707. action = ACTION_FAIL;
  708. if (action != ACTION_FAIL && scsi_cmd_runtime_exceeced(cmd))
  709. action = ACTION_FAIL;
  710. switch (action) {
  711. case ACTION_FAIL:
  712. /* Give up and fail the remainder of the request */
  713. if (!(req->rq_flags & RQF_QUIET)) {
  714. static DEFINE_RATELIMIT_STATE(_rs,
  715. DEFAULT_RATELIMIT_INTERVAL,
  716. DEFAULT_RATELIMIT_BURST);
  717. if (unlikely(scsi_logging_level))
  718. level =
  719. SCSI_LOG_LEVEL(SCSI_LOG_MLCOMPLETE_SHIFT,
  720. SCSI_LOG_MLCOMPLETE_BITS);
  721. /*
  722. * if logging is enabled the failure will be printed
  723. * in scsi_log_completion(), so avoid duplicate messages
  724. */
  725. if (!level && __ratelimit(&_rs)) {
  726. scsi_print_result(cmd, NULL, FAILED);
  727. if (driver_byte(result) == DRIVER_SENSE)
  728. scsi_print_sense(cmd);
  729. scsi_print_command(cmd);
  730. }
  731. }
  732. if (!scsi_end_request(req, blk_stat, blk_rq_err_bytes(req)))
  733. return;
  734. fallthrough;
  735. case ACTION_REPREP:
  736. scsi_io_completion_reprep(cmd, q);
  737. break;
  738. case ACTION_RETRY:
  739. /* Retry the same command immediately */
  740. __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, false);
  741. break;
  742. case ACTION_DELAYED_RETRY:
  743. /* Retry the same command after a delay */
  744. __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, false);
  745. break;
  746. }
  747. }
  748. /*
  749. * Helper for scsi_io_completion() when cmd->result is non-zero. Returns a
  750. * new result that may suppress further error checking. Also modifies
  751. * *blk_statp in some cases.
  752. */
  753. static int scsi_io_completion_nz_result(struct scsi_cmnd *cmd, int result,
  754. blk_status_t *blk_statp)
  755. {
  756. bool sense_valid;
  757. bool sense_current = true; /* false implies "deferred sense" */
  758. struct request *req = cmd->request;
  759. struct scsi_sense_hdr sshdr;
  760. sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
  761. if (sense_valid)
  762. sense_current = !scsi_sense_is_deferred(&sshdr);
  763. if (blk_rq_is_passthrough(req)) {
  764. if (sense_valid) {
  765. /*
  766. * SG_IO wants current and deferred errors
  767. */
  768. scsi_req(req)->sense_len =
  769. min(8 + cmd->sense_buffer[7],
  770. SCSI_SENSE_BUFFERSIZE);
  771. }
  772. if (sense_current)
  773. *blk_statp = scsi_result_to_blk_status(cmd, result);
  774. } else if (blk_rq_bytes(req) == 0 && sense_current) {
  775. /*
  776. * Flush commands do not transfers any data, and thus cannot use
  777. * good_bytes != blk_rq_bytes(req) as the signal for an error.
  778. * This sets *blk_statp explicitly for the problem case.
  779. */
  780. *blk_statp = scsi_result_to_blk_status(cmd, result);
  781. }
  782. /*
  783. * Recovered errors need reporting, but they're always treated as
  784. * success, so fiddle the result code here. For passthrough requests
  785. * we already took a copy of the original into sreq->result which
  786. * is what gets returned to the user
  787. */
  788. if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
  789. bool do_print = true;
  790. /*
  791. * if ATA PASS-THROUGH INFORMATION AVAILABLE [0x0, 0x1d]
  792. * skip print since caller wants ATA registers. Only occurs
  793. * on SCSI ATA PASS_THROUGH commands when CK_COND=1
  794. */
  795. if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
  796. do_print = false;
  797. else if (req->rq_flags & RQF_QUIET)
  798. do_print = false;
  799. if (do_print)
  800. scsi_print_sense(cmd);
  801. result = 0;
  802. /* for passthrough, *blk_statp may be set */
  803. *blk_statp = BLK_STS_OK;
  804. }
  805. /*
  806. * Another corner case: the SCSI status byte is non-zero but 'good'.
  807. * Example: PRE-FETCH command returns SAM_STAT_CONDITION_MET when
  808. * it is able to fit nominated LBs in its cache (and SAM_STAT_GOOD
  809. * if it can't fit). Treat SAM_STAT_CONDITION_MET and the related
  810. * intermediate statuses (both obsolete in SAM-4) as good.
  811. */
  812. if (status_byte(result) && scsi_status_is_good(result)) {
  813. result = 0;
  814. *blk_statp = BLK_STS_OK;
  815. }
  816. return result;
  817. }
  818. /**
  819. * scsi_io_completion - Completion processing for SCSI commands.
  820. * @cmd: command that is finished.
  821. * @good_bytes: number of processed bytes.
  822. *
  823. * We will finish off the specified number of sectors. If we are done, the
  824. * command block will be released and the queue function will be goosed. If we
  825. * are not done then we have to figure out what to do next:
  826. *
  827. * a) We can call scsi_io_completion_reprep(). The request will be
  828. * unprepared and put back on the queue. Then a new command will
  829. * be created for it. This should be used if we made forward
  830. * progress, or if we want to switch from READ(10) to READ(6) for
  831. * example.
  832. *
  833. * b) We can call scsi_io_completion_action(). The request will be
  834. * put back on the queue and retried using the same command as
  835. * before, possibly after a delay.
  836. *
  837. * c) We can call scsi_end_request() with blk_stat other than
  838. * BLK_STS_OK, to fail the remainder of the request.
  839. */
  840. void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
  841. {
  842. int result = cmd->result;
  843. struct request_queue *q = cmd->device->request_queue;
  844. struct request *req = cmd->request;
  845. blk_status_t blk_stat = BLK_STS_OK;
  846. if (unlikely(result)) /* a nz result may or may not be an error */
  847. result = scsi_io_completion_nz_result(cmd, result, &blk_stat);
  848. if (unlikely(blk_rq_is_passthrough(req))) {
  849. /*
  850. * scsi_result_to_blk_status may have reset the host_byte
  851. */
  852. scsi_req(req)->result = cmd->result;
  853. }
  854. /*
  855. * Next deal with any sectors which we were able to correctly
  856. * handle.
  857. */
  858. SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, cmd,
  859. "%u sectors total, %d bytes done.\n",
  860. blk_rq_sectors(req), good_bytes));
  861. /*
  862. * Failed, zero length commands always need to drop down
  863. * to retry code. Fast path should return in this block.
  864. */
  865. if (likely(blk_rq_bytes(req) > 0 || blk_stat == BLK_STS_OK)) {
  866. if (likely(!scsi_end_request(req, blk_stat, good_bytes)))
  867. return; /* no bytes remaining */
  868. }
  869. /* Kill remainder if no retries. */
  870. if (unlikely(blk_stat && scsi_noretry_cmd(cmd))) {
  871. if (scsi_end_request(req, blk_stat, blk_rq_bytes(req)))
  872. WARN_ONCE(true,
  873. "Bytes remaining after failed, no-retry command");
  874. return;
  875. }
  876. /*
  877. * If there had been no error, but we have leftover bytes in the
  878. * requeues just queue the command up again.
  879. */
  880. if (likely(result == 0))
  881. scsi_io_completion_reprep(cmd, q);
  882. else
  883. scsi_io_completion_action(cmd, result);
  884. }
  885. static inline bool scsi_cmd_needs_dma_drain(struct scsi_device *sdev,
  886. struct request *rq)
  887. {
  888. return sdev->dma_drain_len && blk_rq_is_passthrough(rq) &&
  889. !op_is_write(req_op(rq)) &&
  890. sdev->host->hostt->dma_need_drain(rq);
  891. }
  892. /**
  893. * scsi_alloc_sgtables - allocate S/G tables for a command
  894. * @cmd: command descriptor we wish to initialize
  895. *
  896. * Returns:
  897. * * BLK_STS_OK - on success
  898. * * BLK_STS_RESOURCE - if the failure is retryable
  899. * * BLK_STS_IOERR - if the failure is fatal
  900. */
  901. blk_status_t scsi_alloc_sgtables(struct scsi_cmnd *cmd)
  902. {
  903. struct scsi_device *sdev = cmd->device;
  904. struct request *rq = cmd->request;
  905. unsigned short nr_segs = blk_rq_nr_phys_segments(rq);
  906. struct scatterlist *last_sg = NULL;
  907. blk_status_t ret;
  908. bool need_drain = scsi_cmd_needs_dma_drain(sdev, rq);
  909. int count;
  910. if (WARN_ON_ONCE(!nr_segs))
  911. return BLK_STS_IOERR;
  912. /*
  913. * Make sure there is space for the drain. The driver must adjust
  914. * max_hw_segments to be prepared for this.
  915. */
  916. if (need_drain)
  917. nr_segs++;
  918. /*
  919. * If sg table allocation fails, requeue request later.
  920. */
  921. if (unlikely(sg_alloc_table_chained(&cmd->sdb.table, nr_segs,
  922. cmd->sdb.table.sgl, SCSI_INLINE_SG_CNT)))
  923. return BLK_STS_RESOURCE;
  924. /*
  925. * Next, walk the list, and fill in the addresses and sizes of
  926. * each segment.
  927. */
  928. count = __blk_rq_map_sg(rq->q, rq, cmd->sdb.table.sgl, &last_sg);
  929. if (blk_rq_bytes(rq) & rq->q->dma_pad_mask) {
  930. unsigned int pad_len =
  931. (rq->q->dma_pad_mask & ~blk_rq_bytes(rq)) + 1;
  932. last_sg->length += pad_len;
  933. cmd->extra_len += pad_len;
  934. }
  935. if (need_drain) {
  936. sg_unmark_end(last_sg);
  937. last_sg = sg_next(last_sg);
  938. sg_set_buf(last_sg, sdev->dma_drain_buf, sdev->dma_drain_len);
  939. sg_mark_end(last_sg);
  940. cmd->extra_len += sdev->dma_drain_len;
  941. count++;
  942. }
  943. BUG_ON(count > cmd->sdb.table.nents);
  944. cmd->sdb.table.nents = count;
  945. cmd->sdb.length = blk_rq_payload_bytes(rq);
  946. if (blk_integrity_rq(rq)) {
  947. struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
  948. int ivecs;
  949. if (WARN_ON_ONCE(!prot_sdb)) {
  950. /*
  951. * This can happen if someone (e.g. multipath)
  952. * queues a command to a device on an adapter
  953. * that does not support DIX.
  954. */
  955. ret = BLK_STS_IOERR;
  956. goto out_free_sgtables;
  957. }
  958. ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
  959. if (sg_alloc_table_chained(&prot_sdb->table, ivecs,
  960. prot_sdb->table.sgl,
  961. SCSI_INLINE_PROT_SG_CNT)) {
  962. ret = BLK_STS_RESOURCE;
  963. goto out_free_sgtables;
  964. }
  965. count = blk_rq_map_integrity_sg(rq->q, rq->bio,
  966. prot_sdb->table.sgl);
  967. BUG_ON(count > ivecs);
  968. BUG_ON(count > queue_max_integrity_segments(rq->q));
  969. cmd->prot_sdb = prot_sdb;
  970. cmd->prot_sdb->table.nents = count;
  971. }
  972. return BLK_STS_OK;
  973. out_free_sgtables:
  974. scsi_free_sgtables(cmd);
  975. return ret;
  976. }
  977. EXPORT_SYMBOL(scsi_alloc_sgtables);
  978. /**
  979. * scsi_initialize_rq - initialize struct scsi_cmnd partially
  980. * @rq: Request associated with the SCSI command to be initialized.
  981. *
  982. * This function initializes the members of struct scsi_cmnd that must be
  983. * initialized before request processing starts and that won't be
  984. * reinitialized if a SCSI command is requeued.
  985. *
  986. * Called from inside blk_get_request() for pass-through requests and from
  987. * inside scsi_init_command() for filesystem requests.
  988. */
  989. static void scsi_initialize_rq(struct request *rq)
  990. {
  991. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
  992. scsi_req_init(&cmd->req);
  993. init_rcu_head(&cmd->rcu);
  994. cmd->jiffies_at_alloc = jiffies;
  995. cmd->retries = 0;
  996. }
  997. /*
  998. * Only called when the request isn't completed by SCSI, and not freed by
  999. * SCSI
  1000. */
  1001. static void scsi_cleanup_rq(struct request *rq)
  1002. {
  1003. if (rq->rq_flags & RQF_DONTPREP) {
  1004. scsi_mq_uninit_cmd(blk_mq_rq_to_pdu(rq));
  1005. rq->rq_flags &= ~RQF_DONTPREP;
  1006. }
  1007. }
  1008. /* Called before a request is prepared. See also scsi_mq_prep_fn(). */
  1009. void scsi_init_command(struct scsi_device *dev, struct scsi_cmnd *cmd)
  1010. {
  1011. void *buf = cmd->sense_buffer;
  1012. void *prot = cmd->prot_sdb;
  1013. struct request *rq = blk_mq_rq_from_pdu(cmd);
  1014. unsigned int flags = cmd->flags & SCMD_PRESERVED_FLAGS;
  1015. unsigned long jiffies_at_alloc;
  1016. int retries, to_clear;
  1017. bool in_flight;
  1018. if (!blk_rq_is_scsi(rq) && !(flags & SCMD_INITIALIZED)) {
  1019. flags |= SCMD_INITIALIZED;
  1020. scsi_initialize_rq(rq);
  1021. }
  1022. jiffies_at_alloc = cmd->jiffies_at_alloc;
  1023. retries = cmd->retries;
  1024. in_flight = test_bit(SCMD_STATE_INFLIGHT, &cmd->state);
  1025. /*
  1026. * Zero out the cmd, except for the embedded scsi_request. Only clear
  1027. * the driver-private command data if the LLD does not supply a
  1028. * function to initialize that data.
  1029. */
  1030. to_clear = sizeof(*cmd) - sizeof(cmd->req);
  1031. if (!dev->host->hostt->init_cmd_priv)
  1032. to_clear += dev->host->hostt->cmd_size;
  1033. memset((char *)cmd + sizeof(cmd->req), 0, to_clear);
  1034. cmd->device = dev;
  1035. cmd->sense_buffer = buf;
  1036. cmd->prot_sdb = prot;
  1037. cmd->flags = flags;
  1038. INIT_DELAYED_WORK(&cmd->abort_work, scmd_eh_abort_handler);
  1039. cmd->jiffies_at_alloc = jiffies_at_alloc;
  1040. cmd->retries = retries;
  1041. if (in_flight)
  1042. __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
  1043. }
  1044. static blk_status_t scsi_setup_scsi_cmnd(struct scsi_device *sdev,
  1045. struct request *req)
  1046. {
  1047. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
  1048. /*
  1049. * Passthrough requests may transfer data, in which case they must
  1050. * a bio attached to them. Or they might contain a SCSI command
  1051. * that does not transfer data, in which case they may optionally
  1052. * submit a request without an attached bio.
  1053. */
  1054. if (req->bio) {
  1055. blk_status_t ret = scsi_alloc_sgtables(cmd);
  1056. if (unlikely(ret != BLK_STS_OK))
  1057. return ret;
  1058. } else {
  1059. BUG_ON(blk_rq_bytes(req));
  1060. memset(&cmd->sdb, 0, sizeof(cmd->sdb));
  1061. }
  1062. cmd->cmd_len = scsi_req(req)->cmd_len;
  1063. cmd->cmnd = scsi_req(req)->cmd;
  1064. cmd->transfersize = blk_rq_bytes(req);
  1065. cmd->allowed = scsi_req(req)->retries;
  1066. return BLK_STS_OK;
  1067. }
  1068. static blk_status_t
  1069. scsi_device_state_check(struct scsi_device *sdev, struct request *req)
  1070. {
  1071. switch (sdev->sdev_state) {
  1072. case SDEV_CREATED:
  1073. return BLK_STS_OK;
  1074. case SDEV_OFFLINE:
  1075. case SDEV_TRANSPORT_OFFLINE:
  1076. /*
  1077. * If the device is offline we refuse to process any
  1078. * commands. The device must be brought online
  1079. * before trying any recovery commands.
  1080. */
  1081. if (!sdev->offline_already) {
  1082. sdev->offline_already = true;
  1083. sdev_printk(KERN_ERR, sdev,
  1084. "rejecting I/O to offline device\n");
  1085. }
  1086. return BLK_STS_IOERR;
  1087. case SDEV_DEL:
  1088. /*
  1089. * If the device is fully deleted, we refuse to
  1090. * process any commands as well.
  1091. */
  1092. sdev_printk(KERN_ERR, sdev,
  1093. "rejecting I/O to dead device\n");
  1094. return BLK_STS_IOERR;
  1095. case SDEV_BLOCK:
  1096. case SDEV_CREATED_BLOCK:
  1097. return BLK_STS_RESOURCE;
  1098. case SDEV_QUIESCE:
  1099. /*
  1100. * If the device is blocked we only accept power management
  1101. * commands.
  1102. */
  1103. if (req && WARN_ON_ONCE(!(req->rq_flags & RQF_PM)))
  1104. return BLK_STS_RESOURCE;
  1105. return BLK_STS_OK;
  1106. default:
  1107. /*
  1108. * For any other not fully online state we only allow
  1109. * power management commands.
  1110. */
  1111. if (req && !(req->rq_flags & RQF_PM))
  1112. return BLK_STS_IOERR;
  1113. return BLK_STS_OK;
  1114. }
  1115. }
  1116. /*
  1117. * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
  1118. * return 0.
  1119. *
  1120. * Called with the queue_lock held.
  1121. */
  1122. static inline int scsi_dev_queue_ready(struct request_queue *q,
  1123. struct scsi_device *sdev)
  1124. {
  1125. unsigned int busy;
  1126. busy = atomic_inc_return(&sdev->device_busy) - 1;
  1127. if (atomic_read(&sdev->device_blocked)) {
  1128. if (busy)
  1129. goto out_dec;
  1130. /*
  1131. * unblock after device_blocked iterates to zero
  1132. */
  1133. if (atomic_dec_return(&sdev->device_blocked) > 0)
  1134. goto out_dec;
  1135. SCSI_LOG_MLQUEUE(3, sdev_printk(KERN_INFO, sdev,
  1136. "unblocking device at zero depth\n"));
  1137. }
  1138. if (busy >= sdev->queue_depth)
  1139. goto out_dec;
  1140. return 1;
  1141. out_dec:
  1142. atomic_dec(&sdev->device_busy);
  1143. return 0;
  1144. }
  1145. /*
  1146. * scsi_target_queue_ready: checks if there we can send commands to target
  1147. * @sdev: scsi device on starget to check.
  1148. */
  1149. static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
  1150. struct scsi_device *sdev)
  1151. {
  1152. struct scsi_target *starget = scsi_target(sdev);
  1153. unsigned int busy;
  1154. if (starget->single_lun) {
  1155. spin_lock_irq(shost->host_lock);
  1156. if (starget->starget_sdev_user &&
  1157. starget->starget_sdev_user != sdev) {
  1158. spin_unlock_irq(shost->host_lock);
  1159. return 0;
  1160. }
  1161. starget->starget_sdev_user = sdev;
  1162. spin_unlock_irq(shost->host_lock);
  1163. }
  1164. if (starget->can_queue <= 0)
  1165. return 1;
  1166. busy = atomic_inc_return(&starget->target_busy) - 1;
  1167. if (atomic_read(&starget->target_blocked) > 0) {
  1168. if (busy)
  1169. goto starved;
  1170. /*
  1171. * unblock after target_blocked iterates to zero
  1172. */
  1173. if (atomic_dec_return(&starget->target_blocked) > 0)
  1174. goto out_dec;
  1175. SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
  1176. "unblocking target at zero depth\n"));
  1177. }
  1178. if (busy >= starget->can_queue)
  1179. goto starved;
  1180. return 1;
  1181. starved:
  1182. spin_lock_irq(shost->host_lock);
  1183. list_move_tail(&sdev->starved_entry, &shost->starved_list);
  1184. spin_unlock_irq(shost->host_lock);
  1185. out_dec:
  1186. if (starget->can_queue > 0)
  1187. atomic_dec(&starget->target_busy);
  1188. return 0;
  1189. }
  1190. /*
  1191. * scsi_host_queue_ready: if we can send requests to shost, return 1 else
  1192. * return 0. We must end up running the queue again whenever 0 is
  1193. * returned, else IO can hang.
  1194. */
  1195. static inline int scsi_host_queue_ready(struct request_queue *q,
  1196. struct Scsi_Host *shost,
  1197. struct scsi_device *sdev,
  1198. struct scsi_cmnd *cmd)
  1199. {
  1200. if (scsi_host_in_recovery(shost))
  1201. return 0;
  1202. if (atomic_read(&shost->host_blocked) > 0) {
  1203. if (scsi_host_busy(shost) > 0)
  1204. goto starved;
  1205. /*
  1206. * unblock after host_blocked iterates to zero
  1207. */
  1208. if (atomic_dec_return(&shost->host_blocked) > 0)
  1209. goto out_dec;
  1210. SCSI_LOG_MLQUEUE(3,
  1211. shost_printk(KERN_INFO, shost,
  1212. "unblocking host at zero depth\n"));
  1213. }
  1214. if (shost->host_self_blocked)
  1215. goto starved;
  1216. /* We're OK to process the command, so we can't be starved */
  1217. if (!list_empty(&sdev->starved_entry)) {
  1218. spin_lock_irq(shost->host_lock);
  1219. if (!list_empty(&sdev->starved_entry))
  1220. list_del_init(&sdev->starved_entry);
  1221. spin_unlock_irq(shost->host_lock);
  1222. }
  1223. __set_bit(SCMD_STATE_INFLIGHT, &cmd->state);
  1224. return 1;
  1225. starved:
  1226. spin_lock_irq(shost->host_lock);
  1227. if (list_empty(&sdev->starved_entry))
  1228. list_add_tail(&sdev->starved_entry, &shost->starved_list);
  1229. spin_unlock_irq(shost->host_lock);
  1230. out_dec:
  1231. scsi_dec_host_busy(shost, cmd);
  1232. return 0;
  1233. }
  1234. /*
  1235. * Busy state exporting function for request stacking drivers.
  1236. *
  1237. * For efficiency, no lock is taken to check the busy state of
  1238. * shost/starget/sdev, since the returned value is not guaranteed and
  1239. * may be changed after request stacking drivers call the function,
  1240. * regardless of taking lock or not.
  1241. *
  1242. * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
  1243. * needs to return 'not busy'. Otherwise, request stacking drivers
  1244. * may hold requests forever.
  1245. */
  1246. static bool scsi_mq_lld_busy(struct request_queue *q)
  1247. {
  1248. struct scsi_device *sdev = q->queuedata;
  1249. struct Scsi_Host *shost;
  1250. if (blk_queue_dying(q))
  1251. return false;
  1252. shost = sdev->host;
  1253. /*
  1254. * Ignore host/starget busy state.
  1255. * Since block layer does not have a concept of fairness across
  1256. * multiple queues, congestion of host/starget needs to be handled
  1257. * in SCSI layer.
  1258. */
  1259. if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
  1260. return true;
  1261. return false;
  1262. }
  1263. static void scsi_softirq_done(struct request *rq)
  1264. {
  1265. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
  1266. int disposition;
  1267. INIT_LIST_HEAD(&cmd->eh_entry);
  1268. atomic_inc(&cmd->device->iodone_cnt);
  1269. if (cmd->result)
  1270. atomic_inc(&cmd->device->ioerr_cnt);
  1271. disposition = scsi_decide_disposition(cmd);
  1272. if (disposition != SUCCESS && scsi_cmd_runtime_exceeced(cmd))
  1273. disposition = SUCCESS;
  1274. scsi_log_completion(cmd, disposition);
  1275. switch (disposition) {
  1276. case SUCCESS:
  1277. scsi_finish_command(cmd);
  1278. break;
  1279. case NEEDS_RETRY:
  1280. scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
  1281. break;
  1282. case ADD_TO_MLQUEUE:
  1283. scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
  1284. break;
  1285. default:
  1286. scsi_eh_scmd_add(cmd);
  1287. break;
  1288. }
  1289. }
  1290. /**
  1291. * scsi_dispatch_command - Dispatch a command to the low-level driver.
  1292. * @cmd: command block we are dispatching.
  1293. *
  1294. * Return: nonzero return request was rejected and device's queue needs to be
  1295. * plugged.
  1296. */
  1297. static int scsi_dispatch_cmd(struct scsi_cmnd *cmd)
  1298. {
  1299. struct Scsi_Host *host = cmd->device->host;
  1300. int rtn = 0;
  1301. atomic_inc(&cmd->device->iorequest_cnt);
  1302. /* check if the device is still usable */
  1303. if (unlikely(cmd->device->sdev_state == SDEV_DEL)) {
  1304. /* in SDEV_DEL we error all commands. DID_NO_CONNECT
  1305. * returns an immediate error upwards, and signals
  1306. * that the device is no longer present */
  1307. cmd->result = DID_NO_CONNECT << 16;
  1308. goto done;
  1309. }
  1310. /* Check to see if the scsi lld made this device blocked. */
  1311. if (unlikely(scsi_device_blocked(cmd->device))) {
  1312. /*
  1313. * in blocked state, the command is just put back on
  1314. * the device queue. The suspend state has already
  1315. * blocked the queue so future requests should not
  1316. * occur until the device transitions out of the
  1317. * suspend state.
  1318. */
  1319. SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
  1320. "queuecommand : device blocked\n"));
  1321. return SCSI_MLQUEUE_DEVICE_BUSY;
  1322. }
  1323. /* Store the LUN value in cmnd, if needed. */
  1324. if (cmd->device->lun_in_cdb)
  1325. cmd->cmnd[1] = (cmd->cmnd[1] & 0x1f) |
  1326. (cmd->device->lun << 5 & 0xe0);
  1327. scsi_log_send(cmd);
  1328. /*
  1329. * Before we queue this command, check if the command
  1330. * length exceeds what the host adapter can handle.
  1331. */
  1332. if (cmd->cmd_len > cmd->device->host->max_cmd_len) {
  1333. SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
  1334. "queuecommand : command too long. "
  1335. "cdb_size=%d host->max_cmd_len=%d\n",
  1336. cmd->cmd_len, cmd->device->host->max_cmd_len));
  1337. cmd->result = (DID_ABORT << 16);
  1338. goto done;
  1339. }
  1340. if (unlikely(host->shost_state == SHOST_DEL)) {
  1341. cmd->result = (DID_NO_CONNECT << 16);
  1342. goto done;
  1343. }
  1344. trace_scsi_dispatch_cmd_start(cmd);
  1345. rtn = host->hostt->queuecommand(host, cmd);
  1346. if (rtn) {
  1347. trace_scsi_dispatch_cmd_error(cmd, rtn);
  1348. if (rtn != SCSI_MLQUEUE_DEVICE_BUSY &&
  1349. rtn != SCSI_MLQUEUE_TARGET_BUSY)
  1350. rtn = SCSI_MLQUEUE_HOST_BUSY;
  1351. SCSI_LOG_MLQUEUE(3, scmd_printk(KERN_INFO, cmd,
  1352. "queuecommand : request rejected\n"));
  1353. }
  1354. return rtn;
  1355. done:
  1356. cmd->scsi_done(cmd);
  1357. return 0;
  1358. }
  1359. /* Size in bytes of the sg-list stored in the scsi-mq command-private data. */
  1360. static unsigned int scsi_mq_inline_sgl_size(struct Scsi_Host *shost)
  1361. {
  1362. return min_t(unsigned int, shost->sg_tablesize, SCSI_INLINE_SG_CNT) *
  1363. sizeof(struct scatterlist);
  1364. }
  1365. static blk_status_t scsi_prepare_cmd(struct request *req)
  1366. {
  1367. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
  1368. struct scsi_device *sdev = req->q->queuedata;
  1369. struct Scsi_Host *shost = sdev->host;
  1370. struct scatterlist *sg;
  1371. scsi_init_command(sdev, cmd);
  1372. cmd->request = req;
  1373. cmd->tag = req->tag;
  1374. cmd->prot_op = SCSI_PROT_NORMAL;
  1375. if (blk_rq_bytes(req))
  1376. cmd->sc_data_direction = rq_dma_dir(req);
  1377. else
  1378. cmd->sc_data_direction = DMA_NONE;
  1379. sg = (void *)cmd + sizeof(struct scsi_cmnd) + shost->hostt->cmd_size;
  1380. cmd->sdb.table.sgl = sg;
  1381. if (scsi_host_get_prot(shost)) {
  1382. memset(cmd->prot_sdb, 0, sizeof(struct scsi_data_buffer));
  1383. cmd->prot_sdb->table.sgl =
  1384. (struct scatterlist *)(cmd->prot_sdb + 1);
  1385. }
  1386. /*
  1387. * Special handling for passthrough commands, which don't go to the ULP
  1388. * at all:
  1389. */
  1390. if (blk_rq_is_scsi(req))
  1391. return scsi_setup_scsi_cmnd(sdev, req);
  1392. if (sdev->handler && sdev->handler->prep_fn) {
  1393. blk_status_t ret = sdev->handler->prep_fn(sdev, req);
  1394. if (ret != BLK_STS_OK)
  1395. return ret;
  1396. }
  1397. cmd->cmnd = scsi_req(req)->cmd = scsi_req(req)->__cmd;
  1398. memset(cmd->cmnd, 0, BLK_MAX_CDB);
  1399. return scsi_cmd_to_driver(cmd)->init_command(cmd);
  1400. }
  1401. static void scsi_mq_done(struct scsi_cmnd *cmd)
  1402. {
  1403. if (unlikely(blk_should_fake_timeout(cmd->request->q)))
  1404. return;
  1405. if (unlikely(test_and_set_bit(SCMD_STATE_COMPLETE, &cmd->state)))
  1406. return;
  1407. trace_scsi_dispatch_cmd_done(cmd);
  1408. blk_mq_complete_request(cmd->request);
  1409. }
  1410. static void scsi_mq_put_budget(struct request_queue *q)
  1411. {
  1412. struct scsi_device *sdev = q->queuedata;
  1413. atomic_dec(&sdev->device_busy);
  1414. }
  1415. static bool scsi_mq_get_budget(struct request_queue *q)
  1416. {
  1417. struct scsi_device *sdev = q->queuedata;
  1418. if (scsi_dev_queue_ready(q, sdev))
  1419. return true;
  1420. atomic_inc(&sdev->restarts);
  1421. /*
  1422. * Orders atomic_inc(&sdev->restarts) and atomic_read(&sdev->device_busy).
  1423. * .restarts must be incremented before .device_busy is read because the
  1424. * code in scsi_run_queue_async() depends on the order of these operations.
  1425. */
  1426. smp_mb__after_atomic();
  1427. /*
  1428. * If all in-flight requests originated from this LUN are completed
  1429. * before reading .device_busy, sdev->device_busy will be observed as
  1430. * zero, then blk_mq_delay_run_hw_queues() will dispatch this request
  1431. * soon. Otherwise, completion of one of these requests will observe
  1432. * the .restarts flag, and the request queue will be run for handling
  1433. * this request, see scsi_end_request().
  1434. */
  1435. if (unlikely(atomic_read(&sdev->device_busy) == 0 &&
  1436. !scsi_device_blocked(sdev)))
  1437. blk_mq_delay_run_hw_queues(sdev->request_queue, SCSI_QUEUE_DELAY);
  1438. return false;
  1439. }
  1440. static blk_status_t scsi_queue_rq(struct blk_mq_hw_ctx *hctx,
  1441. const struct blk_mq_queue_data *bd)
  1442. {
  1443. struct request *req = bd->rq;
  1444. struct request_queue *q = req->q;
  1445. struct scsi_device *sdev = q->queuedata;
  1446. struct Scsi_Host *shost = sdev->host;
  1447. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(req);
  1448. blk_status_t ret;
  1449. int reason;
  1450. /*
  1451. * If the device is not in running state we will reject some or all
  1452. * commands.
  1453. */
  1454. if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
  1455. ret = scsi_device_state_check(sdev, req);
  1456. if (ret != BLK_STS_OK)
  1457. goto out_put_budget;
  1458. }
  1459. ret = BLK_STS_RESOURCE;
  1460. if (!scsi_target_queue_ready(shost, sdev))
  1461. goto out_put_budget;
  1462. if (!scsi_host_queue_ready(q, shost, sdev, cmd))
  1463. goto out_dec_target_busy;
  1464. if (!(req->rq_flags & RQF_DONTPREP)) {
  1465. ret = scsi_prepare_cmd(req);
  1466. if (ret != BLK_STS_OK)
  1467. goto out_dec_host_busy;
  1468. req->rq_flags |= RQF_DONTPREP;
  1469. } else {
  1470. clear_bit(SCMD_STATE_COMPLETE, &cmd->state);
  1471. }
  1472. cmd->flags &= SCMD_PRESERVED_FLAGS;
  1473. if (sdev->simple_tags)
  1474. cmd->flags |= SCMD_TAGGED;
  1475. if (bd->last)
  1476. cmd->flags |= SCMD_LAST;
  1477. scsi_set_resid(cmd, 0);
  1478. memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
  1479. cmd->scsi_done = scsi_mq_done;
  1480. blk_mq_start_request(req);
  1481. reason = scsi_dispatch_cmd(cmd);
  1482. if (reason) {
  1483. scsi_set_blocked(cmd, reason);
  1484. ret = BLK_STS_RESOURCE;
  1485. goto out_dec_host_busy;
  1486. }
  1487. return BLK_STS_OK;
  1488. out_dec_host_busy:
  1489. scsi_dec_host_busy(shost, cmd);
  1490. out_dec_target_busy:
  1491. if (scsi_target(sdev)->can_queue > 0)
  1492. atomic_dec(&scsi_target(sdev)->target_busy);
  1493. out_put_budget:
  1494. scsi_mq_put_budget(q);
  1495. switch (ret) {
  1496. case BLK_STS_OK:
  1497. break;
  1498. case BLK_STS_RESOURCE:
  1499. case BLK_STS_ZONE_RESOURCE:
  1500. if (scsi_device_blocked(sdev))
  1501. ret = BLK_STS_DEV_RESOURCE;
  1502. break;
  1503. default:
  1504. if (unlikely(!scsi_device_online(sdev)))
  1505. scsi_req(req)->result = DID_NO_CONNECT << 16;
  1506. else
  1507. scsi_req(req)->result = DID_ERROR << 16;
  1508. /*
  1509. * Make sure to release all allocated resources when
  1510. * we hit an error, as we will never see this command
  1511. * again.
  1512. */
  1513. if (req->rq_flags & RQF_DONTPREP)
  1514. scsi_mq_uninit_cmd(cmd);
  1515. scsi_run_queue_async(sdev);
  1516. break;
  1517. }
  1518. return ret;
  1519. }
  1520. static enum blk_eh_timer_return scsi_timeout(struct request *req,
  1521. bool reserved)
  1522. {
  1523. if (reserved)
  1524. return BLK_EH_RESET_TIMER;
  1525. return scsi_times_out(req);
  1526. }
  1527. static int scsi_mq_init_request(struct blk_mq_tag_set *set, struct request *rq,
  1528. unsigned int hctx_idx, unsigned int numa_node)
  1529. {
  1530. struct Scsi_Host *shost = set->driver_data;
  1531. const bool unchecked_isa_dma = shost->unchecked_isa_dma;
  1532. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
  1533. struct scatterlist *sg;
  1534. int ret = 0;
  1535. if (unchecked_isa_dma)
  1536. cmd->flags |= SCMD_UNCHECKED_ISA_DMA;
  1537. cmd->sense_buffer = scsi_alloc_sense_buffer(unchecked_isa_dma,
  1538. GFP_KERNEL, numa_node);
  1539. if (!cmd->sense_buffer)
  1540. return -ENOMEM;
  1541. cmd->req.sense = cmd->sense_buffer;
  1542. if (scsi_host_get_prot(shost)) {
  1543. sg = (void *)cmd + sizeof(struct scsi_cmnd) +
  1544. shost->hostt->cmd_size;
  1545. cmd->prot_sdb = (void *)sg + scsi_mq_inline_sgl_size(shost);
  1546. }
  1547. if (shost->hostt->init_cmd_priv) {
  1548. ret = shost->hostt->init_cmd_priv(shost, cmd);
  1549. if (ret < 0)
  1550. scsi_free_sense_buffer(unchecked_isa_dma,
  1551. cmd->sense_buffer);
  1552. }
  1553. return ret;
  1554. }
  1555. static void scsi_mq_exit_request(struct blk_mq_tag_set *set, struct request *rq,
  1556. unsigned int hctx_idx)
  1557. {
  1558. struct Scsi_Host *shost = set->driver_data;
  1559. struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
  1560. if (shost->hostt->exit_cmd_priv)
  1561. shost->hostt->exit_cmd_priv(shost, cmd);
  1562. scsi_free_sense_buffer(cmd->flags & SCMD_UNCHECKED_ISA_DMA,
  1563. cmd->sense_buffer);
  1564. }
  1565. static int scsi_map_queues(struct blk_mq_tag_set *set)
  1566. {
  1567. struct Scsi_Host *shost = container_of(set, struct Scsi_Host, tag_set);
  1568. if (shost->hostt->map_queues)
  1569. return shost->hostt->map_queues(shost);
  1570. return blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
  1571. }
  1572. void __scsi_init_queue(struct Scsi_Host *shost, struct request_queue *q)
  1573. {
  1574. struct device *dev = shost->dma_dev;
  1575. /*
  1576. * this limit is imposed by hardware restrictions
  1577. */
  1578. blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
  1579. SG_MAX_SEGMENTS));
  1580. if (scsi_host_prot_dma(shost)) {
  1581. shost->sg_prot_tablesize =
  1582. min_not_zero(shost->sg_prot_tablesize,
  1583. (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
  1584. BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
  1585. blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
  1586. }
  1587. if (dev->dma_mask) {
  1588. shost->max_sectors = min_t(unsigned int, shost->max_sectors,
  1589. dma_max_mapping_size(dev) >> SECTOR_SHIFT);
  1590. }
  1591. blk_queue_max_hw_sectors(q, shost->max_sectors);
  1592. if (shost->unchecked_isa_dma)
  1593. blk_queue_bounce_limit(q, BLK_BOUNCE_ISA);
  1594. blk_queue_segment_boundary(q, shost->dma_boundary);
  1595. dma_set_seg_boundary(dev, shost->dma_boundary);
  1596. blk_queue_max_segment_size(q, shost->max_segment_size);
  1597. blk_queue_virt_boundary(q, shost->virt_boundary_mask);
  1598. dma_set_max_seg_size(dev, queue_max_segment_size(q));
  1599. /*
  1600. * Set a reasonable default alignment: The larger of 32-byte (dword),
  1601. * which is a common minimum for HBAs, and the minimum DMA alignment,
  1602. * which is set by the platform.
  1603. *
  1604. * Devices that require a bigger alignment can increase it later.
  1605. */
  1606. blk_queue_dma_alignment(q, max(4, dma_get_cache_alignment()) - 1);
  1607. }
  1608. EXPORT_SYMBOL_GPL(__scsi_init_queue);
  1609. static const struct blk_mq_ops scsi_mq_ops_no_commit = {
  1610. .get_budget = scsi_mq_get_budget,
  1611. .put_budget = scsi_mq_put_budget,
  1612. .queue_rq = scsi_queue_rq,
  1613. .complete = scsi_softirq_done,
  1614. .timeout = scsi_timeout,
  1615. #ifdef CONFIG_BLK_DEBUG_FS
  1616. .show_rq = scsi_show_rq,
  1617. #endif
  1618. .init_request = scsi_mq_init_request,
  1619. .exit_request = scsi_mq_exit_request,
  1620. .initialize_rq_fn = scsi_initialize_rq,
  1621. .cleanup_rq = scsi_cleanup_rq,
  1622. .busy = scsi_mq_lld_busy,
  1623. .map_queues = scsi_map_queues,
  1624. };
  1625. static void scsi_commit_rqs(struct blk_mq_hw_ctx *hctx)
  1626. {
  1627. struct request_queue *q = hctx->queue;
  1628. struct scsi_device *sdev = q->queuedata;
  1629. struct Scsi_Host *shost = sdev->host;
  1630. shost->hostt->commit_rqs(shost, hctx->queue_num);
  1631. }
  1632. static const struct blk_mq_ops scsi_mq_ops = {
  1633. .get_budget = scsi_mq_get_budget,
  1634. .put_budget = scsi_mq_put_budget,
  1635. .queue_rq = scsi_queue_rq,
  1636. .commit_rqs = scsi_commit_rqs,
  1637. .complete = scsi_softirq_done,
  1638. .timeout = scsi_timeout,
  1639. #ifdef CONFIG_BLK_DEBUG_FS
  1640. .show_rq = scsi_show_rq,
  1641. #endif
  1642. .init_request = scsi_mq_init_request,
  1643. .exit_request = scsi_mq_exit_request,
  1644. .initialize_rq_fn = scsi_initialize_rq,
  1645. .cleanup_rq = scsi_cleanup_rq,
  1646. .busy = scsi_mq_lld_busy,
  1647. .map_queues = scsi_map_queues,
  1648. };
  1649. struct request_queue *scsi_mq_alloc_queue(struct scsi_device *sdev)
  1650. {
  1651. sdev->request_queue = blk_mq_init_queue(&sdev->host->tag_set);
  1652. if (IS_ERR(sdev->request_queue))
  1653. return NULL;
  1654. sdev->request_queue->queuedata = sdev;
  1655. __scsi_init_queue(sdev->host, sdev->request_queue);
  1656. blk_queue_flag_set(QUEUE_FLAG_SCSI_PASSTHROUGH, sdev->request_queue);
  1657. return sdev->request_queue;
  1658. }
  1659. int scsi_mq_setup_tags(struct Scsi_Host *shost)
  1660. {
  1661. unsigned int cmd_size, sgl_size;
  1662. struct blk_mq_tag_set *tag_set = &shost->tag_set;
  1663. sgl_size = max_t(unsigned int, sizeof(struct scatterlist),
  1664. scsi_mq_inline_sgl_size(shost));
  1665. cmd_size = sizeof(struct scsi_cmnd) + shost->hostt->cmd_size + sgl_size;
  1666. if (scsi_host_get_prot(shost))
  1667. cmd_size += sizeof(struct scsi_data_buffer) +
  1668. sizeof(struct scatterlist) * SCSI_INLINE_PROT_SG_CNT;
  1669. memset(tag_set, 0, sizeof(*tag_set));
  1670. if (shost->hostt->commit_rqs)
  1671. tag_set->ops = &scsi_mq_ops;
  1672. else
  1673. tag_set->ops = &scsi_mq_ops_no_commit;
  1674. tag_set->nr_hw_queues = shost->nr_hw_queues ? : 1;
  1675. tag_set->queue_depth = shost->can_queue;
  1676. tag_set->cmd_size = cmd_size;
  1677. tag_set->numa_node = NUMA_NO_NODE;
  1678. tag_set->flags = BLK_MQ_F_SHOULD_MERGE;
  1679. tag_set->flags |=
  1680. BLK_ALLOC_POLICY_TO_MQ_FLAG(shost->hostt->tag_alloc_policy);
  1681. tag_set->driver_data = shost;
  1682. if (shost->host_tagset)
  1683. tag_set->flags |= BLK_MQ_F_TAG_HCTX_SHARED;
  1684. return blk_mq_alloc_tag_set(tag_set);
  1685. }
  1686. void scsi_mq_destroy_tags(struct Scsi_Host *shost)
  1687. {
  1688. blk_mq_free_tag_set(&shost->tag_set);
  1689. }
  1690. /**
  1691. * scsi_device_from_queue - return sdev associated with a request_queue
  1692. * @q: The request queue to return the sdev from
  1693. *
  1694. * Return the sdev associated with a request queue or NULL if the
  1695. * request_queue does not reference a SCSI device.
  1696. */
  1697. struct scsi_device *scsi_device_from_queue(struct request_queue *q)
  1698. {
  1699. struct scsi_device *sdev = NULL;
  1700. if (q->mq_ops == &scsi_mq_ops_no_commit ||
  1701. q->mq_ops == &scsi_mq_ops)
  1702. sdev = q->queuedata;
  1703. if (!sdev || !get_device(&sdev->sdev_gendev))
  1704. sdev = NULL;
  1705. return sdev;
  1706. }
  1707. /**
  1708. * scsi_block_requests - Utility function used by low-level drivers to prevent
  1709. * further commands from being queued to the device.
  1710. * @shost: host in question
  1711. *
  1712. * There is no timer nor any other means by which the requests get unblocked
  1713. * other than the low-level driver calling scsi_unblock_requests().
  1714. */
  1715. void scsi_block_requests(struct Scsi_Host *shost)
  1716. {
  1717. shost->host_self_blocked = 1;
  1718. }
  1719. EXPORT_SYMBOL(scsi_block_requests);
  1720. /**
  1721. * scsi_unblock_requests - Utility function used by low-level drivers to allow
  1722. * further commands to be queued to the device.
  1723. * @shost: host in question
  1724. *
  1725. * There is no timer nor any other means by which the requests get unblocked
  1726. * other than the low-level driver calling scsi_unblock_requests(). This is done
  1727. * as an API function so that changes to the internals of the scsi mid-layer
  1728. * won't require wholesale changes to drivers that use this feature.
  1729. */
  1730. void scsi_unblock_requests(struct Scsi_Host *shost)
  1731. {
  1732. shost->host_self_blocked = 0;
  1733. scsi_run_host_queues(shost);
  1734. }
  1735. EXPORT_SYMBOL(scsi_unblock_requests);
  1736. void scsi_exit_queue(void)
  1737. {
  1738. kmem_cache_destroy(scsi_sense_cache);
  1739. kmem_cache_destroy(scsi_sense_isadma_cache);
  1740. }
  1741. /**
  1742. * scsi_mode_select - issue a mode select
  1743. * @sdev: SCSI device to be queried
  1744. * @pf: Page format bit (1 == standard, 0 == vendor specific)
  1745. * @sp: Save page bit (0 == don't save, 1 == save)
  1746. * @modepage: mode page being requested
  1747. * @buffer: request buffer (may not be smaller than eight bytes)
  1748. * @len: length of request buffer.
  1749. * @timeout: command timeout
  1750. * @retries: number of retries before failing
  1751. * @data: returns a structure abstracting the mode header data
  1752. * @sshdr: place to put sense data (or NULL if no sense to be collected).
  1753. * must be SCSI_SENSE_BUFFERSIZE big.
  1754. *
  1755. * Returns zero if successful; negative error number or scsi
  1756. * status on error
  1757. *
  1758. */
  1759. int
  1760. scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
  1761. unsigned char *buffer, int len, int timeout, int retries,
  1762. struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
  1763. {
  1764. unsigned char cmd[10];
  1765. unsigned char *real_buffer;
  1766. int ret;
  1767. memset(cmd, 0, sizeof(cmd));
  1768. cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
  1769. if (sdev->use_10_for_ms) {
  1770. if (len > 65535)
  1771. return -EINVAL;
  1772. real_buffer = kmalloc(8 + len, GFP_KERNEL);
  1773. if (!real_buffer)
  1774. return -ENOMEM;
  1775. memcpy(real_buffer + 8, buffer, len);
  1776. len += 8;
  1777. real_buffer[0] = 0;
  1778. real_buffer[1] = 0;
  1779. real_buffer[2] = data->medium_type;
  1780. real_buffer[3] = data->device_specific;
  1781. real_buffer[4] = data->longlba ? 0x01 : 0;
  1782. real_buffer[5] = 0;
  1783. real_buffer[6] = data->block_descriptor_length >> 8;
  1784. real_buffer[7] = data->block_descriptor_length;
  1785. cmd[0] = MODE_SELECT_10;
  1786. cmd[7] = len >> 8;
  1787. cmd[8] = len;
  1788. } else {
  1789. if (len > 255 || data->block_descriptor_length > 255 ||
  1790. data->longlba)
  1791. return -EINVAL;
  1792. real_buffer = kmalloc(4 + len, GFP_KERNEL);
  1793. if (!real_buffer)
  1794. return -ENOMEM;
  1795. memcpy(real_buffer + 4, buffer, len);
  1796. len += 4;
  1797. real_buffer[0] = 0;
  1798. real_buffer[1] = data->medium_type;
  1799. real_buffer[2] = data->device_specific;
  1800. real_buffer[3] = data->block_descriptor_length;
  1801. cmd[0] = MODE_SELECT;
  1802. cmd[4] = len;
  1803. }
  1804. ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
  1805. sshdr, timeout, retries, NULL);
  1806. kfree(real_buffer);
  1807. return ret;
  1808. }
  1809. EXPORT_SYMBOL_GPL(scsi_mode_select);
  1810. /**
  1811. * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
  1812. * @sdev: SCSI device to be queried
  1813. * @dbd: set if mode sense will allow block descriptors to be returned
  1814. * @modepage: mode page being requested
  1815. * @buffer: request buffer (may not be smaller than eight bytes)
  1816. * @len: length of request buffer.
  1817. * @timeout: command timeout
  1818. * @retries: number of retries before failing
  1819. * @data: returns a structure abstracting the mode header data
  1820. * @sshdr: place to put sense data (or NULL if no sense to be collected).
  1821. * must be SCSI_SENSE_BUFFERSIZE big.
  1822. *
  1823. * Returns zero if successful, or a negative error number on failure
  1824. */
  1825. int
  1826. scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
  1827. unsigned char *buffer, int len, int timeout, int retries,
  1828. struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
  1829. {
  1830. unsigned char cmd[12];
  1831. int use_10_for_ms;
  1832. int header_length;
  1833. int result, retry_count = retries;
  1834. struct scsi_sense_hdr my_sshdr;
  1835. memset(data, 0, sizeof(*data));
  1836. memset(&cmd[0], 0, 12);
  1837. dbd = sdev->set_dbd_for_ms ? 8 : dbd;
  1838. cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
  1839. cmd[2] = modepage;
  1840. /* caller might not be interested in sense, but we need it */
  1841. if (!sshdr)
  1842. sshdr = &my_sshdr;
  1843. retry:
  1844. use_10_for_ms = sdev->use_10_for_ms;
  1845. if (use_10_for_ms) {
  1846. if (len < 8)
  1847. len = 8;
  1848. cmd[0] = MODE_SENSE_10;
  1849. cmd[8] = len;
  1850. header_length = 8;
  1851. } else {
  1852. if (len < 4)
  1853. len = 4;
  1854. cmd[0] = MODE_SENSE;
  1855. cmd[4] = len;
  1856. header_length = 4;
  1857. }
  1858. memset(buffer, 0, len);
  1859. result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
  1860. sshdr, timeout, retries, NULL);
  1861. if (result < 0)
  1862. return result;
  1863. /* This code looks awful: what it's doing is making sure an
  1864. * ILLEGAL REQUEST sense return identifies the actual command
  1865. * byte as the problem. MODE_SENSE commands can return
  1866. * ILLEGAL REQUEST if the code page isn't supported */
  1867. if (use_10_for_ms && !scsi_status_is_good(result) &&
  1868. driver_byte(result) == DRIVER_SENSE) {
  1869. if (scsi_sense_valid(sshdr)) {
  1870. if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
  1871. (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
  1872. /*
  1873. * Invalid command operation code
  1874. */
  1875. sdev->use_10_for_ms = 0;
  1876. goto retry;
  1877. }
  1878. }
  1879. }
  1880. if (scsi_status_is_good(result)) {
  1881. if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
  1882. (modepage == 6 || modepage == 8))) {
  1883. /* Initio breakage? */
  1884. header_length = 0;
  1885. data->length = 13;
  1886. data->medium_type = 0;
  1887. data->device_specific = 0;
  1888. data->longlba = 0;
  1889. data->block_descriptor_length = 0;
  1890. } else if (use_10_for_ms) {
  1891. data->length = buffer[0]*256 + buffer[1] + 2;
  1892. data->medium_type = buffer[2];
  1893. data->device_specific = buffer[3];
  1894. data->longlba = buffer[4] & 0x01;
  1895. data->block_descriptor_length = buffer[6]*256
  1896. + buffer[7];
  1897. } else {
  1898. data->length = buffer[0] + 1;
  1899. data->medium_type = buffer[1];
  1900. data->device_specific = buffer[2];
  1901. data->block_descriptor_length = buffer[3];
  1902. }
  1903. data->header_length = header_length;
  1904. result = 0;
  1905. } else if ((status_byte(result) == CHECK_CONDITION) &&
  1906. scsi_sense_valid(sshdr) &&
  1907. sshdr->sense_key == UNIT_ATTENTION && retry_count) {
  1908. retry_count--;
  1909. goto retry;
  1910. }
  1911. if (result > 0)
  1912. result = -EIO;
  1913. return result;
  1914. }
  1915. EXPORT_SYMBOL(scsi_mode_sense);
  1916. /**
  1917. * scsi_test_unit_ready - test if unit is ready
  1918. * @sdev: scsi device to change the state of.
  1919. * @timeout: command timeout
  1920. * @retries: number of retries before failing
  1921. * @sshdr: outpout pointer for decoded sense information.
  1922. *
  1923. * Returns zero if unsuccessful or an error if TUR failed. For
  1924. * removable media, UNIT_ATTENTION sets ->changed flag.
  1925. **/
  1926. int
  1927. scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
  1928. struct scsi_sense_hdr *sshdr)
  1929. {
  1930. char cmd[] = {
  1931. TEST_UNIT_READY, 0, 0, 0, 0, 0,
  1932. };
  1933. int result;
  1934. /* try to eat the UNIT_ATTENTION if there are enough retries */
  1935. do {
  1936. result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
  1937. timeout, 1, NULL);
  1938. if (sdev->removable && scsi_sense_valid(sshdr) &&
  1939. sshdr->sense_key == UNIT_ATTENTION)
  1940. sdev->changed = 1;
  1941. } while (scsi_sense_valid(sshdr) &&
  1942. sshdr->sense_key == UNIT_ATTENTION && --retries);
  1943. return result;
  1944. }
  1945. EXPORT_SYMBOL(scsi_test_unit_ready);
  1946. /**
  1947. * scsi_device_set_state - Take the given device through the device state model.
  1948. * @sdev: scsi device to change the state of.
  1949. * @state: state to change to.
  1950. *
  1951. * Returns zero if successful or an error if the requested
  1952. * transition is illegal.
  1953. */
  1954. int
  1955. scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
  1956. {
  1957. enum scsi_device_state oldstate = sdev->sdev_state;
  1958. if (state == oldstate)
  1959. return 0;
  1960. switch (state) {
  1961. case SDEV_CREATED:
  1962. switch (oldstate) {
  1963. case SDEV_CREATED_BLOCK:
  1964. break;
  1965. default:
  1966. goto illegal;
  1967. }
  1968. break;
  1969. case SDEV_RUNNING:
  1970. switch (oldstate) {
  1971. case SDEV_CREATED:
  1972. case SDEV_OFFLINE:
  1973. case SDEV_TRANSPORT_OFFLINE:
  1974. case SDEV_QUIESCE:
  1975. case SDEV_BLOCK:
  1976. break;
  1977. default:
  1978. goto illegal;
  1979. }
  1980. break;
  1981. case SDEV_QUIESCE:
  1982. switch (oldstate) {
  1983. case SDEV_RUNNING:
  1984. case SDEV_OFFLINE:
  1985. case SDEV_TRANSPORT_OFFLINE:
  1986. break;
  1987. default:
  1988. goto illegal;
  1989. }
  1990. break;
  1991. case SDEV_OFFLINE:
  1992. case SDEV_TRANSPORT_OFFLINE:
  1993. switch (oldstate) {
  1994. case SDEV_CREATED:
  1995. case SDEV_RUNNING:
  1996. case SDEV_QUIESCE:
  1997. case SDEV_BLOCK:
  1998. break;
  1999. default:
  2000. goto illegal;
  2001. }
  2002. break;
  2003. case SDEV_BLOCK:
  2004. switch (oldstate) {
  2005. case SDEV_RUNNING:
  2006. case SDEV_CREATED_BLOCK:
  2007. case SDEV_QUIESCE:
  2008. case SDEV_OFFLINE:
  2009. break;
  2010. default:
  2011. goto illegal;
  2012. }
  2013. break;
  2014. case SDEV_CREATED_BLOCK:
  2015. switch (oldstate) {
  2016. case SDEV_CREATED:
  2017. break;
  2018. default:
  2019. goto illegal;
  2020. }
  2021. break;
  2022. case SDEV_CANCEL:
  2023. switch (oldstate) {
  2024. case SDEV_CREATED:
  2025. case SDEV_RUNNING:
  2026. case SDEV_QUIESCE:
  2027. case SDEV_OFFLINE:
  2028. case SDEV_TRANSPORT_OFFLINE:
  2029. break;
  2030. default:
  2031. goto illegal;
  2032. }
  2033. break;
  2034. case SDEV_DEL:
  2035. switch (oldstate) {
  2036. case SDEV_CREATED:
  2037. case SDEV_RUNNING:
  2038. case SDEV_OFFLINE:
  2039. case SDEV_TRANSPORT_OFFLINE:
  2040. case SDEV_CANCEL:
  2041. case SDEV_BLOCK:
  2042. case SDEV_CREATED_BLOCK:
  2043. break;
  2044. default:
  2045. goto illegal;
  2046. }
  2047. break;
  2048. }
  2049. sdev->offline_already = false;
  2050. sdev->sdev_state = state;
  2051. return 0;
  2052. illegal:
  2053. SCSI_LOG_ERROR_RECOVERY(1,
  2054. sdev_printk(KERN_ERR, sdev,
  2055. "Illegal state transition %s->%s",
  2056. scsi_device_state_name(oldstate),
  2057. scsi_device_state_name(state))
  2058. );
  2059. return -EINVAL;
  2060. }
  2061. EXPORT_SYMBOL(scsi_device_set_state);
  2062. /**
  2063. * sdev_evt_emit - emit a single SCSI device uevent
  2064. * @sdev: associated SCSI device
  2065. * @evt: event to emit
  2066. *
  2067. * Send a single uevent (scsi_event) to the associated scsi_device.
  2068. */
  2069. static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
  2070. {
  2071. int idx = 0;
  2072. char *envp[3];
  2073. switch (evt->evt_type) {
  2074. case SDEV_EVT_MEDIA_CHANGE:
  2075. envp[idx++] = "SDEV_MEDIA_CHANGE=1";
  2076. break;
  2077. case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
  2078. scsi_rescan_device(&sdev->sdev_gendev);
  2079. envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
  2080. break;
  2081. case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
  2082. envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
  2083. break;
  2084. case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
  2085. envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
  2086. break;
  2087. case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
  2088. envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
  2089. break;
  2090. case SDEV_EVT_LUN_CHANGE_REPORTED:
  2091. envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
  2092. break;
  2093. case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
  2094. envp[idx++] = "SDEV_UA=ASYMMETRIC_ACCESS_STATE_CHANGED";
  2095. break;
  2096. case SDEV_EVT_POWER_ON_RESET_OCCURRED:
  2097. envp[idx++] = "SDEV_UA=POWER_ON_RESET_OCCURRED";
  2098. break;
  2099. default:
  2100. /* do nothing */
  2101. break;
  2102. }
  2103. envp[idx++] = NULL;
  2104. kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
  2105. }
  2106. /**
  2107. * sdev_evt_thread - send a uevent for each scsi event
  2108. * @work: work struct for scsi_device
  2109. *
  2110. * Dispatch queued events to their associated scsi_device kobjects
  2111. * as uevents.
  2112. */
  2113. void scsi_evt_thread(struct work_struct *work)
  2114. {
  2115. struct scsi_device *sdev;
  2116. enum scsi_device_event evt_type;
  2117. LIST_HEAD(event_list);
  2118. sdev = container_of(work, struct scsi_device, event_work);
  2119. for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
  2120. if (test_and_clear_bit(evt_type, sdev->pending_events))
  2121. sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
  2122. while (1) {
  2123. struct scsi_event *evt;
  2124. struct list_head *this, *tmp;
  2125. unsigned long flags;
  2126. spin_lock_irqsave(&sdev->list_lock, flags);
  2127. list_splice_init(&sdev->event_list, &event_list);
  2128. spin_unlock_irqrestore(&sdev->list_lock, flags);
  2129. if (list_empty(&event_list))
  2130. break;
  2131. list_for_each_safe(this, tmp, &event_list) {
  2132. evt = list_entry(this, struct scsi_event, node);
  2133. list_del(&evt->node);
  2134. scsi_evt_emit(sdev, evt);
  2135. kfree(evt);
  2136. }
  2137. }
  2138. }
  2139. /**
  2140. * sdev_evt_send - send asserted event to uevent thread
  2141. * @sdev: scsi_device event occurred on
  2142. * @evt: event to send
  2143. *
  2144. * Assert scsi device event asynchronously.
  2145. */
  2146. void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
  2147. {
  2148. unsigned long flags;
  2149. #if 0
  2150. /* FIXME: currently this check eliminates all media change events
  2151. * for polled devices. Need to update to discriminate between AN
  2152. * and polled events */
  2153. if (!test_bit(evt->evt_type, sdev->supported_events)) {
  2154. kfree(evt);
  2155. return;
  2156. }
  2157. #endif
  2158. spin_lock_irqsave(&sdev->list_lock, flags);
  2159. list_add_tail(&evt->node, &sdev->event_list);
  2160. schedule_work(&sdev->event_work);
  2161. spin_unlock_irqrestore(&sdev->list_lock, flags);
  2162. }
  2163. EXPORT_SYMBOL_GPL(sdev_evt_send);
  2164. /**
  2165. * sdev_evt_alloc - allocate a new scsi event
  2166. * @evt_type: type of event to allocate
  2167. * @gfpflags: GFP flags for allocation
  2168. *
  2169. * Allocates and returns a new scsi_event.
  2170. */
  2171. struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
  2172. gfp_t gfpflags)
  2173. {
  2174. struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
  2175. if (!evt)
  2176. return NULL;
  2177. evt->evt_type = evt_type;
  2178. INIT_LIST_HEAD(&evt->node);
  2179. /* evt_type-specific initialization, if any */
  2180. switch (evt_type) {
  2181. case SDEV_EVT_MEDIA_CHANGE:
  2182. case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
  2183. case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
  2184. case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
  2185. case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
  2186. case SDEV_EVT_LUN_CHANGE_REPORTED:
  2187. case SDEV_EVT_ALUA_STATE_CHANGE_REPORTED:
  2188. case SDEV_EVT_POWER_ON_RESET_OCCURRED:
  2189. default:
  2190. /* do nothing */
  2191. break;
  2192. }
  2193. return evt;
  2194. }
  2195. EXPORT_SYMBOL_GPL(sdev_evt_alloc);
  2196. /**
  2197. * sdev_evt_send_simple - send asserted event to uevent thread
  2198. * @sdev: scsi_device event occurred on
  2199. * @evt_type: type of event to send
  2200. * @gfpflags: GFP flags for allocation
  2201. *
  2202. * Assert scsi device event asynchronously, given an event type.
  2203. */
  2204. void sdev_evt_send_simple(struct scsi_device *sdev,
  2205. enum scsi_device_event evt_type, gfp_t gfpflags)
  2206. {
  2207. struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
  2208. if (!evt) {
  2209. sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
  2210. evt_type);
  2211. return;
  2212. }
  2213. sdev_evt_send(sdev, evt);
  2214. }
  2215. EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
  2216. /**
  2217. * scsi_device_quiesce - Block all commands except power management.
  2218. * @sdev: scsi device to quiesce.
  2219. *
  2220. * This works by trying to transition to the SDEV_QUIESCE state
  2221. * (which must be a legal transition). When the device is in this
  2222. * state, only power management requests will be accepted, all others will
  2223. * be deferred.
  2224. *
  2225. * Must be called with user context, may sleep.
  2226. *
  2227. * Returns zero if unsuccessful or an error if not.
  2228. */
  2229. int
  2230. scsi_device_quiesce(struct scsi_device *sdev)
  2231. {
  2232. struct request_queue *q = sdev->request_queue;
  2233. int err;
  2234. /*
  2235. * It is allowed to call scsi_device_quiesce() multiple times from
  2236. * the same context but concurrent scsi_device_quiesce() calls are
  2237. * not allowed.
  2238. */
  2239. WARN_ON_ONCE(sdev->quiesced_by && sdev->quiesced_by != current);
  2240. if (sdev->quiesced_by == current)
  2241. return 0;
  2242. blk_set_pm_only(q);
  2243. blk_mq_freeze_queue(q);
  2244. /*
  2245. * Ensure that the effect of blk_set_pm_only() will be visible
  2246. * for percpu_ref_tryget() callers that occur after the queue
  2247. * unfreeze even if the queue was already frozen before this function
  2248. * was called. See also https://lwn.net/Articles/573497/.
  2249. */
  2250. synchronize_rcu();
  2251. blk_mq_unfreeze_queue(q);
  2252. mutex_lock(&sdev->state_mutex);
  2253. err = scsi_device_set_state(sdev, SDEV_QUIESCE);
  2254. if (err == 0)
  2255. sdev->quiesced_by = current;
  2256. else
  2257. blk_clear_pm_only(q);
  2258. mutex_unlock(&sdev->state_mutex);
  2259. return err;
  2260. }
  2261. EXPORT_SYMBOL(scsi_device_quiesce);
  2262. /**
  2263. * scsi_device_resume - Restart user issued commands to a quiesced device.
  2264. * @sdev: scsi device to resume.
  2265. *
  2266. * Moves the device from quiesced back to running and restarts the
  2267. * queues.
  2268. *
  2269. * Must be called with user context, may sleep.
  2270. */
  2271. void scsi_device_resume(struct scsi_device *sdev)
  2272. {
  2273. /* check if the device state was mutated prior to resume, and if
  2274. * so assume the state is being managed elsewhere (for example
  2275. * device deleted during suspend)
  2276. */
  2277. mutex_lock(&sdev->state_mutex);
  2278. if (sdev->sdev_state == SDEV_QUIESCE)
  2279. scsi_device_set_state(sdev, SDEV_RUNNING);
  2280. if (sdev->quiesced_by) {
  2281. sdev->quiesced_by = NULL;
  2282. blk_clear_pm_only(sdev->request_queue);
  2283. }
  2284. mutex_unlock(&sdev->state_mutex);
  2285. }
  2286. EXPORT_SYMBOL(scsi_device_resume);
  2287. static void
  2288. device_quiesce_fn(struct scsi_device *sdev, void *data)
  2289. {
  2290. scsi_device_quiesce(sdev);
  2291. }
  2292. void
  2293. scsi_target_quiesce(struct scsi_target *starget)
  2294. {
  2295. starget_for_each_device(starget, NULL, device_quiesce_fn);
  2296. }
  2297. EXPORT_SYMBOL(scsi_target_quiesce);
  2298. static void
  2299. device_resume_fn(struct scsi_device *sdev, void *data)
  2300. {
  2301. scsi_device_resume(sdev);
  2302. }
  2303. void
  2304. scsi_target_resume(struct scsi_target *starget)
  2305. {
  2306. starget_for_each_device(starget, NULL, device_resume_fn);
  2307. }
  2308. EXPORT_SYMBOL(scsi_target_resume);
  2309. /**
  2310. * scsi_internal_device_block_nowait - try to transition to the SDEV_BLOCK state
  2311. * @sdev: device to block
  2312. *
  2313. * Pause SCSI command processing on the specified device. Does not sleep.
  2314. *
  2315. * Returns zero if successful or a negative error code upon failure.
  2316. *
  2317. * Notes:
  2318. * This routine transitions the device to the SDEV_BLOCK state (which must be
  2319. * a legal transition). When the device is in this state, command processing
  2320. * is paused until the device leaves the SDEV_BLOCK state. See also
  2321. * scsi_internal_device_unblock_nowait().
  2322. */
  2323. int scsi_internal_device_block_nowait(struct scsi_device *sdev)
  2324. {
  2325. struct request_queue *q = sdev->request_queue;
  2326. int err = 0;
  2327. err = scsi_device_set_state(sdev, SDEV_BLOCK);
  2328. if (err) {
  2329. err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
  2330. if (err)
  2331. return err;
  2332. }
  2333. /*
  2334. * The device has transitioned to SDEV_BLOCK. Stop the
  2335. * block layer from calling the midlayer with this device's
  2336. * request queue.
  2337. */
  2338. blk_mq_quiesce_queue_nowait(q);
  2339. return 0;
  2340. }
  2341. EXPORT_SYMBOL_GPL(scsi_internal_device_block_nowait);
  2342. /**
  2343. * scsi_internal_device_block - try to transition to the SDEV_BLOCK state
  2344. * @sdev: device to block
  2345. *
  2346. * Pause SCSI command processing on the specified device and wait until all
  2347. * ongoing scsi_request_fn() / scsi_queue_rq() calls have finished. May sleep.
  2348. *
  2349. * Returns zero if successful or a negative error code upon failure.
  2350. *
  2351. * Note:
  2352. * This routine transitions the device to the SDEV_BLOCK state (which must be
  2353. * a legal transition). When the device is in this state, command processing
  2354. * is paused until the device leaves the SDEV_BLOCK state. See also
  2355. * scsi_internal_device_unblock().
  2356. */
  2357. static int scsi_internal_device_block(struct scsi_device *sdev)
  2358. {
  2359. struct request_queue *q = sdev->request_queue;
  2360. int err;
  2361. mutex_lock(&sdev->state_mutex);
  2362. err = scsi_internal_device_block_nowait(sdev);
  2363. if (err == 0)
  2364. blk_mq_quiesce_queue(q);
  2365. mutex_unlock(&sdev->state_mutex);
  2366. return err;
  2367. }
  2368. void scsi_start_queue(struct scsi_device *sdev)
  2369. {
  2370. struct request_queue *q = sdev->request_queue;
  2371. blk_mq_unquiesce_queue(q);
  2372. }
  2373. /**
  2374. * scsi_internal_device_unblock_nowait - resume a device after a block request
  2375. * @sdev: device to resume
  2376. * @new_state: state to set the device to after unblocking
  2377. *
  2378. * Restart the device queue for a previously suspended SCSI device. Does not
  2379. * sleep.
  2380. *
  2381. * Returns zero if successful or a negative error code upon failure.
  2382. *
  2383. * Notes:
  2384. * This routine transitions the device to the SDEV_RUNNING state or to one of
  2385. * the offline states (which must be a legal transition) allowing the midlayer
  2386. * to goose the queue for this device.
  2387. */
  2388. int scsi_internal_device_unblock_nowait(struct scsi_device *sdev,
  2389. enum scsi_device_state new_state)
  2390. {
  2391. switch (new_state) {
  2392. case SDEV_RUNNING:
  2393. case SDEV_TRANSPORT_OFFLINE:
  2394. break;
  2395. default:
  2396. return -EINVAL;
  2397. }
  2398. /*
  2399. * Try to transition the scsi device to SDEV_RUNNING or one of the
  2400. * offlined states and goose the device queue if successful.
  2401. */
  2402. switch (sdev->sdev_state) {
  2403. case SDEV_BLOCK:
  2404. case SDEV_TRANSPORT_OFFLINE:
  2405. sdev->sdev_state = new_state;
  2406. break;
  2407. case SDEV_CREATED_BLOCK:
  2408. if (new_state == SDEV_TRANSPORT_OFFLINE ||
  2409. new_state == SDEV_OFFLINE)
  2410. sdev->sdev_state = new_state;
  2411. else
  2412. sdev->sdev_state = SDEV_CREATED;
  2413. break;
  2414. case SDEV_CANCEL:
  2415. case SDEV_OFFLINE:
  2416. break;
  2417. default:
  2418. return -EINVAL;
  2419. }
  2420. scsi_start_queue(sdev);
  2421. return 0;
  2422. }
  2423. EXPORT_SYMBOL_GPL(scsi_internal_device_unblock_nowait);
  2424. /**
  2425. * scsi_internal_device_unblock - resume a device after a block request
  2426. * @sdev: device to resume
  2427. * @new_state: state to set the device to after unblocking
  2428. *
  2429. * Restart the device queue for a previously suspended SCSI device. May sleep.
  2430. *
  2431. * Returns zero if successful or a negative error code upon failure.
  2432. *
  2433. * Notes:
  2434. * This routine transitions the device to the SDEV_RUNNING state or to one of
  2435. * the offline states (which must be a legal transition) allowing the midlayer
  2436. * to goose the queue for this device.
  2437. */
  2438. static int scsi_internal_device_unblock(struct scsi_device *sdev,
  2439. enum scsi_device_state new_state)
  2440. {
  2441. int ret;
  2442. mutex_lock(&sdev->state_mutex);
  2443. ret = scsi_internal_device_unblock_nowait(sdev, new_state);
  2444. mutex_unlock(&sdev->state_mutex);
  2445. return ret;
  2446. }
  2447. static void
  2448. device_block(struct scsi_device *sdev, void *data)
  2449. {
  2450. int ret;
  2451. ret = scsi_internal_device_block(sdev);
  2452. WARN_ONCE(ret, "scsi_internal_device_block(%s) failed: ret = %d\n",
  2453. dev_name(&sdev->sdev_gendev), ret);
  2454. }
  2455. static int
  2456. target_block(struct device *dev, void *data)
  2457. {
  2458. if (scsi_is_target_device(dev))
  2459. starget_for_each_device(to_scsi_target(dev), NULL,
  2460. device_block);
  2461. return 0;
  2462. }
  2463. void
  2464. scsi_target_block(struct device *dev)
  2465. {
  2466. if (scsi_is_target_device(dev))
  2467. starget_for_each_device(to_scsi_target(dev), NULL,
  2468. device_block);
  2469. else
  2470. device_for_each_child(dev, NULL, target_block);
  2471. }
  2472. EXPORT_SYMBOL_GPL(scsi_target_block);
  2473. static void
  2474. device_unblock(struct scsi_device *sdev, void *data)
  2475. {
  2476. scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
  2477. }
  2478. static int
  2479. target_unblock(struct device *dev, void *data)
  2480. {
  2481. if (scsi_is_target_device(dev))
  2482. starget_for_each_device(to_scsi_target(dev), data,
  2483. device_unblock);
  2484. return 0;
  2485. }
  2486. void
  2487. scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
  2488. {
  2489. if (scsi_is_target_device(dev))
  2490. starget_for_each_device(to_scsi_target(dev), &new_state,
  2491. device_unblock);
  2492. else
  2493. device_for_each_child(dev, &new_state, target_unblock);
  2494. }
  2495. EXPORT_SYMBOL_GPL(scsi_target_unblock);
  2496. int
  2497. scsi_host_block(struct Scsi_Host *shost)
  2498. {
  2499. struct scsi_device *sdev;
  2500. int ret = 0;
  2501. /*
  2502. * Call scsi_internal_device_block_nowait so we can avoid
  2503. * calling synchronize_rcu() for each LUN.
  2504. */
  2505. shost_for_each_device(sdev, shost) {
  2506. mutex_lock(&sdev->state_mutex);
  2507. ret = scsi_internal_device_block_nowait(sdev);
  2508. mutex_unlock(&sdev->state_mutex);
  2509. if (ret) {
  2510. scsi_device_put(sdev);
  2511. break;
  2512. }
  2513. }
  2514. /*
  2515. * SCSI never enables blk-mq's BLK_MQ_F_BLOCKING flag so
  2516. * calling synchronize_rcu() once is enough.
  2517. */
  2518. WARN_ON_ONCE(shost->tag_set.flags & BLK_MQ_F_BLOCKING);
  2519. if (!ret)
  2520. synchronize_rcu();
  2521. return ret;
  2522. }
  2523. EXPORT_SYMBOL_GPL(scsi_host_block);
  2524. int
  2525. scsi_host_unblock(struct Scsi_Host *shost, int new_state)
  2526. {
  2527. struct scsi_device *sdev;
  2528. int ret = 0;
  2529. shost_for_each_device(sdev, shost) {
  2530. ret = scsi_internal_device_unblock(sdev, new_state);
  2531. if (ret) {
  2532. scsi_device_put(sdev);
  2533. break;
  2534. }
  2535. }
  2536. return ret;
  2537. }
  2538. EXPORT_SYMBOL_GPL(scsi_host_unblock);
  2539. /**
  2540. * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
  2541. * @sgl: scatter-gather list
  2542. * @sg_count: number of segments in sg
  2543. * @offset: offset in bytes into sg, on return offset into the mapped area
  2544. * @len: bytes to map, on return number of bytes mapped
  2545. *
  2546. * Returns virtual address of the start of the mapped page
  2547. */
  2548. void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
  2549. size_t *offset, size_t *len)
  2550. {
  2551. int i;
  2552. size_t sg_len = 0, len_complete = 0;
  2553. struct scatterlist *sg;
  2554. struct page *page;
  2555. WARN_ON(!irqs_disabled());
  2556. for_each_sg(sgl, sg, sg_count, i) {
  2557. len_complete = sg_len; /* Complete sg-entries */
  2558. sg_len += sg->length;
  2559. if (sg_len > *offset)
  2560. break;
  2561. }
  2562. if (unlikely(i == sg_count)) {
  2563. printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
  2564. "elements %d\n",
  2565. __func__, sg_len, *offset, sg_count);
  2566. WARN_ON(1);
  2567. return NULL;
  2568. }
  2569. /* Offset starting from the beginning of first page in this sg-entry */
  2570. *offset = *offset - len_complete + sg->offset;
  2571. /* Assumption: contiguous pages can be accessed as "page + i" */
  2572. page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
  2573. *offset &= ~PAGE_MASK;
  2574. /* Bytes in this sg-entry from *offset to the end of the page */
  2575. sg_len = PAGE_SIZE - *offset;
  2576. if (*len > sg_len)
  2577. *len = sg_len;
  2578. return kmap_atomic(page);
  2579. }
  2580. EXPORT_SYMBOL(scsi_kmap_atomic_sg);
  2581. /**
  2582. * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
  2583. * @virt: virtual address to be unmapped
  2584. */
  2585. void scsi_kunmap_atomic_sg(void *virt)
  2586. {
  2587. kunmap_atomic(virt);
  2588. }
  2589. EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
  2590. void sdev_disable_disk_events(struct scsi_device *sdev)
  2591. {
  2592. atomic_inc(&sdev->disk_events_disable_depth);
  2593. }
  2594. EXPORT_SYMBOL(sdev_disable_disk_events);
  2595. void sdev_enable_disk_events(struct scsi_device *sdev)
  2596. {
  2597. if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
  2598. return;
  2599. atomic_dec(&sdev->disk_events_disable_depth);
  2600. }
  2601. EXPORT_SYMBOL(sdev_enable_disk_events);
  2602. static unsigned char designator_prio(const unsigned char *d)
  2603. {
  2604. if (d[1] & 0x30)
  2605. /* not associated with LUN */
  2606. return 0;
  2607. if (d[3] == 0)
  2608. /* invalid length */
  2609. return 0;
  2610. /*
  2611. * Order of preference for lun descriptor:
  2612. * - SCSI name string
  2613. * - NAA IEEE Registered Extended
  2614. * - EUI-64 based 16-byte
  2615. * - EUI-64 based 12-byte
  2616. * - NAA IEEE Registered
  2617. * - NAA IEEE Extended
  2618. * - EUI-64 based 8-byte
  2619. * - SCSI name string (truncated)
  2620. * - T10 Vendor ID
  2621. * as longer descriptors reduce the likelyhood
  2622. * of identification clashes.
  2623. */
  2624. switch (d[1] & 0xf) {
  2625. case 8:
  2626. /* SCSI name string, variable-length UTF-8 */
  2627. return 9;
  2628. case 3:
  2629. switch (d[4] >> 4) {
  2630. case 6:
  2631. /* NAA registered extended */
  2632. return 8;
  2633. case 5:
  2634. /* NAA registered */
  2635. return 5;
  2636. case 4:
  2637. /* NAA extended */
  2638. return 4;
  2639. case 3:
  2640. /* NAA locally assigned */
  2641. return 1;
  2642. default:
  2643. break;
  2644. }
  2645. break;
  2646. case 2:
  2647. switch (d[3]) {
  2648. case 16:
  2649. /* EUI64-based, 16 byte */
  2650. return 7;
  2651. case 12:
  2652. /* EUI64-based, 12 byte */
  2653. return 6;
  2654. case 8:
  2655. /* EUI64-based, 8 byte */
  2656. return 3;
  2657. default:
  2658. break;
  2659. }
  2660. break;
  2661. case 1:
  2662. /* T10 vendor ID */
  2663. return 1;
  2664. default:
  2665. break;
  2666. }
  2667. return 0;
  2668. }
  2669. /**
  2670. * scsi_vpd_lun_id - return a unique device identification
  2671. * @sdev: SCSI device
  2672. * @id: buffer for the identification
  2673. * @id_len: length of the buffer
  2674. *
  2675. * Copies a unique device identification into @id based
  2676. * on the information in the VPD page 0x83 of the device.
  2677. * The string will be formatted as a SCSI name string.
  2678. *
  2679. * Returns the length of the identification or error on failure.
  2680. * If the identifier is longer than the supplied buffer the actual
  2681. * identifier length is returned and the buffer is not zero-padded.
  2682. */
  2683. int scsi_vpd_lun_id(struct scsi_device *sdev, char *id, size_t id_len)
  2684. {
  2685. u8 cur_id_prio = 0;
  2686. u8 cur_id_size = 0;
  2687. const unsigned char *d, *cur_id_str;
  2688. const struct scsi_vpd *vpd_pg83;
  2689. int id_size = -EINVAL;
  2690. rcu_read_lock();
  2691. vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
  2692. if (!vpd_pg83) {
  2693. rcu_read_unlock();
  2694. return -ENXIO;
  2695. }
  2696. /* The id string must be at least 20 bytes + terminating NULL byte */
  2697. if (id_len < 21) {
  2698. rcu_read_unlock();
  2699. return -EINVAL;
  2700. }
  2701. memset(id, 0, id_len);
  2702. d = vpd_pg83->data + 4;
  2703. while (d < vpd_pg83->data + vpd_pg83->len) {
  2704. u8 prio = designator_prio(d);
  2705. if (prio == 0 || cur_id_prio > prio)
  2706. goto next_desig;
  2707. switch (d[1] & 0xf) {
  2708. case 0x1:
  2709. /* T10 Vendor ID */
  2710. if (cur_id_size > d[3])
  2711. break;
  2712. cur_id_prio = prio;
  2713. cur_id_size = d[3];
  2714. if (cur_id_size + 4 > id_len)
  2715. cur_id_size = id_len - 4;
  2716. cur_id_str = d + 4;
  2717. id_size = snprintf(id, id_len, "t10.%*pE",
  2718. cur_id_size, cur_id_str);
  2719. break;
  2720. case 0x2:
  2721. /* EUI-64 */
  2722. cur_id_prio = prio;
  2723. cur_id_size = d[3];
  2724. cur_id_str = d + 4;
  2725. switch (cur_id_size) {
  2726. case 8:
  2727. id_size = snprintf(id, id_len,
  2728. "eui.%8phN",
  2729. cur_id_str);
  2730. break;
  2731. case 12:
  2732. id_size = snprintf(id, id_len,
  2733. "eui.%12phN",
  2734. cur_id_str);
  2735. break;
  2736. case 16:
  2737. id_size = snprintf(id, id_len,
  2738. "eui.%16phN",
  2739. cur_id_str);
  2740. break;
  2741. default:
  2742. break;
  2743. }
  2744. break;
  2745. case 0x3:
  2746. /* NAA */
  2747. cur_id_prio = prio;
  2748. cur_id_size = d[3];
  2749. cur_id_str = d + 4;
  2750. switch (cur_id_size) {
  2751. case 8:
  2752. id_size = snprintf(id, id_len,
  2753. "naa.%8phN",
  2754. cur_id_str);
  2755. break;
  2756. case 16:
  2757. id_size = snprintf(id, id_len,
  2758. "naa.%16phN",
  2759. cur_id_str);
  2760. break;
  2761. default:
  2762. break;
  2763. }
  2764. break;
  2765. case 0x8:
  2766. /* SCSI name string */
  2767. if (cur_id_size > d[3])
  2768. break;
  2769. /* Prefer others for truncated descriptor */
  2770. if (d[3] > id_len) {
  2771. prio = 2;
  2772. if (cur_id_prio > prio)
  2773. break;
  2774. }
  2775. cur_id_prio = prio;
  2776. cur_id_size = id_size = d[3];
  2777. cur_id_str = d + 4;
  2778. if (cur_id_size >= id_len)
  2779. cur_id_size = id_len - 1;
  2780. memcpy(id, cur_id_str, cur_id_size);
  2781. break;
  2782. default:
  2783. break;
  2784. }
  2785. next_desig:
  2786. d += d[3] + 4;
  2787. }
  2788. rcu_read_unlock();
  2789. return id_size;
  2790. }
  2791. EXPORT_SYMBOL(scsi_vpd_lun_id);
  2792. /*
  2793. * scsi_vpd_tpg_id - return a target port group identifier
  2794. * @sdev: SCSI device
  2795. *
  2796. * Returns the Target Port Group identifier from the information
  2797. * froom VPD page 0x83 of the device.
  2798. *
  2799. * Returns the identifier or error on failure.
  2800. */
  2801. int scsi_vpd_tpg_id(struct scsi_device *sdev, int *rel_id)
  2802. {
  2803. const unsigned char *d;
  2804. const struct scsi_vpd *vpd_pg83;
  2805. int group_id = -EAGAIN, rel_port = -1;
  2806. rcu_read_lock();
  2807. vpd_pg83 = rcu_dereference(sdev->vpd_pg83);
  2808. if (!vpd_pg83) {
  2809. rcu_read_unlock();
  2810. return -ENXIO;
  2811. }
  2812. d = vpd_pg83->data + 4;
  2813. while (d < vpd_pg83->data + vpd_pg83->len) {
  2814. switch (d[1] & 0xf) {
  2815. case 0x4:
  2816. /* Relative target port */
  2817. rel_port = get_unaligned_be16(&d[6]);
  2818. break;
  2819. case 0x5:
  2820. /* Target port group */
  2821. group_id = get_unaligned_be16(&d[6]);
  2822. break;
  2823. default:
  2824. break;
  2825. }
  2826. d += d[3] + 4;
  2827. }
  2828. rcu_read_unlock();
  2829. if (group_id >= 0 && rel_id && rel_port != -1)
  2830. *rel_id = rel_port;
  2831. return group_id;
  2832. }
  2833. EXPORT_SYMBOL(scsi_vpd_tpg_id);