scsi_lib.c 93 KB

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