scsi_lib.c 87 KB

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