scsi_lib.c 90 KB

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