sg.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * History:
  4. * Started: Aug 9 by Lawrence Foard ([email protected]),
  5. * to allow user process control of SCSI devices.
  6. * Development Sponsored by Killy Corp. NY NY
  7. *
  8. * Original driver (sg.c):
  9. * Copyright (C) 1992 Lawrence Foard
  10. * Version 2 and 3 extensions to driver:
  11. * Copyright (C) 1998 - 2014 Douglas Gilbert
  12. */
  13. static int sg_version_num = 30536; /* 2 digits for each component */
  14. #define SG_VERSION_STR "3.5.36"
  15. /*
  16. * D. P. Gilbert ([email protected]), notes:
  17. * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
  18. * the kernel/module needs to be built with CONFIG_SCSI_LOGGING
  19. * (otherwise the macros compile to empty statements).
  20. *
  21. */
  22. #include <linux/module.h>
  23. #include <linux/fs.h>
  24. #include <linux/kernel.h>
  25. #include <linux/sched.h>
  26. #include <linux/string.h>
  27. #include <linux/mm.h>
  28. #include <linux/errno.h>
  29. #include <linux/mtio.h>
  30. #include <linux/ioctl.h>
  31. #include <linux/major.h>
  32. #include <linux/slab.h>
  33. #include <linux/fcntl.h>
  34. #include <linux/init.h>
  35. #include <linux/poll.h>
  36. #include <linux/moduleparam.h>
  37. #include <linux/cdev.h>
  38. #include <linux/idr.h>
  39. #include <linux/seq_file.h>
  40. #include <linux/blkdev.h>
  41. #include <linux/delay.h>
  42. #include <linux/blktrace_api.h>
  43. #include <linux/mutex.h>
  44. #include <linux/atomic.h>
  45. #include <linux/ratelimit.h>
  46. #include <linux/uio.h>
  47. #include <linux/cred.h> /* for sg_check_file_access() */
  48. #include <scsi/scsi.h>
  49. #include <scsi/scsi_cmnd.h>
  50. #include <scsi/scsi_dbg.h>
  51. #include <scsi/scsi_device.h>
  52. #include <scsi/scsi_driver.h>
  53. #include <scsi/scsi_eh.h>
  54. #include <scsi/scsi_host.h>
  55. #include <scsi/scsi_ioctl.h>
  56. #include <scsi/scsi_tcq.h>
  57. #include <scsi/sg.h>
  58. #include "scsi_logging.h"
  59. #ifdef CONFIG_SCSI_PROC_FS
  60. #include <linux/proc_fs.h>
  61. static char *sg_version_date = "20140603";
  62. static int sg_proc_init(void);
  63. #endif
  64. #define SG_ALLOW_DIO_DEF 0
  65. #define SG_MAX_DEVS 32768
  66. /* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type
  67. * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater
  68. * than 16 bytes are "variable length" whose length is a multiple of 4
  69. */
  70. #define SG_MAX_CDB_SIZE 252
  71. #define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
  72. static int sg_big_buff = SG_DEF_RESERVED_SIZE;
  73. /* N.B. This variable is readable and writeable via
  74. /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
  75. of this size (or less if there is not enough memory) will be reserved
  76. for use by this file descriptor. [Deprecated usage: this variable is also
  77. readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
  78. the kernel (i.e. it is not a module).] */
  79. static int def_reserved_size = -1; /* picks up init parameter */
  80. static int sg_allow_dio = SG_ALLOW_DIO_DEF;
  81. static int scatter_elem_sz = SG_SCATTER_SZ;
  82. static int scatter_elem_sz_prev = SG_SCATTER_SZ;
  83. #define SG_SECTOR_SZ 512
  84. static int sg_add_device(struct device *, struct class_interface *);
  85. static void sg_remove_device(struct device *, struct class_interface *);
  86. static DEFINE_IDR(sg_index_idr);
  87. static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
  88. file descriptor list for device */
  89. static struct class_interface sg_interface = {
  90. .add_dev = sg_add_device,
  91. .remove_dev = sg_remove_device,
  92. };
  93. typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
  94. unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
  95. unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
  96. unsigned bufflen; /* Size of (aggregate) data buffer */
  97. struct page **pages;
  98. int page_order;
  99. char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
  100. unsigned char cmd_opcode; /* first byte of command */
  101. } Sg_scatter_hold;
  102. struct sg_device; /* forward declarations */
  103. struct sg_fd;
  104. typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */
  105. struct list_head entry; /* list entry */
  106. struct sg_fd *parentfp; /* NULL -> not in use */
  107. Sg_scatter_hold data; /* hold buffer, perhaps scatter list */
  108. sg_io_hdr_t header; /* scsi command+info, see <scsi/sg.h> */
  109. unsigned char sense_b[SCSI_SENSE_BUFFERSIZE];
  110. char res_used; /* 1 -> using reserve buffer, 0 -> not ... */
  111. char orphan; /* 1 -> drop on sight, 0 -> normal */
  112. char sg_io_owned; /* 1 -> packet belongs to SG_IO */
  113. /* done protected by rq_list_lock */
  114. char done; /* 0->before bh, 1->before read, 2->read */
  115. struct request *rq;
  116. struct bio *bio;
  117. struct execute_work ew;
  118. } Sg_request;
  119. typedef struct sg_fd { /* holds the state of a file descriptor */
  120. struct list_head sfd_siblings; /* protected by device's sfd_lock */
  121. struct sg_device *parentdp; /* owning device */
  122. wait_queue_head_t read_wait; /* queue read until command done */
  123. rwlock_t rq_list_lock; /* protect access to list in req_arr */
  124. struct mutex f_mutex; /* protect against changes in this fd */
  125. int timeout; /* defaults to SG_DEFAULT_TIMEOUT */
  126. int timeout_user; /* defaults to SG_DEFAULT_TIMEOUT_USER */
  127. Sg_scatter_hold reserve; /* buffer held for this file descriptor */
  128. struct list_head rq_list; /* head of request list */
  129. struct fasync_struct *async_qp; /* used by asynchronous notification */
  130. Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */
  131. char force_packid; /* 1 -> pack_id input to read(), 0 -> ignored */
  132. char cmd_q; /* 1 -> allow command queuing, 0 -> don't */
  133. unsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */
  134. char keep_orphan; /* 0 -> drop orphan (def), 1 -> keep for read() */
  135. char mmap_called; /* 0 -> mmap() never called on this fd */
  136. char res_in_use; /* 1 -> 'reserve' array in use */
  137. struct kref f_ref;
  138. struct execute_work ew;
  139. } Sg_fd;
  140. typedef struct sg_device { /* holds the state of each scsi generic device */
  141. struct scsi_device *device;
  142. wait_queue_head_t open_wait; /* queue open() when O_EXCL present */
  143. struct mutex open_rel_lock; /* held when in open() or release() */
  144. int sg_tablesize; /* adapter's max scatter-gather table size */
  145. u32 index; /* device index number */
  146. struct list_head sfds;
  147. rwlock_t sfd_lock; /* protect access to sfd list */
  148. atomic_t detaching; /* 0->device usable, 1->device detaching */
  149. bool exclude; /* 1->open(O_EXCL) succeeded and is active */
  150. int open_cnt; /* count of opens (perhaps < num(sfds) ) */
  151. char sgdebug; /* 0->off, 1->sense, 9->dump dev, 10-> all devs */
  152. char name[DISK_NAME_LEN];
  153. struct cdev * cdev; /* char_dev [sysfs: /sys/cdev/major/sg<n>] */
  154. struct kref d_ref;
  155. } Sg_device;
  156. /* tasklet or soft irq callback */
  157. static enum rq_end_io_ret sg_rq_end_io(struct request *rq, blk_status_t status);
  158. static int sg_start_req(Sg_request *srp, unsigned char *cmd);
  159. static int sg_finish_rem_req(Sg_request * srp);
  160. static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);
  161. static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,
  162. Sg_request * srp);
  163. static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
  164. const char __user *buf, size_t count, int blocking,
  165. int read_only, int sg_io_owned, Sg_request **o_srp);
  166. static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
  167. unsigned char *cmnd, int timeout, int blocking);
  168. static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
  169. static void sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp);
  170. static void sg_build_reserve(Sg_fd * sfp, int req_size);
  171. static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
  172. static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
  173. static Sg_fd *sg_add_sfp(Sg_device * sdp);
  174. static void sg_remove_sfp(struct kref *);
  175. static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id, bool *busy);
  176. static Sg_request *sg_add_request(Sg_fd * sfp);
  177. static int sg_remove_request(Sg_fd * sfp, Sg_request * srp);
  178. static Sg_device *sg_get_dev(int dev);
  179. static void sg_device_destroy(struct kref *kref);
  180. #define SZ_SG_HEADER sizeof(struct sg_header)
  181. #define SZ_SG_IO_HDR sizeof(sg_io_hdr_t)
  182. #define SZ_SG_IOVEC sizeof(sg_iovec_t)
  183. #define SZ_SG_REQ_INFO sizeof(sg_req_info_t)
  184. #define sg_printk(prefix, sdp, fmt, a...) \
  185. sdev_prefix_printk(prefix, (sdp)->device, (sdp)->name, fmt, ##a)
  186. /*
  187. * The SCSI interfaces that use read() and write() as an asynchronous variant of
  188. * ioctl(..., SG_IO, ...) are fundamentally unsafe, since there are lots of ways
  189. * to trigger read() and write() calls from various contexts with elevated
  190. * privileges. This can lead to kernel memory corruption (e.g. if these
  191. * interfaces are called through splice()) and privilege escalation inside
  192. * userspace (e.g. if a process with access to such a device passes a file
  193. * descriptor to a SUID binary as stdin/stdout/stderr).
  194. *
  195. * This function provides protection for the legacy API by restricting the
  196. * calling context.
  197. */
  198. static int sg_check_file_access(struct file *filp, const char *caller)
  199. {
  200. if (filp->f_cred != current_real_cred()) {
  201. pr_err_once("%s: process %d (%s) changed security contexts after opening file descriptor, this is not allowed.\n",
  202. caller, task_tgid_vnr(current), current->comm);
  203. return -EPERM;
  204. }
  205. return 0;
  206. }
  207. static int sg_allow_access(struct file *filp, unsigned char *cmd)
  208. {
  209. struct sg_fd *sfp = filp->private_data;
  210. if (sfp->parentdp->device->type == TYPE_SCANNER)
  211. return 0;
  212. if (!scsi_cmd_allowed(cmd, filp->f_mode))
  213. return -EPERM;
  214. return 0;
  215. }
  216. static int
  217. open_wait(Sg_device *sdp, int flags)
  218. {
  219. int retval = 0;
  220. if (flags & O_EXCL) {
  221. while (sdp->open_cnt > 0) {
  222. mutex_unlock(&sdp->open_rel_lock);
  223. retval = wait_event_interruptible(sdp->open_wait,
  224. (atomic_read(&sdp->detaching) ||
  225. !sdp->open_cnt));
  226. mutex_lock(&sdp->open_rel_lock);
  227. if (retval) /* -ERESTARTSYS */
  228. return retval;
  229. if (atomic_read(&sdp->detaching))
  230. return -ENODEV;
  231. }
  232. } else {
  233. while (sdp->exclude) {
  234. mutex_unlock(&sdp->open_rel_lock);
  235. retval = wait_event_interruptible(sdp->open_wait,
  236. (atomic_read(&sdp->detaching) ||
  237. !sdp->exclude));
  238. mutex_lock(&sdp->open_rel_lock);
  239. if (retval) /* -ERESTARTSYS */
  240. return retval;
  241. if (atomic_read(&sdp->detaching))
  242. return -ENODEV;
  243. }
  244. }
  245. return retval;
  246. }
  247. /* Returns 0 on success, else a negated errno value */
  248. static int
  249. sg_open(struct inode *inode, struct file *filp)
  250. {
  251. int dev = iminor(inode);
  252. int flags = filp->f_flags;
  253. struct request_queue *q;
  254. Sg_device *sdp;
  255. Sg_fd *sfp;
  256. int retval;
  257. nonseekable_open(inode, filp);
  258. if ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE)))
  259. return -EPERM; /* Can't lock it with read only access */
  260. sdp = sg_get_dev(dev);
  261. if (IS_ERR(sdp))
  262. return PTR_ERR(sdp);
  263. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  264. "sg_open: flags=0x%x\n", flags));
  265. /* This driver's module count bumped by fops_get in <linux/fs.h> */
  266. /* Prevent the device driver from vanishing while we sleep */
  267. retval = scsi_device_get(sdp->device);
  268. if (retval)
  269. goto sg_put;
  270. retval = scsi_autopm_get_device(sdp->device);
  271. if (retval)
  272. goto sdp_put;
  273. /* scsi_block_when_processing_errors() may block so bypass
  274. * check if O_NONBLOCK. Permits SCSI commands to be issued
  275. * during error recovery. Tread carefully. */
  276. if (!((flags & O_NONBLOCK) ||
  277. scsi_block_when_processing_errors(sdp->device))) {
  278. retval = -ENXIO;
  279. /* we are in error recovery for this device */
  280. goto error_out;
  281. }
  282. mutex_lock(&sdp->open_rel_lock);
  283. if (flags & O_NONBLOCK) {
  284. if (flags & O_EXCL) {
  285. if (sdp->open_cnt > 0) {
  286. retval = -EBUSY;
  287. goto error_mutex_locked;
  288. }
  289. } else {
  290. if (sdp->exclude) {
  291. retval = -EBUSY;
  292. goto error_mutex_locked;
  293. }
  294. }
  295. } else {
  296. retval = open_wait(sdp, flags);
  297. if (retval) /* -ERESTARTSYS or -ENODEV */
  298. goto error_mutex_locked;
  299. }
  300. /* N.B. at this point we are holding the open_rel_lock */
  301. if (flags & O_EXCL)
  302. sdp->exclude = true;
  303. if (sdp->open_cnt < 1) { /* no existing opens */
  304. sdp->sgdebug = 0;
  305. q = sdp->device->request_queue;
  306. sdp->sg_tablesize = queue_max_segments(q);
  307. }
  308. sfp = sg_add_sfp(sdp);
  309. if (IS_ERR(sfp)) {
  310. retval = PTR_ERR(sfp);
  311. goto out_undo;
  312. }
  313. filp->private_data = sfp;
  314. sdp->open_cnt++;
  315. mutex_unlock(&sdp->open_rel_lock);
  316. retval = 0;
  317. sg_put:
  318. kref_put(&sdp->d_ref, sg_device_destroy);
  319. return retval;
  320. out_undo:
  321. if (flags & O_EXCL) {
  322. sdp->exclude = false; /* undo if error */
  323. wake_up_interruptible(&sdp->open_wait);
  324. }
  325. error_mutex_locked:
  326. mutex_unlock(&sdp->open_rel_lock);
  327. error_out:
  328. scsi_autopm_put_device(sdp->device);
  329. sdp_put:
  330. scsi_device_put(sdp->device);
  331. goto sg_put;
  332. }
  333. /* Release resources associated with a successful sg_open()
  334. * Returns 0 on success, else a negated errno value */
  335. static int
  336. sg_release(struct inode *inode, struct file *filp)
  337. {
  338. Sg_device *sdp;
  339. Sg_fd *sfp;
  340. if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
  341. return -ENXIO;
  342. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_release\n"));
  343. mutex_lock(&sdp->open_rel_lock);
  344. scsi_autopm_put_device(sdp->device);
  345. kref_put(&sfp->f_ref, sg_remove_sfp);
  346. sdp->open_cnt--;
  347. /* possibly many open()s waiting on exlude clearing, start many;
  348. * only open(O_EXCL)s wait on 0==open_cnt so only start one */
  349. if (sdp->exclude) {
  350. sdp->exclude = false;
  351. wake_up_interruptible_all(&sdp->open_wait);
  352. } else if (0 == sdp->open_cnt) {
  353. wake_up_interruptible(&sdp->open_wait);
  354. }
  355. mutex_unlock(&sdp->open_rel_lock);
  356. return 0;
  357. }
  358. static int get_sg_io_pack_id(int *pack_id, void __user *buf, size_t count)
  359. {
  360. struct sg_header __user *old_hdr = buf;
  361. int reply_len;
  362. if (count >= SZ_SG_HEADER) {
  363. /* negative reply_len means v3 format, otherwise v1/v2 */
  364. if (get_user(reply_len, &old_hdr->reply_len))
  365. return -EFAULT;
  366. if (reply_len >= 0)
  367. return get_user(*pack_id, &old_hdr->pack_id);
  368. if (in_compat_syscall() &&
  369. count >= sizeof(struct compat_sg_io_hdr)) {
  370. struct compat_sg_io_hdr __user *hp = buf;
  371. return get_user(*pack_id, &hp->pack_id);
  372. }
  373. if (count >= sizeof(struct sg_io_hdr)) {
  374. struct sg_io_hdr __user *hp = buf;
  375. return get_user(*pack_id, &hp->pack_id);
  376. }
  377. }
  378. /* no valid header was passed, so ignore the pack_id */
  379. *pack_id = -1;
  380. return 0;
  381. }
  382. static ssize_t
  383. sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
  384. {
  385. Sg_device *sdp;
  386. Sg_fd *sfp;
  387. Sg_request *srp;
  388. int req_pack_id = -1;
  389. bool busy;
  390. sg_io_hdr_t *hp;
  391. struct sg_header *old_hdr;
  392. int retval;
  393. /*
  394. * This could cause a response to be stranded. Close the associated
  395. * file descriptor to free up any resources being held.
  396. */
  397. retval = sg_check_file_access(filp, __func__);
  398. if (retval)
  399. return retval;
  400. if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
  401. return -ENXIO;
  402. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  403. "sg_read: count=%d\n", (int) count));
  404. if (sfp->force_packid)
  405. retval = get_sg_io_pack_id(&req_pack_id, buf, count);
  406. if (retval)
  407. return retval;
  408. srp = sg_get_rq_mark(sfp, req_pack_id, &busy);
  409. if (!srp) { /* now wait on packet to arrive */
  410. if (filp->f_flags & O_NONBLOCK)
  411. return -EAGAIN;
  412. retval = wait_event_interruptible(sfp->read_wait,
  413. ((srp = sg_get_rq_mark(sfp, req_pack_id, &busy)) ||
  414. (!busy && atomic_read(&sdp->detaching))));
  415. if (!srp)
  416. /* signal or detaching */
  417. return retval ? retval : -ENODEV;
  418. }
  419. if (srp->header.interface_id != '\0')
  420. return sg_new_read(sfp, buf, count, srp);
  421. hp = &srp->header;
  422. old_hdr = kzalloc(SZ_SG_HEADER, GFP_KERNEL);
  423. if (!old_hdr)
  424. return -ENOMEM;
  425. old_hdr->reply_len = (int) hp->timeout;
  426. old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */
  427. old_hdr->pack_id = hp->pack_id;
  428. old_hdr->twelve_byte =
  429. ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
  430. old_hdr->target_status = hp->masked_status;
  431. old_hdr->host_status = hp->host_status;
  432. old_hdr->driver_status = hp->driver_status;
  433. if ((CHECK_CONDITION & hp->masked_status) ||
  434. (srp->sense_b[0] & 0x70) == 0x70) {
  435. old_hdr->driver_status = DRIVER_SENSE;
  436. memcpy(old_hdr->sense_buffer, srp->sense_b,
  437. sizeof (old_hdr->sense_buffer));
  438. }
  439. switch (hp->host_status) {
  440. /* This setup of 'result' is for backward compatibility and is best
  441. ignored by the user who should use target, host + driver status */
  442. case DID_OK:
  443. case DID_PASSTHROUGH:
  444. case DID_SOFT_ERROR:
  445. old_hdr->result = 0;
  446. break;
  447. case DID_NO_CONNECT:
  448. case DID_BUS_BUSY:
  449. case DID_TIME_OUT:
  450. old_hdr->result = EBUSY;
  451. break;
  452. case DID_BAD_TARGET:
  453. case DID_ABORT:
  454. case DID_PARITY:
  455. case DID_RESET:
  456. case DID_BAD_INTR:
  457. old_hdr->result = EIO;
  458. break;
  459. case DID_ERROR:
  460. old_hdr->result = (srp->sense_b[0] == 0 &&
  461. hp->masked_status == GOOD) ? 0 : EIO;
  462. break;
  463. default:
  464. old_hdr->result = EIO;
  465. break;
  466. }
  467. /* Now copy the result back to the user buffer. */
  468. if (count >= SZ_SG_HEADER) {
  469. if (copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {
  470. retval = -EFAULT;
  471. goto free_old_hdr;
  472. }
  473. buf += SZ_SG_HEADER;
  474. if (count > old_hdr->reply_len)
  475. count = old_hdr->reply_len;
  476. if (count > SZ_SG_HEADER) {
  477. if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {
  478. retval = -EFAULT;
  479. goto free_old_hdr;
  480. }
  481. }
  482. } else
  483. count = (old_hdr->result == 0) ? 0 : -EIO;
  484. sg_finish_rem_req(srp);
  485. sg_remove_request(sfp, srp);
  486. retval = count;
  487. free_old_hdr:
  488. kfree(old_hdr);
  489. return retval;
  490. }
  491. static ssize_t
  492. sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp)
  493. {
  494. sg_io_hdr_t *hp = &srp->header;
  495. int err = 0, err2;
  496. int len;
  497. if (in_compat_syscall()) {
  498. if (count < sizeof(struct compat_sg_io_hdr)) {
  499. err = -EINVAL;
  500. goto err_out;
  501. }
  502. } else if (count < SZ_SG_IO_HDR) {
  503. err = -EINVAL;
  504. goto err_out;
  505. }
  506. hp->sb_len_wr = 0;
  507. if ((hp->mx_sb_len > 0) && hp->sbp) {
  508. if ((CHECK_CONDITION & hp->masked_status) ||
  509. (srp->sense_b[0] & 0x70) == 0x70) {
  510. int sb_len = SCSI_SENSE_BUFFERSIZE;
  511. sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;
  512. len = 8 + (int) srp->sense_b[7]; /* Additional sense length field */
  513. len = (len > sb_len) ? sb_len : len;
  514. if (copy_to_user(hp->sbp, srp->sense_b, len)) {
  515. err = -EFAULT;
  516. goto err_out;
  517. }
  518. hp->driver_status = DRIVER_SENSE;
  519. hp->sb_len_wr = len;
  520. }
  521. }
  522. if (hp->masked_status || hp->host_status || hp->driver_status)
  523. hp->info |= SG_INFO_CHECK;
  524. err = put_sg_io_hdr(hp, buf);
  525. err_out:
  526. err2 = sg_finish_rem_req(srp);
  527. sg_remove_request(sfp, srp);
  528. return err ? : err2 ? : count;
  529. }
  530. static ssize_t
  531. sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
  532. {
  533. int mxsize, cmd_size, k;
  534. int input_size, blocking;
  535. unsigned char opcode;
  536. Sg_device *sdp;
  537. Sg_fd *sfp;
  538. Sg_request *srp;
  539. struct sg_header old_hdr;
  540. sg_io_hdr_t *hp;
  541. unsigned char cmnd[SG_MAX_CDB_SIZE];
  542. int retval;
  543. retval = sg_check_file_access(filp, __func__);
  544. if (retval)
  545. return retval;
  546. if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
  547. return -ENXIO;
  548. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  549. "sg_write: count=%d\n", (int) count));
  550. if (atomic_read(&sdp->detaching))
  551. return -ENODEV;
  552. if (!((filp->f_flags & O_NONBLOCK) ||
  553. scsi_block_when_processing_errors(sdp->device)))
  554. return -ENXIO;
  555. if (count < SZ_SG_HEADER)
  556. return -EIO;
  557. if (copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
  558. return -EFAULT;
  559. blocking = !(filp->f_flags & O_NONBLOCK);
  560. if (old_hdr.reply_len < 0)
  561. return sg_new_write(sfp, filp, buf, count,
  562. blocking, 0, 0, NULL);
  563. if (count < (SZ_SG_HEADER + 6))
  564. return -EIO; /* The minimum scsi command length is 6 bytes. */
  565. buf += SZ_SG_HEADER;
  566. if (get_user(opcode, buf))
  567. return -EFAULT;
  568. if (!(srp = sg_add_request(sfp))) {
  569. SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,
  570. "sg_write: queue full\n"));
  571. return -EDOM;
  572. }
  573. mutex_lock(&sfp->f_mutex);
  574. if (sfp->next_cmd_len > 0) {
  575. cmd_size = sfp->next_cmd_len;
  576. sfp->next_cmd_len = 0; /* reset so only this write() effected */
  577. } else {
  578. cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
  579. if ((opcode >= 0xc0) && old_hdr.twelve_byte)
  580. cmd_size = 12;
  581. }
  582. mutex_unlock(&sfp->f_mutex);
  583. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
  584. "sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
  585. /* Determine buffer size. */
  586. input_size = count - cmd_size;
  587. mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
  588. mxsize -= SZ_SG_HEADER;
  589. input_size -= SZ_SG_HEADER;
  590. if (input_size < 0) {
  591. sg_remove_request(sfp, srp);
  592. return -EIO; /* User did not pass enough bytes for this command. */
  593. }
  594. hp = &srp->header;
  595. hp->interface_id = '\0'; /* indicator of old interface tunnelled */
  596. hp->cmd_len = (unsigned char) cmd_size;
  597. hp->iovec_count = 0;
  598. hp->mx_sb_len = 0;
  599. if (input_size > 0)
  600. hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
  601. SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
  602. else
  603. hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
  604. hp->dxfer_len = mxsize;
  605. if ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||
  606. (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))
  607. hp->dxferp = (char __user *)buf + cmd_size;
  608. else
  609. hp->dxferp = NULL;
  610. hp->sbp = NULL;
  611. hp->timeout = old_hdr.reply_len; /* structure abuse ... */
  612. hp->flags = input_size; /* structure abuse ... */
  613. hp->pack_id = old_hdr.pack_id;
  614. hp->usr_ptr = NULL;
  615. if (copy_from_user(cmnd, buf, cmd_size)) {
  616. sg_remove_request(sfp, srp);
  617. return -EFAULT;
  618. }
  619. /*
  620. * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
  621. * but is is possible that the app intended SG_DXFER_TO_DEV, because there
  622. * is a non-zero input_size, so emit a warning.
  623. */
  624. if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {
  625. printk_ratelimited(KERN_WARNING
  626. "sg_write: data in/out %d/%d bytes "
  627. "for SCSI command 0x%x-- guessing "
  628. "data in;\n program %s not setting "
  629. "count and/or reply_len properly\n",
  630. old_hdr.reply_len - (int)SZ_SG_HEADER,
  631. input_size, (unsigned int) cmnd[0],
  632. current->comm);
  633. }
  634. k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
  635. return (k < 0) ? k : count;
  636. }
  637. static ssize_t
  638. sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf,
  639. size_t count, int blocking, int read_only, int sg_io_owned,
  640. Sg_request **o_srp)
  641. {
  642. int k;
  643. Sg_request *srp;
  644. sg_io_hdr_t *hp;
  645. unsigned char cmnd[SG_MAX_CDB_SIZE];
  646. int timeout;
  647. unsigned long ul_timeout;
  648. if (count < SZ_SG_IO_HDR)
  649. return -EINVAL;
  650. sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */
  651. if (!(srp = sg_add_request(sfp))) {
  652. SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
  653. "sg_new_write: queue full\n"));
  654. return -EDOM;
  655. }
  656. srp->sg_io_owned = sg_io_owned;
  657. hp = &srp->header;
  658. if (get_sg_io_hdr(hp, buf)) {
  659. sg_remove_request(sfp, srp);
  660. return -EFAULT;
  661. }
  662. if (hp->interface_id != 'S') {
  663. sg_remove_request(sfp, srp);
  664. return -ENOSYS;
  665. }
  666. if (hp->flags & SG_FLAG_MMAP_IO) {
  667. if (hp->dxfer_len > sfp->reserve.bufflen) {
  668. sg_remove_request(sfp, srp);
  669. return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */
  670. }
  671. if (hp->flags & SG_FLAG_DIRECT_IO) {
  672. sg_remove_request(sfp, srp);
  673. return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */
  674. }
  675. if (sfp->res_in_use) {
  676. sg_remove_request(sfp, srp);
  677. return -EBUSY; /* reserve buffer already being used */
  678. }
  679. }
  680. ul_timeout = msecs_to_jiffies(srp->header.timeout);
  681. timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX;
  682. if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {
  683. sg_remove_request(sfp, srp);
  684. return -EMSGSIZE;
  685. }
  686. if (copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) {
  687. sg_remove_request(sfp, srp);
  688. return -EFAULT;
  689. }
  690. if (read_only && sg_allow_access(file, cmnd)) {
  691. sg_remove_request(sfp, srp);
  692. return -EPERM;
  693. }
  694. k = sg_common_write(sfp, srp, cmnd, timeout, blocking);
  695. if (k < 0)
  696. return k;
  697. if (o_srp)
  698. *o_srp = srp;
  699. return count;
  700. }
  701. static int
  702. sg_common_write(Sg_fd * sfp, Sg_request * srp,
  703. unsigned char *cmnd, int timeout, int blocking)
  704. {
  705. int k, at_head;
  706. Sg_device *sdp = sfp->parentdp;
  707. sg_io_hdr_t *hp = &srp->header;
  708. srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
  709. hp->status = 0;
  710. hp->masked_status = 0;
  711. hp->msg_status = 0;
  712. hp->info = 0;
  713. hp->host_status = 0;
  714. hp->driver_status = 0;
  715. hp->resid = 0;
  716. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  717. "sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n",
  718. (int) cmnd[0], (int) hp->cmd_len));
  719. if (hp->dxfer_len >= SZ_256M) {
  720. sg_remove_request(sfp, srp);
  721. return -EINVAL;
  722. }
  723. k = sg_start_req(srp, cmnd);
  724. if (k) {
  725. SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
  726. "sg_common_write: start_req err=%d\n", k));
  727. sg_finish_rem_req(srp);
  728. sg_remove_request(sfp, srp);
  729. return k; /* probably out of space --> ENOMEM */
  730. }
  731. if (atomic_read(&sdp->detaching)) {
  732. if (srp->bio) {
  733. blk_mq_free_request(srp->rq);
  734. srp->rq = NULL;
  735. }
  736. sg_finish_rem_req(srp);
  737. sg_remove_request(sfp, srp);
  738. return -ENODEV;
  739. }
  740. hp->duration = jiffies_to_msecs(jiffies);
  741. if (hp->interface_id != '\0' && /* v3 (or later) interface */
  742. (SG_FLAG_Q_AT_TAIL & hp->flags))
  743. at_head = 0;
  744. else
  745. at_head = 1;
  746. srp->rq->timeout = timeout;
  747. kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */
  748. srp->rq->end_io = sg_rq_end_io;
  749. blk_execute_rq_nowait(srp->rq, at_head);
  750. return 0;
  751. }
  752. static int srp_done(Sg_fd *sfp, Sg_request *srp)
  753. {
  754. unsigned long flags;
  755. int ret;
  756. read_lock_irqsave(&sfp->rq_list_lock, flags);
  757. ret = srp->done;
  758. read_unlock_irqrestore(&sfp->rq_list_lock, flags);
  759. return ret;
  760. }
  761. static int max_sectors_bytes(struct request_queue *q)
  762. {
  763. unsigned int max_sectors = queue_max_sectors(q);
  764. max_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9);
  765. return max_sectors << 9;
  766. }
  767. static void
  768. sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo)
  769. {
  770. Sg_request *srp;
  771. int val;
  772. unsigned int ms;
  773. val = 0;
  774. list_for_each_entry(srp, &sfp->rq_list, entry) {
  775. if (val >= SG_MAX_QUEUE)
  776. break;
  777. rinfo[val].req_state = srp->done + 1;
  778. rinfo[val].problem =
  779. srp->header.masked_status &
  780. srp->header.host_status &
  781. srp->header.driver_status;
  782. if (srp->done)
  783. rinfo[val].duration =
  784. srp->header.duration;
  785. else {
  786. ms = jiffies_to_msecs(jiffies);
  787. rinfo[val].duration =
  788. (ms > srp->header.duration) ?
  789. (ms - srp->header.duration) : 0;
  790. }
  791. rinfo[val].orphan = srp->orphan;
  792. rinfo[val].sg_io_owned = srp->sg_io_owned;
  793. rinfo[val].pack_id = srp->header.pack_id;
  794. rinfo[val].usr_ptr = srp->header.usr_ptr;
  795. val++;
  796. }
  797. }
  798. #ifdef CONFIG_COMPAT
  799. struct compat_sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
  800. char req_state;
  801. char orphan;
  802. char sg_io_owned;
  803. char problem;
  804. int pack_id;
  805. compat_uptr_t usr_ptr;
  806. unsigned int duration;
  807. int unused;
  808. };
  809. static int put_compat_request_table(struct compat_sg_req_info __user *o,
  810. struct sg_req_info *rinfo)
  811. {
  812. int i;
  813. for (i = 0; i < SG_MAX_QUEUE; i++) {
  814. if (copy_to_user(o + i, rinfo + i, offsetof(sg_req_info_t, usr_ptr)) ||
  815. put_user((uintptr_t)rinfo[i].usr_ptr, &o[i].usr_ptr) ||
  816. put_user(rinfo[i].duration, &o[i].duration) ||
  817. put_user(rinfo[i].unused, &o[i].unused))
  818. return -EFAULT;
  819. }
  820. return 0;
  821. }
  822. #endif
  823. static long
  824. sg_ioctl_common(struct file *filp, Sg_device *sdp, Sg_fd *sfp,
  825. unsigned int cmd_in, void __user *p)
  826. {
  827. int __user *ip = p;
  828. int result, val, read_only;
  829. Sg_request *srp;
  830. unsigned long iflags;
  831. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  832. "sg_ioctl: cmd=0x%x\n", (int) cmd_in));
  833. read_only = (O_RDWR != (filp->f_flags & O_ACCMODE));
  834. switch (cmd_in) {
  835. case SG_IO:
  836. if (atomic_read(&sdp->detaching))
  837. return -ENODEV;
  838. if (!scsi_block_when_processing_errors(sdp->device))
  839. return -ENXIO;
  840. result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR,
  841. 1, read_only, 1, &srp);
  842. if (result < 0)
  843. return result;
  844. result = wait_event_interruptible(sfp->read_wait,
  845. srp_done(sfp, srp));
  846. write_lock_irq(&sfp->rq_list_lock);
  847. if (srp->done) {
  848. srp->done = 2;
  849. write_unlock_irq(&sfp->rq_list_lock);
  850. result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);
  851. return (result < 0) ? result : 0;
  852. }
  853. srp->orphan = 1;
  854. write_unlock_irq(&sfp->rq_list_lock);
  855. return result; /* -ERESTARTSYS because signal hit process */
  856. case SG_SET_TIMEOUT:
  857. result = get_user(val, ip);
  858. if (result)
  859. return result;
  860. if (val < 0)
  861. return -EIO;
  862. if (val >= mult_frac((s64)INT_MAX, USER_HZ, HZ))
  863. val = min_t(s64, mult_frac((s64)INT_MAX, USER_HZ, HZ),
  864. INT_MAX);
  865. sfp->timeout_user = val;
  866. sfp->timeout = mult_frac(val, HZ, USER_HZ);
  867. return 0;
  868. case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */
  869. /* strange ..., for backward compatibility */
  870. return sfp->timeout_user;
  871. case SG_SET_FORCE_LOW_DMA:
  872. /*
  873. * N.B. This ioctl never worked properly, but failed to
  874. * return an error value. So returning '0' to keep compability
  875. * with legacy applications.
  876. */
  877. return 0;
  878. case SG_GET_LOW_DMA:
  879. return put_user(0, ip);
  880. case SG_GET_SCSI_ID:
  881. {
  882. sg_scsi_id_t v;
  883. if (atomic_read(&sdp->detaching))
  884. return -ENODEV;
  885. memset(&v, 0, sizeof(v));
  886. v.host_no = sdp->device->host->host_no;
  887. v.channel = sdp->device->channel;
  888. v.scsi_id = sdp->device->id;
  889. v.lun = sdp->device->lun;
  890. v.scsi_type = sdp->device->type;
  891. v.h_cmd_per_lun = sdp->device->host->cmd_per_lun;
  892. v.d_queue_depth = sdp->device->queue_depth;
  893. if (copy_to_user(p, &v, sizeof(sg_scsi_id_t)))
  894. return -EFAULT;
  895. return 0;
  896. }
  897. case SG_SET_FORCE_PACK_ID:
  898. result = get_user(val, ip);
  899. if (result)
  900. return result;
  901. sfp->force_packid = val ? 1 : 0;
  902. return 0;
  903. case SG_GET_PACK_ID:
  904. read_lock_irqsave(&sfp->rq_list_lock, iflags);
  905. list_for_each_entry(srp, &sfp->rq_list, entry) {
  906. if ((1 == srp->done) && (!srp->sg_io_owned)) {
  907. read_unlock_irqrestore(&sfp->rq_list_lock,
  908. iflags);
  909. return put_user(srp->header.pack_id, ip);
  910. }
  911. }
  912. read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  913. return put_user(-1, ip);
  914. case SG_GET_NUM_WAITING:
  915. read_lock_irqsave(&sfp->rq_list_lock, iflags);
  916. val = 0;
  917. list_for_each_entry(srp, &sfp->rq_list, entry) {
  918. if ((1 == srp->done) && (!srp->sg_io_owned))
  919. ++val;
  920. }
  921. read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  922. return put_user(val, ip);
  923. case SG_GET_SG_TABLESIZE:
  924. return put_user(sdp->sg_tablesize, ip);
  925. case SG_SET_RESERVED_SIZE:
  926. result = get_user(val, ip);
  927. if (result)
  928. return result;
  929. if (val < 0)
  930. return -EINVAL;
  931. val = min_t(int, val,
  932. max_sectors_bytes(sdp->device->request_queue));
  933. mutex_lock(&sfp->f_mutex);
  934. if (val != sfp->reserve.bufflen) {
  935. if (sfp->mmap_called ||
  936. sfp->res_in_use) {
  937. mutex_unlock(&sfp->f_mutex);
  938. return -EBUSY;
  939. }
  940. sg_remove_scat(sfp, &sfp->reserve);
  941. sg_build_reserve(sfp, val);
  942. }
  943. mutex_unlock(&sfp->f_mutex);
  944. return 0;
  945. case SG_GET_RESERVED_SIZE:
  946. val = min_t(int, sfp->reserve.bufflen,
  947. max_sectors_bytes(sdp->device->request_queue));
  948. return put_user(val, ip);
  949. case SG_SET_COMMAND_Q:
  950. result = get_user(val, ip);
  951. if (result)
  952. return result;
  953. sfp->cmd_q = val ? 1 : 0;
  954. return 0;
  955. case SG_GET_COMMAND_Q:
  956. return put_user((int) sfp->cmd_q, ip);
  957. case SG_SET_KEEP_ORPHAN:
  958. result = get_user(val, ip);
  959. if (result)
  960. return result;
  961. sfp->keep_orphan = val;
  962. return 0;
  963. case SG_GET_KEEP_ORPHAN:
  964. return put_user((int) sfp->keep_orphan, ip);
  965. case SG_NEXT_CMD_LEN:
  966. result = get_user(val, ip);
  967. if (result)
  968. return result;
  969. if (val > SG_MAX_CDB_SIZE)
  970. return -ENOMEM;
  971. sfp->next_cmd_len = (val > 0) ? val : 0;
  972. return 0;
  973. case SG_GET_VERSION_NUM:
  974. return put_user(sg_version_num, ip);
  975. case SG_GET_ACCESS_COUNT:
  976. /* faked - we don't have a real access count anymore */
  977. val = (sdp->device ? 1 : 0);
  978. return put_user(val, ip);
  979. case SG_GET_REQUEST_TABLE:
  980. {
  981. sg_req_info_t *rinfo;
  982. rinfo = kcalloc(SG_MAX_QUEUE, SZ_SG_REQ_INFO,
  983. GFP_KERNEL);
  984. if (!rinfo)
  985. return -ENOMEM;
  986. read_lock_irqsave(&sfp->rq_list_lock, iflags);
  987. sg_fill_request_table(sfp, rinfo);
  988. read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  989. #ifdef CONFIG_COMPAT
  990. if (in_compat_syscall())
  991. result = put_compat_request_table(p, rinfo);
  992. else
  993. #endif
  994. result = copy_to_user(p, rinfo,
  995. SZ_SG_REQ_INFO * SG_MAX_QUEUE);
  996. result = result ? -EFAULT : 0;
  997. kfree(rinfo);
  998. return result;
  999. }
  1000. case SG_EMULATED_HOST:
  1001. if (atomic_read(&sdp->detaching))
  1002. return -ENODEV;
  1003. return put_user(sdp->device->host->hostt->emulated, ip);
  1004. case SCSI_IOCTL_SEND_COMMAND:
  1005. if (atomic_read(&sdp->detaching))
  1006. return -ENODEV;
  1007. return scsi_ioctl(sdp->device, filp->f_mode, cmd_in, p);
  1008. case SG_SET_DEBUG:
  1009. result = get_user(val, ip);
  1010. if (result)
  1011. return result;
  1012. sdp->sgdebug = (char) val;
  1013. return 0;
  1014. case BLKSECTGET:
  1015. return put_user(max_sectors_bytes(sdp->device->request_queue),
  1016. ip);
  1017. case BLKTRACESETUP:
  1018. return blk_trace_setup(sdp->device->request_queue, sdp->name,
  1019. MKDEV(SCSI_GENERIC_MAJOR, sdp->index),
  1020. NULL, p);
  1021. case BLKTRACESTART:
  1022. return blk_trace_startstop(sdp->device->request_queue, 1);
  1023. case BLKTRACESTOP:
  1024. return blk_trace_startstop(sdp->device->request_queue, 0);
  1025. case BLKTRACETEARDOWN:
  1026. return blk_trace_remove(sdp->device->request_queue);
  1027. case SCSI_IOCTL_GET_IDLUN:
  1028. case SCSI_IOCTL_GET_BUS_NUMBER:
  1029. case SCSI_IOCTL_PROBE_HOST:
  1030. case SG_GET_TRANSFORM:
  1031. case SG_SCSI_RESET:
  1032. if (atomic_read(&sdp->detaching))
  1033. return -ENODEV;
  1034. break;
  1035. default:
  1036. if (read_only)
  1037. return -EPERM; /* don't know so take safe approach */
  1038. break;
  1039. }
  1040. result = scsi_ioctl_block_when_processing_errors(sdp->device,
  1041. cmd_in, filp->f_flags & O_NDELAY);
  1042. if (result)
  1043. return result;
  1044. return -ENOIOCTLCMD;
  1045. }
  1046. static long
  1047. sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)
  1048. {
  1049. void __user *p = (void __user *)arg;
  1050. Sg_device *sdp;
  1051. Sg_fd *sfp;
  1052. int ret;
  1053. if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
  1054. return -ENXIO;
  1055. ret = sg_ioctl_common(filp, sdp, sfp, cmd_in, p);
  1056. if (ret != -ENOIOCTLCMD)
  1057. return ret;
  1058. return scsi_ioctl(sdp->device, filp->f_mode, cmd_in, p);
  1059. }
  1060. static __poll_t
  1061. sg_poll(struct file *filp, poll_table * wait)
  1062. {
  1063. __poll_t res = 0;
  1064. Sg_device *sdp;
  1065. Sg_fd *sfp;
  1066. Sg_request *srp;
  1067. int count = 0;
  1068. unsigned long iflags;
  1069. sfp = filp->private_data;
  1070. if (!sfp)
  1071. return EPOLLERR;
  1072. sdp = sfp->parentdp;
  1073. if (!sdp)
  1074. return EPOLLERR;
  1075. poll_wait(filp, &sfp->read_wait, wait);
  1076. read_lock_irqsave(&sfp->rq_list_lock, iflags);
  1077. list_for_each_entry(srp, &sfp->rq_list, entry) {
  1078. /* if any read waiting, flag it */
  1079. if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned))
  1080. res = EPOLLIN | EPOLLRDNORM;
  1081. ++count;
  1082. }
  1083. read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1084. if (atomic_read(&sdp->detaching))
  1085. res |= EPOLLHUP;
  1086. else if (!sfp->cmd_q) {
  1087. if (0 == count)
  1088. res |= EPOLLOUT | EPOLLWRNORM;
  1089. } else if (count < SG_MAX_QUEUE)
  1090. res |= EPOLLOUT | EPOLLWRNORM;
  1091. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  1092. "sg_poll: res=0x%x\n", (__force u32) res));
  1093. return res;
  1094. }
  1095. static int
  1096. sg_fasync(int fd, struct file *filp, int mode)
  1097. {
  1098. Sg_device *sdp;
  1099. Sg_fd *sfp;
  1100. if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
  1101. return -ENXIO;
  1102. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  1103. "sg_fasync: mode=%d\n", mode));
  1104. return fasync_helper(fd, filp, mode, &sfp->async_qp);
  1105. }
  1106. static vm_fault_t
  1107. sg_vma_fault(struct vm_fault *vmf)
  1108. {
  1109. struct vm_area_struct *vma = vmf->vma;
  1110. Sg_fd *sfp;
  1111. unsigned long offset, len, sa;
  1112. Sg_scatter_hold *rsv_schp;
  1113. int k, length;
  1114. if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
  1115. return VM_FAULT_SIGBUS;
  1116. rsv_schp = &sfp->reserve;
  1117. offset = vmf->pgoff << PAGE_SHIFT;
  1118. if (offset >= rsv_schp->bufflen)
  1119. return VM_FAULT_SIGBUS;
  1120. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
  1121. "sg_vma_fault: offset=%lu, scatg=%d\n",
  1122. offset, rsv_schp->k_use_sg));
  1123. sa = vma->vm_start;
  1124. length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
  1125. for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
  1126. len = vma->vm_end - sa;
  1127. len = (len < length) ? len : length;
  1128. if (offset < len) {
  1129. struct page *page = nth_page(rsv_schp->pages[k],
  1130. offset >> PAGE_SHIFT);
  1131. get_page(page); /* increment page count */
  1132. vmf->page = page;
  1133. return 0; /* success */
  1134. }
  1135. sa += len;
  1136. offset -= len;
  1137. }
  1138. return VM_FAULT_SIGBUS;
  1139. }
  1140. static const struct vm_operations_struct sg_mmap_vm_ops = {
  1141. .fault = sg_vma_fault,
  1142. };
  1143. static int
  1144. sg_mmap(struct file *filp, struct vm_area_struct *vma)
  1145. {
  1146. Sg_fd *sfp;
  1147. unsigned long req_sz, len, sa;
  1148. Sg_scatter_hold *rsv_schp;
  1149. int k, length;
  1150. int ret = 0;
  1151. if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
  1152. return -ENXIO;
  1153. req_sz = vma->vm_end - vma->vm_start;
  1154. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
  1155. "sg_mmap starting, vm_start=%p, len=%d\n",
  1156. (void *) vma->vm_start, (int) req_sz));
  1157. if (vma->vm_pgoff)
  1158. return -EINVAL; /* want no offset */
  1159. rsv_schp = &sfp->reserve;
  1160. mutex_lock(&sfp->f_mutex);
  1161. if (req_sz > rsv_schp->bufflen) {
  1162. ret = -ENOMEM; /* cannot map more than reserved buffer */
  1163. goto out;
  1164. }
  1165. sa = vma->vm_start;
  1166. length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
  1167. for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
  1168. len = vma->vm_end - sa;
  1169. len = (len < length) ? len : length;
  1170. sa += len;
  1171. }
  1172. sfp->mmap_called = 1;
  1173. vm_flags_set(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
  1174. vma->vm_private_data = sfp;
  1175. vma->vm_ops = &sg_mmap_vm_ops;
  1176. out:
  1177. mutex_unlock(&sfp->f_mutex);
  1178. return ret;
  1179. }
  1180. static void
  1181. sg_rq_end_io_usercontext(struct work_struct *work)
  1182. {
  1183. struct sg_request *srp = container_of(work, struct sg_request, ew.work);
  1184. struct sg_fd *sfp = srp->parentfp;
  1185. sg_finish_rem_req(srp);
  1186. sg_remove_request(sfp, srp);
  1187. kref_put(&sfp->f_ref, sg_remove_sfp);
  1188. }
  1189. /*
  1190. * This function is a "bottom half" handler that is called by the mid
  1191. * level when a command is completed (or has failed).
  1192. */
  1193. static enum rq_end_io_ret
  1194. sg_rq_end_io(struct request *rq, blk_status_t status)
  1195. {
  1196. struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(rq);
  1197. struct sg_request *srp = rq->end_io_data;
  1198. Sg_device *sdp;
  1199. Sg_fd *sfp;
  1200. unsigned long iflags;
  1201. unsigned int ms;
  1202. char *sense;
  1203. int result, resid, done = 1;
  1204. if (WARN_ON(srp->done != 0))
  1205. return RQ_END_IO_NONE;
  1206. sfp = srp->parentfp;
  1207. if (WARN_ON(sfp == NULL))
  1208. return RQ_END_IO_NONE;
  1209. sdp = sfp->parentdp;
  1210. if (unlikely(atomic_read(&sdp->detaching)))
  1211. pr_info("%s: device detaching\n", __func__);
  1212. sense = scmd->sense_buffer;
  1213. result = scmd->result;
  1214. resid = scmd->resid_len;
  1215. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
  1216. "sg_cmd_done: pack_id=%d, res=0x%x\n",
  1217. srp->header.pack_id, result));
  1218. srp->header.resid = resid;
  1219. ms = jiffies_to_msecs(jiffies);
  1220. srp->header.duration = (ms > srp->header.duration) ?
  1221. (ms - srp->header.duration) : 0;
  1222. if (0 != result) {
  1223. struct scsi_sense_hdr sshdr;
  1224. srp->header.status = 0xff & result;
  1225. srp->header.masked_status = status_byte(result);
  1226. srp->header.msg_status = COMMAND_COMPLETE;
  1227. srp->header.host_status = host_byte(result);
  1228. srp->header.driver_status = driver_byte(result);
  1229. if ((sdp->sgdebug > 0) &&
  1230. ((CHECK_CONDITION == srp->header.masked_status) ||
  1231. (COMMAND_TERMINATED == srp->header.masked_status)))
  1232. __scsi_print_sense(sdp->device, __func__, sense,
  1233. SCSI_SENSE_BUFFERSIZE);
  1234. /* Following if statement is a patch supplied by Eric Youngdale */
  1235. if (driver_byte(result) != 0
  1236. && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr)
  1237. && !scsi_sense_is_deferred(&sshdr)
  1238. && sshdr.sense_key == UNIT_ATTENTION
  1239. && sdp->device->removable) {
  1240. /* Detected possible disc change. Set the bit - this */
  1241. /* may be used if there are filesystems using this device */
  1242. sdp->device->changed = 1;
  1243. }
  1244. }
  1245. if (scmd->sense_len)
  1246. memcpy(srp->sense_b, scmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
  1247. /* Rely on write phase to clean out srp status values, so no "else" */
  1248. /*
  1249. * Free the request as soon as it is complete so that its resources
  1250. * can be reused without waiting for userspace to read() the
  1251. * result. But keep the associated bio (if any) around until
  1252. * blk_rq_unmap_user() can be called from user context.
  1253. */
  1254. srp->rq = NULL;
  1255. blk_mq_free_request(rq);
  1256. write_lock_irqsave(&sfp->rq_list_lock, iflags);
  1257. if (unlikely(srp->orphan)) {
  1258. if (sfp->keep_orphan)
  1259. srp->sg_io_owned = 0;
  1260. else
  1261. done = 0;
  1262. }
  1263. srp->done = done;
  1264. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1265. if (likely(done)) {
  1266. /* Now wake up any sg_read() that is waiting for this
  1267. * packet.
  1268. */
  1269. wake_up_interruptible(&sfp->read_wait);
  1270. kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);
  1271. kref_put(&sfp->f_ref, sg_remove_sfp);
  1272. } else {
  1273. INIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext);
  1274. schedule_work(&srp->ew.work);
  1275. }
  1276. return RQ_END_IO_NONE;
  1277. }
  1278. static const struct file_operations sg_fops = {
  1279. .owner = THIS_MODULE,
  1280. .read = sg_read,
  1281. .write = sg_write,
  1282. .poll = sg_poll,
  1283. .unlocked_ioctl = sg_ioctl,
  1284. .compat_ioctl = compat_ptr_ioctl,
  1285. .open = sg_open,
  1286. .mmap = sg_mmap,
  1287. .release = sg_release,
  1288. .fasync = sg_fasync,
  1289. .llseek = no_llseek,
  1290. };
  1291. static struct class *sg_sysfs_class;
  1292. static int sg_sysfs_valid = 0;
  1293. static Sg_device *
  1294. sg_alloc(struct scsi_device *scsidp)
  1295. {
  1296. struct request_queue *q = scsidp->request_queue;
  1297. Sg_device *sdp;
  1298. unsigned long iflags;
  1299. int error;
  1300. u32 k;
  1301. sdp = kzalloc(sizeof(Sg_device), GFP_KERNEL);
  1302. if (!sdp) {
  1303. sdev_printk(KERN_WARNING, scsidp, "%s: kmalloc Sg_device "
  1304. "failure\n", __func__);
  1305. return ERR_PTR(-ENOMEM);
  1306. }
  1307. idr_preload(GFP_KERNEL);
  1308. write_lock_irqsave(&sg_index_lock, iflags);
  1309. error = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT);
  1310. if (error < 0) {
  1311. if (error == -ENOSPC) {
  1312. sdev_printk(KERN_WARNING, scsidp,
  1313. "Unable to attach sg device type=%d, minor number exceeds %d\n",
  1314. scsidp->type, SG_MAX_DEVS - 1);
  1315. error = -ENODEV;
  1316. } else {
  1317. sdev_printk(KERN_WARNING, scsidp, "%s: idr "
  1318. "allocation Sg_device failure: %d\n",
  1319. __func__, error);
  1320. }
  1321. goto out_unlock;
  1322. }
  1323. k = error;
  1324. SCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp,
  1325. "sg_alloc: dev=%d \n", k));
  1326. sprintf(sdp->name, "sg%d", k);
  1327. sdp->device = scsidp;
  1328. mutex_init(&sdp->open_rel_lock);
  1329. INIT_LIST_HEAD(&sdp->sfds);
  1330. init_waitqueue_head(&sdp->open_wait);
  1331. atomic_set(&sdp->detaching, 0);
  1332. rwlock_init(&sdp->sfd_lock);
  1333. sdp->sg_tablesize = queue_max_segments(q);
  1334. sdp->index = k;
  1335. kref_init(&sdp->d_ref);
  1336. error = 0;
  1337. out_unlock:
  1338. write_unlock_irqrestore(&sg_index_lock, iflags);
  1339. idr_preload_end();
  1340. if (error) {
  1341. kfree(sdp);
  1342. return ERR_PTR(error);
  1343. }
  1344. return sdp;
  1345. }
  1346. static int
  1347. sg_add_device(struct device *cl_dev, struct class_interface *cl_intf)
  1348. {
  1349. struct scsi_device *scsidp = to_scsi_device(cl_dev->parent);
  1350. Sg_device *sdp = NULL;
  1351. struct cdev * cdev = NULL;
  1352. int error;
  1353. unsigned long iflags;
  1354. error = -ENOMEM;
  1355. cdev = cdev_alloc();
  1356. if (!cdev) {
  1357. pr_warn("%s: cdev_alloc failed\n", __func__);
  1358. goto out;
  1359. }
  1360. cdev->owner = THIS_MODULE;
  1361. cdev->ops = &sg_fops;
  1362. sdp = sg_alloc(scsidp);
  1363. if (IS_ERR(sdp)) {
  1364. pr_warn("%s: sg_alloc failed\n", __func__);
  1365. error = PTR_ERR(sdp);
  1366. goto out;
  1367. }
  1368. error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1);
  1369. if (error)
  1370. goto cdev_add_err;
  1371. sdp->cdev = cdev;
  1372. if (sg_sysfs_valid) {
  1373. struct device *sg_class_member;
  1374. sg_class_member = device_create(sg_sysfs_class, cl_dev->parent,
  1375. MKDEV(SCSI_GENERIC_MAJOR,
  1376. sdp->index),
  1377. sdp, "%s", sdp->name);
  1378. if (IS_ERR(sg_class_member)) {
  1379. pr_err("%s: device_create failed\n", __func__);
  1380. error = PTR_ERR(sg_class_member);
  1381. goto cdev_add_err;
  1382. }
  1383. error = sysfs_create_link(&scsidp->sdev_gendev.kobj,
  1384. &sg_class_member->kobj, "generic");
  1385. if (error)
  1386. pr_err("%s: unable to make symlink 'generic' back "
  1387. "to sg%d\n", __func__, sdp->index);
  1388. } else
  1389. pr_warn("%s: sg_sys Invalid\n", __func__);
  1390. sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d "
  1391. "type %d\n", sdp->index, scsidp->type);
  1392. dev_set_drvdata(cl_dev, sdp);
  1393. return 0;
  1394. cdev_add_err:
  1395. write_lock_irqsave(&sg_index_lock, iflags);
  1396. idr_remove(&sg_index_idr, sdp->index);
  1397. write_unlock_irqrestore(&sg_index_lock, iflags);
  1398. kfree(sdp);
  1399. out:
  1400. if (cdev)
  1401. cdev_del(cdev);
  1402. return error;
  1403. }
  1404. static void
  1405. sg_device_destroy(struct kref *kref)
  1406. {
  1407. struct sg_device *sdp = container_of(kref, struct sg_device, d_ref);
  1408. unsigned long flags;
  1409. /* CAUTION! Note that the device can still be found via idr_find()
  1410. * even though the refcount is 0. Therefore, do idr_remove() BEFORE
  1411. * any other cleanup.
  1412. */
  1413. write_lock_irqsave(&sg_index_lock, flags);
  1414. idr_remove(&sg_index_idr, sdp->index);
  1415. write_unlock_irqrestore(&sg_index_lock, flags);
  1416. SCSI_LOG_TIMEOUT(3,
  1417. sg_printk(KERN_INFO, sdp, "sg_device_destroy\n"));
  1418. kfree(sdp);
  1419. }
  1420. static void
  1421. sg_remove_device(struct device *cl_dev, struct class_interface *cl_intf)
  1422. {
  1423. struct scsi_device *scsidp = to_scsi_device(cl_dev->parent);
  1424. Sg_device *sdp = dev_get_drvdata(cl_dev);
  1425. unsigned long iflags;
  1426. Sg_fd *sfp;
  1427. int val;
  1428. if (!sdp)
  1429. return;
  1430. /* want sdp->detaching non-zero as soon as possible */
  1431. val = atomic_inc_return(&sdp->detaching);
  1432. if (val > 1)
  1433. return; /* only want to do following once per device */
  1434. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  1435. "%s\n", __func__));
  1436. read_lock_irqsave(&sdp->sfd_lock, iflags);
  1437. list_for_each_entry(sfp, &sdp->sfds, sfd_siblings) {
  1438. wake_up_interruptible_all(&sfp->read_wait);
  1439. kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP);
  1440. }
  1441. wake_up_interruptible_all(&sdp->open_wait);
  1442. read_unlock_irqrestore(&sdp->sfd_lock, iflags);
  1443. sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
  1444. device_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
  1445. cdev_del(sdp->cdev);
  1446. sdp->cdev = NULL;
  1447. kref_put(&sdp->d_ref, sg_device_destroy);
  1448. }
  1449. module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
  1450. module_param_named(def_reserved_size, def_reserved_size, int,
  1451. S_IRUGO | S_IWUSR);
  1452. module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
  1453. MODULE_AUTHOR("Douglas Gilbert");
  1454. MODULE_DESCRIPTION("SCSI generic (sg) driver");
  1455. MODULE_LICENSE("GPL");
  1456. MODULE_VERSION(SG_VERSION_STR);
  1457. MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
  1458. MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
  1459. "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
  1460. MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
  1461. MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
  1462. #ifdef CONFIG_SYSCTL
  1463. #include <linux/sysctl.h>
  1464. static struct ctl_table sg_sysctls[] = {
  1465. {
  1466. .procname = "sg-big-buff",
  1467. .data = &sg_big_buff,
  1468. .maxlen = sizeof(int),
  1469. .mode = 0444,
  1470. .proc_handler = proc_dointvec,
  1471. },
  1472. {}
  1473. };
  1474. static struct ctl_table_header *hdr;
  1475. static void register_sg_sysctls(void)
  1476. {
  1477. if (!hdr)
  1478. hdr = register_sysctl("kernel", sg_sysctls);
  1479. }
  1480. static void unregister_sg_sysctls(void)
  1481. {
  1482. if (hdr)
  1483. unregister_sysctl_table(hdr);
  1484. }
  1485. #else
  1486. #define register_sg_sysctls() do { } while (0)
  1487. #define unregister_sg_sysctls() do { } while (0)
  1488. #endif /* CONFIG_SYSCTL */
  1489. static int __init
  1490. init_sg(void)
  1491. {
  1492. int rc;
  1493. if (scatter_elem_sz < PAGE_SIZE) {
  1494. scatter_elem_sz = PAGE_SIZE;
  1495. scatter_elem_sz_prev = scatter_elem_sz;
  1496. }
  1497. if (def_reserved_size >= 0)
  1498. sg_big_buff = def_reserved_size;
  1499. else
  1500. def_reserved_size = sg_big_buff;
  1501. rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
  1502. SG_MAX_DEVS, "sg");
  1503. if (rc)
  1504. return rc;
  1505. sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic");
  1506. if ( IS_ERR(sg_sysfs_class) ) {
  1507. rc = PTR_ERR(sg_sysfs_class);
  1508. goto err_out;
  1509. }
  1510. sg_sysfs_valid = 1;
  1511. rc = scsi_register_interface(&sg_interface);
  1512. if (0 == rc) {
  1513. #ifdef CONFIG_SCSI_PROC_FS
  1514. sg_proc_init();
  1515. #endif /* CONFIG_SCSI_PROC_FS */
  1516. return 0;
  1517. }
  1518. class_destroy(sg_sysfs_class);
  1519. register_sg_sysctls();
  1520. err_out:
  1521. unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
  1522. return rc;
  1523. }
  1524. static void __exit
  1525. exit_sg(void)
  1526. {
  1527. unregister_sg_sysctls();
  1528. #ifdef CONFIG_SCSI_PROC_FS
  1529. remove_proc_subtree("scsi/sg", NULL);
  1530. #endif /* CONFIG_SCSI_PROC_FS */
  1531. scsi_unregister_interface(&sg_interface);
  1532. class_destroy(sg_sysfs_class);
  1533. sg_sysfs_valid = 0;
  1534. unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
  1535. SG_MAX_DEVS);
  1536. idr_destroy(&sg_index_idr);
  1537. }
  1538. static int
  1539. sg_start_req(Sg_request *srp, unsigned char *cmd)
  1540. {
  1541. int res;
  1542. struct request *rq;
  1543. Sg_fd *sfp = srp->parentfp;
  1544. sg_io_hdr_t *hp = &srp->header;
  1545. int dxfer_len = (int) hp->dxfer_len;
  1546. int dxfer_dir = hp->dxfer_direction;
  1547. unsigned int iov_count = hp->iovec_count;
  1548. Sg_scatter_hold *req_schp = &srp->data;
  1549. Sg_scatter_hold *rsv_schp = &sfp->reserve;
  1550. struct request_queue *q = sfp->parentdp->device->request_queue;
  1551. struct rq_map_data *md, map_data;
  1552. int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? ITER_SOURCE : ITER_DEST;
  1553. struct scsi_cmnd *scmd;
  1554. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1555. "sg_start_req: dxfer_len=%d\n",
  1556. dxfer_len));
  1557. /*
  1558. * NOTE
  1559. *
  1560. * With scsi-mq enabled, there are a fixed number of preallocated
  1561. * requests equal in number to shost->can_queue. If all of the
  1562. * preallocated requests are already in use, then scsi_alloc_request()
  1563. * will sleep until an active command completes, freeing up a request.
  1564. * Although waiting in an asynchronous interface is less than ideal, we
  1565. * do not want to use BLK_MQ_REQ_NOWAIT here because userspace might
  1566. * not expect an EWOULDBLOCK from this condition.
  1567. */
  1568. rq = scsi_alloc_request(q, hp->dxfer_direction == SG_DXFER_TO_DEV ?
  1569. REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
  1570. if (IS_ERR(rq))
  1571. return PTR_ERR(rq);
  1572. scmd = blk_mq_rq_to_pdu(rq);
  1573. if (hp->cmd_len > sizeof(scmd->cmnd)) {
  1574. blk_mq_free_request(rq);
  1575. return -EINVAL;
  1576. }
  1577. memcpy(scmd->cmnd, cmd, hp->cmd_len);
  1578. scmd->cmd_len = hp->cmd_len;
  1579. srp->rq = rq;
  1580. rq->end_io_data = srp;
  1581. scmd->allowed = SG_DEFAULT_RETRIES;
  1582. if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
  1583. return 0;
  1584. if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
  1585. dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
  1586. blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
  1587. md = NULL;
  1588. else
  1589. md = &map_data;
  1590. if (md) {
  1591. mutex_lock(&sfp->f_mutex);
  1592. if (dxfer_len <= rsv_schp->bufflen &&
  1593. !sfp->res_in_use) {
  1594. sfp->res_in_use = 1;
  1595. sg_link_reserve(sfp, srp, dxfer_len);
  1596. } else if (hp->flags & SG_FLAG_MMAP_IO) {
  1597. res = -EBUSY; /* sfp->res_in_use == 1 */
  1598. if (dxfer_len > rsv_schp->bufflen)
  1599. res = -ENOMEM;
  1600. mutex_unlock(&sfp->f_mutex);
  1601. return res;
  1602. } else {
  1603. res = sg_build_indirect(req_schp, sfp, dxfer_len);
  1604. if (res) {
  1605. mutex_unlock(&sfp->f_mutex);
  1606. return res;
  1607. }
  1608. }
  1609. mutex_unlock(&sfp->f_mutex);
  1610. md->pages = req_schp->pages;
  1611. md->page_order = req_schp->page_order;
  1612. md->nr_entries = req_schp->k_use_sg;
  1613. md->offset = 0;
  1614. md->null_mapped = hp->dxferp ? 0 : 1;
  1615. if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
  1616. md->from_user = 1;
  1617. else
  1618. md->from_user = 0;
  1619. }
  1620. res = blk_rq_map_user_io(rq, md, hp->dxferp, hp->dxfer_len,
  1621. GFP_ATOMIC, iov_count, iov_count, 1, rw);
  1622. if (!res) {
  1623. srp->bio = rq->bio;
  1624. if (!md) {
  1625. req_schp->dio_in_use = 1;
  1626. hp->info |= SG_INFO_DIRECT_IO;
  1627. }
  1628. }
  1629. return res;
  1630. }
  1631. static int
  1632. sg_finish_rem_req(Sg_request *srp)
  1633. {
  1634. int ret = 0;
  1635. Sg_fd *sfp = srp->parentfp;
  1636. Sg_scatter_hold *req_schp = &srp->data;
  1637. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1638. "sg_finish_rem_req: res_used=%d\n",
  1639. (int) srp->res_used));
  1640. if (srp->bio)
  1641. ret = blk_rq_unmap_user(srp->bio);
  1642. if (srp->rq)
  1643. blk_mq_free_request(srp->rq);
  1644. if (srp->res_used)
  1645. sg_unlink_reserve(sfp, srp);
  1646. else
  1647. sg_remove_scat(sfp, req_schp);
  1648. return ret;
  1649. }
  1650. static int
  1651. sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
  1652. {
  1653. int sg_bufflen = tablesize * sizeof(struct page *);
  1654. gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
  1655. schp->pages = kzalloc(sg_bufflen, gfp_flags);
  1656. if (!schp->pages)
  1657. return -ENOMEM;
  1658. schp->sglist_len = sg_bufflen;
  1659. return tablesize; /* number of scat_gath elements allocated */
  1660. }
  1661. static int
  1662. sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
  1663. {
  1664. int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
  1665. int sg_tablesize = sfp->parentdp->sg_tablesize;
  1666. int blk_size = buff_size, order;
  1667. gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
  1668. if (blk_size < 0)
  1669. return -EFAULT;
  1670. if (0 == blk_size)
  1671. ++blk_size; /* don't know why */
  1672. /* round request up to next highest SG_SECTOR_SZ byte boundary */
  1673. blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
  1674. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1675. "sg_build_indirect: buff_size=%d, blk_size=%d\n",
  1676. buff_size, blk_size));
  1677. /* N.B. ret_sz carried into this block ... */
  1678. mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
  1679. if (mx_sc_elems < 0)
  1680. return mx_sc_elems; /* most likely -ENOMEM */
  1681. num = scatter_elem_sz;
  1682. if (unlikely(num != scatter_elem_sz_prev)) {
  1683. if (num < PAGE_SIZE) {
  1684. scatter_elem_sz = PAGE_SIZE;
  1685. scatter_elem_sz_prev = PAGE_SIZE;
  1686. } else
  1687. scatter_elem_sz_prev = num;
  1688. }
  1689. order = get_order(num);
  1690. retry:
  1691. ret_sz = 1 << (PAGE_SHIFT + order);
  1692. for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
  1693. k++, rem_sz -= ret_sz) {
  1694. num = (rem_sz > scatter_elem_sz_prev) ?
  1695. scatter_elem_sz_prev : rem_sz;
  1696. schp->pages[k] = alloc_pages(gfp_mask, order);
  1697. if (!schp->pages[k])
  1698. goto out;
  1699. if (num == scatter_elem_sz_prev) {
  1700. if (unlikely(ret_sz > scatter_elem_sz_prev)) {
  1701. scatter_elem_sz = ret_sz;
  1702. scatter_elem_sz_prev = ret_sz;
  1703. }
  1704. }
  1705. SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
  1706. "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
  1707. k, num, ret_sz));
  1708. } /* end of for loop */
  1709. schp->page_order = order;
  1710. schp->k_use_sg = k;
  1711. SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
  1712. "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
  1713. k, rem_sz));
  1714. schp->bufflen = blk_size;
  1715. if (rem_sz > 0) /* must have failed */
  1716. return -ENOMEM;
  1717. return 0;
  1718. out:
  1719. for (i = 0; i < k; i++)
  1720. __free_pages(schp->pages[i], order);
  1721. if (--order >= 0)
  1722. goto retry;
  1723. return -ENOMEM;
  1724. }
  1725. static void
  1726. sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
  1727. {
  1728. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1729. "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
  1730. if (schp->pages && schp->sglist_len > 0) {
  1731. if (!schp->dio_in_use) {
  1732. int k;
  1733. for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
  1734. SCSI_LOG_TIMEOUT(5,
  1735. sg_printk(KERN_INFO, sfp->parentdp,
  1736. "sg_remove_scat: k=%d, pg=0x%p\n",
  1737. k, schp->pages[k]));
  1738. __free_pages(schp->pages[k], schp->page_order);
  1739. }
  1740. kfree(schp->pages);
  1741. }
  1742. }
  1743. memset(schp, 0, sizeof (*schp));
  1744. }
  1745. static int
  1746. sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
  1747. {
  1748. Sg_scatter_hold *schp = &srp->data;
  1749. int k, num;
  1750. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
  1751. "sg_read_oxfer: num_read_xfer=%d\n",
  1752. num_read_xfer));
  1753. if ((!outp) || (num_read_xfer <= 0))
  1754. return 0;
  1755. num = 1 << (PAGE_SHIFT + schp->page_order);
  1756. for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
  1757. if (num > num_read_xfer) {
  1758. if (copy_to_user(outp, page_address(schp->pages[k]),
  1759. num_read_xfer))
  1760. return -EFAULT;
  1761. break;
  1762. } else {
  1763. if (copy_to_user(outp, page_address(schp->pages[k]),
  1764. num))
  1765. return -EFAULT;
  1766. num_read_xfer -= num;
  1767. if (num_read_xfer <= 0)
  1768. break;
  1769. outp += num;
  1770. }
  1771. }
  1772. return 0;
  1773. }
  1774. static void
  1775. sg_build_reserve(Sg_fd * sfp, int req_size)
  1776. {
  1777. Sg_scatter_hold *schp = &sfp->reserve;
  1778. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1779. "sg_build_reserve: req_size=%d\n", req_size));
  1780. do {
  1781. if (req_size < PAGE_SIZE)
  1782. req_size = PAGE_SIZE;
  1783. if (0 == sg_build_indirect(schp, sfp, req_size))
  1784. return;
  1785. else
  1786. sg_remove_scat(sfp, schp);
  1787. req_size >>= 1; /* divide by 2 */
  1788. } while (req_size > (PAGE_SIZE / 2));
  1789. }
  1790. static void
  1791. sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
  1792. {
  1793. Sg_scatter_hold *req_schp = &srp->data;
  1794. Sg_scatter_hold *rsv_schp = &sfp->reserve;
  1795. int k, num, rem;
  1796. srp->res_used = 1;
  1797. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
  1798. "sg_link_reserve: size=%d\n", size));
  1799. rem = size;
  1800. num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
  1801. for (k = 0; k < rsv_schp->k_use_sg; k++) {
  1802. if (rem <= num) {
  1803. req_schp->k_use_sg = k + 1;
  1804. req_schp->sglist_len = rsv_schp->sglist_len;
  1805. req_schp->pages = rsv_schp->pages;
  1806. req_schp->bufflen = size;
  1807. req_schp->page_order = rsv_schp->page_order;
  1808. break;
  1809. } else
  1810. rem -= num;
  1811. }
  1812. if (k >= rsv_schp->k_use_sg)
  1813. SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
  1814. "sg_link_reserve: BAD size\n"));
  1815. }
  1816. static void
  1817. sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
  1818. {
  1819. Sg_scatter_hold *req_schp = &srp->data;
  1820. SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
  1821. "sg_unlink_reserve: req->k_use_sg=%d\n",
  1822. (int) req_schp->k_use_sg));
  1823. req_schp->k_use_sg = 0;
  1824. req_schp->bufflen = 0;
  1825. req_schp->pages = NULL;
  1826. req_schp->page_order = 0;
  1827. req_schp->sglist_len = 0;
  1828. srp->res_used = 0;
  1829. /* Called without mutex lock to avoid deadlock */
  1830. sfp->res_in_use = 0;
  1831. }
  1832. static Sg_request *
  1833. sg_get_rq_mark(Sg_fd * sfp, int pack_id, bool *busy)
  1834. {
  1835. Sg_request *resp;
  1836. unsigned long iflags;
  1837. *busy = false;
  1838. write_lock_irqsave(&sfp->rq_list_lock, iflags);
  1839. list_for_each_entry(resp, &sfp->rq_list, entry) {
  1840. /* look for requests that are not SG_IO owned */
  1841. if ((!resp->sg_io_owned) &&
  1842. ((-1 == pack_id) || (resp->header.pack_id == pack_id))) {
  1843. switch (resp->done) {
  1844. case 0: /* request active */
  1845. *busy = true;
  1846. break;
  1847. case 1: /* request done; response ready to return */
  1848. resp->done = 2; /* guard against other readers */
  1849. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1850. return resp;
  1851. case 2: /* response already being returned */
  1852. break;
  1853. }
  1854. }
  1855. }
  1856. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1857. return NULL;
  1858. }
  1859. /* always adds to end of list */
  1860. static Sg_request *
  1861. sg_add_request(Sg_fd * sfp)
  1862. {
  1863. int k;
  1864. unsigned long iflags;
  1865. Sg_request *rp = sfp->req_arr;
  1866. write_lock_irqsave(&sfp->rq_list_lock, iflags);
  1867. if (!list_empty(&sfp->rq_list)) {
  1868. if (!sfp->cmd_q)
  1869. goto out_unlock;
  1870. for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {
  1871. if (!rp->parentfp)
  1872. break;
  1873. }
  1874. if (k >= SG_MAX_QUEUE)
  1875. goto out_unlock;
  1876. }
  1877. memset(rp, 0, sizeof (Sg_request));
  1878. rp->parentfp = sfp;
  1879. rp->header.duration = jiffies_to_msecs(jiffies);
  1880. list_add_tail(&rp->entry, &sfp->rq_list);
  1881. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1882. return rp;
  1883. out_unlock:
  1884. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1885. return NULL;
  1886. }
  1887. /* Return of 1 for found; 0 for not found */
  1888. static int
  1889. sg_remove_request(Sg_fd * sfp, Sg_request * srp)
  1890. {
  1891. unsigned long iflags;
  1892. int res = 0;
  1893. if (!sfp || !srp || list_empty(&sfp->rq_list))
  1894. return res;
  1895. write_lock_irqsave(&sfp->rq_list_lock, iflags);
  1896. if (!list_empty(&srp->entry)) {
  1897. list_del(&srp->entry);
  1898. srp->parentfp = NULL;
  1899. res = 1;
  1900. }
  1901. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1902. /*
  1903. * If the device is detaching, wakeup any readers in case we just
  1904. * removed the last response, which would leave nothing for them to
  1905. * return other than -ENODEV.
  1906. */
  1907. if (unlikely(atomic_read(&sfp->parentdp->detaching)))
  1908. wake_up_interruptible_all(&sfp->read_wait);
  1909. return res;
  1910. }
  1911. static Sg_fd *
  1912. sg_add_sfp(Sg_device * sdp)
  1913. {
  1914. Sg_fd *sfp;
  1915. unsigned long iflags;
  1916. int bufflen;
  1917. sfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN);
  1918. if (!sfp)
  1919. return ERR_PTR(-ENOMEM);
  1920. init_waitqueue_head(&sfp->read_wait);
  1921. rwlock_init(&sfp->rq_list_lock);
  1922. INIT_LIST_HEAD(&sfp->rq_list);
  1923. kref_init(&sfp->f_ref);
  1924. mutex_init(&sfp->f_mutex);
  1925. sfp->timeout = SG_DEFAULT_TIMEOUT;
  1926. sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER;
  1927. sfp->force_packid = SG_DEF_FORCE_PACK_ID;
  1928. sfp->cmd_q = SG_DEF_COMMAND_Q;
  1929. sfp->keep_orphan = SG_DEF_KEEP_ORPHAN;
  1930. sfp->parentdp = sdp;
  1931. write_lock_irqsave(&sdp->sfd_lock, iflags);
  1932. if (atomic_read(&sdp->detaching)) {
  1933. write_unlock_irqrestore(&sdp->sfd_lock, iflags);
  1934. kfree(sfp);
  1935. return ERR_PTR(-ENODEV);
  1936. }
  1937. list_add_tail(&sfp->sfd_siblings, &sdp->sfds);
  1938. write_unlock_irqrestore(&sdp->sfd_lock, iflags);
  1939. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  1940. "sg_add_sfp: sfp=0x%p\n", sfp));
  1941. if (unlikely(sg_big_buff != def_reserved_size))
  1942. sg_big_buff = def_reserved_size;
  1943. bufflen = min_t(int, sg_big_buff,
  1944. max_sectors_bytes(sdp->device->request_queue));
  1945. sg_build_reserve(sfp, bufflen);
  1946. SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
  1947. "sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
  1948. sfp->reserve.bufflen,
  1949. sfp->reserve.k_use_sg));
  1950. kref_get(&sdp->d_ref);
  1951. __module_get(THIS_MODULE);
  1952. return sfp;
  1953. }
  1954. static void
  1955. sg_remove_sfp_usercontext(struct work_struct *work)
  1956. {
  1957. struct sg_fd *sfp = container_of(work, struct sg_fd, ew.work);
  1958. struct sg_device *sdp = sfp->parentdp;
  1959. Sg_request *srp;
  1960. unsigned long iflags;
  1961. /* Cleanup any responses which were never read(). */
  1962. write_lock_irqsave(&sfp->rq_list_lock, iflags);
  1963. while (!list_empty(&sfp->rq_list)) {
  1964. srp = list_first_entry(&sfp->rq_list, Sg_request, entry);
  1965. sg_finish_rem_req(srp);
  1966. list_del(&srp->entry);
  1967. srp->parentfp = NULL;
  1968. }
  1969. write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
  1970. if (sfp->reserve.bufflen > 0) {
  1971. SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,
  1972. "sg_remove_sfp: bufflen=%d, k_use_sg=%d\n",
  1973. (int) sfp->reserve.bufflen,
  1974. (int) sfp->reserve.k_use_sg));
  1975. sg_remove_scat(sfp, &sfp->reserve);
  1976. }
  1977. SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,
  1978. "sg_remove_sfp: sfp=0x%p\n", sfp));
  1979. kfree(sfp);
  1980. scsi_device_put(sdp->device);
  1981. kref_put(&sdp->d_ref, sg_device_destroy);
  1982. module_put(THIS_MODULE);
  1983. }
  1984. static void
  1985. sg_remove_sfp(struct kref *kref)
  1986. {
  1987. struct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref);
  1988. struct sg_device *sdp = sfp->parentdp;
  1989. unsigned long iflags;
  1990. write_lock_irqsave(&sdp->sfd_lock, iflags);
  1991. list_del(&sfp->sfd_siblings);
  1992. write_unlock_irqrestore(&sdp->sfd_lock, iflags);
  1993. INIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext);
  1994. schedule_work(&sfp->ew.work);
  1995. }
  1996. #ifdef CONFIG_SCSI_PROC_FS
  1997. static int
  1998. sg_idr_max_id(int id, void *p, void *data)
  1999. {
  2000. int *k = data;
  2001. if (*k < id)
  2002. *k = id;
  2003. return 0;
  2004. }
  2005. static int
  2006. sg_last_dev(void)
  2007. {
  2008. int k = -1;
  2009. unsigned long iflags;
  2010. read_lock_irqsave(&sg_index_lock, iflags);
  2011. idr_for_each(&sg_index_idr, sg_idr_max_id, &k);
  2012. read_unlock_irqrestore(&sg_index_lock, iflags);
  2013. return k + 1; /* origin 1 */
  2014. }
  2015. #endif
  2016. /* must be called with sg_index_lock held */
  2017. static Sg_device *sg_lookup_dev(int dev)
  2018. {
  2019. return idr_find(&sg_index_idr, dev);
  2020. }
  2021. static Sg_device *
  2022. sg_get_dev(int dev)
  2023. {
  2024. struct sg_device *sdp;
  2025. unsigned long flags;
  2026. read_lock_irqsave(&sg_index_lock, flags);
  2027. sdp = sg_lookup_dev(dev);
  2028. if (!sdp)
  2029. sdp = ERR_PTR(-ENXIO);
  2030. else if (atomic_read(&sdp->detaching)) {
  2031. /* If sdp->detaching, then the refcount may already be 0, in
  2032. * which case it would be a bug to do kref_get().
  2033. */
  2034. sdp = ERR_PTR(-ENODEV);
  2035. } else
  2036. kref_get(&sdp->d_ref);
  2037. read_unlock_irqrestore(&sg_index_lock, flags);
  2038. return sdp;
  2039. }
  2040. #ifdef CONFIG_SCSI_PROC_FS
  2041. static int sg_proc_seq_show_int(struct seq_file *s, void *v);
  2042. static int sg_proc_single_open_adio(struct inode *inode, struct file *file);
  2043. static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer,
  2044. size_t count, loff_t *off);
  2045. static const struct proc_ops adio_proc_ops = {
  2046. .proc_open = sg_proc_single_open_adio,
  2047. .proc_read = seq_read,
  2048. .proc_lseek = seq_lseek,
  2049. .proc_write = sg_proc_write_adio,
  2050. .proc_release = single_release,
  2051. };
  2052. static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);
  2053. static ssize_t sg_proc_write_dressz(struct file *filp,
  2054. const char __user *buffer, size_t count, loff_t *off);
  2055. static const struct proc_ops dressz_proc_ops = {
  2056. .proc_open = sg_proc_single_open_dressz,
  2057. .proc_read = seq_read,
  2058. .proc_lseek = seq_lseek,
  2059. .proc_write = sg_proc_write_dressz,
  2060. .proc_release = single_release,
  2061. };
  2062. static int sg_proc_seq_show_version(struct seq_file *s, void *v);
  2063. static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v);
  2064. static int sg_proc_seq_show_dev(struct seq_file *s, void *v);
  2065. static void * dev_seq_start(struct seq_file *s, loff_t *pos);
  2066. static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos);
  2067. static void dev_seq_stop(struct seq_file *s, void *v);
  2068. static const struct seq_operations dev_seq_ops = {
  2069. .start = dev_seq_start,
  2070. .next = dev_seq_next,
  2071. .stop = dev_seq_stop,
  2072. .show = sg_proc_seq_show_dev,
  2073. };
  2074. static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v);
  2075. static const struct seq_operations devstrs_seq_ops = {
  2076. .start = dev_seq_start,
  2077. .next = dev_seq_next,
  2078. .stop = dev_seq_stop,
  2079. .show = sg_proc_seq_show_devstrs,
  2080. };
  2081. static int sg_proc_seq_show_debug(struct seq_file *s, void *v);
  2082. static const struct seq_operations debug_seq_ops = {
  2083. .start = dev_seq_start,
  2084. .next = dev_seq_next,
  2085. .stop = dev_seq_stop,
  2086. .show = sg_proc_seq_show_debug,
  2087. };
  2088. static int
  2089. sg_proc_init(void)
  2090. {
  2091. struct proc_dir_entry *p;
  2092. p = proc_mkdir("scsi/sg", NULL);
  2093. if (!p)
  2094. return 1;
  2095. proc_create("allow_dio", S_IRUGO | S_IWUSR, p, &adio_proc_ops);
  2096. proc_create_seq("debug", S_IRUGO, p, &debug_seq_ops);
  2097. proc_create("def_reserved_size", S_IRUGO | S_IWUSR, p, &dressz_proc_ops);
  2098. proc_create_single("device_hdr", S_IRUGO, p, sg_proc_seq_show_devhdr);
  2099. proc_create_seq("devices", S_IRUGO, p, &dev_seq_ops);
  2100. proc_create_seq("device_strs", S_IRUGO, p, &devstrs_seq_ops);
  2101. proc_create_single("version", S_IRUGO, p, sg_proc_seq_show_version);
  2102. return 0;
  2103. }
  2104. static int sg_proc_seq_show_int(struct seq_file *s, void *v)
  2105. {
  2106. seq_printf(s, "%d\n", *((int *)s->private));
  2107. return 0;
  2108. }
  2109. static int sg_proc_single_open_adio(struct inode *inode, struct file *file)
  2110. {
  2111. return single_open(file, sg_proc_seq_show_int, &sg_allow_dio);
  2112. }
  2113. static ssize_t
  2114. sg_proc_write_adio(struct file *filp, const char __user *buffer,
  2115. size_t count, loff_t *off)
  2116. {
  2117. int err;
  2118. unsigned long num;
  2119. if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
  2120. return -EACCES;
  2121. err = kstrtoul_from_user(buffer, count, 0, &num);
  2122. if (err)
  2123. return err;
  2124. sg_allow_dio = num ? 1 : 0;
  2125. return count;
  2126. }
  2127. static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
  2128. {
  2129. return single_open(file, sg_proc_seq_show_int, &sg_big_buff);
  2130. }
  2131. static ssize_t
  2132. sg_proc_write_dressz(struct file *filp, const char __user *buffer,
  2133. size_t count, loff_t *off)
  2134. {
  2135. int err;
  2136. unsigned long k = ULONG_MAX;
  2137. if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
  2138. return -EACCES;
  2139. err = kstrtoul_from_user(buffer, count, 0, &k);
  2140. if (err)
  2141. return err;
  2142. if (k <= 1048576) { /* limit "big buff" to 1 MB */
  2143. sg_big_buff = k;
  2144. return count;
  2145. }
  2146. return -ERANGE;
  2147. }
  2148. static int sg_proc_seq_show_version(struct seq_file *s, void *v)
  2149. {
  2150. seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR,
  2151. sg_version_date);
  2152. return 0;
  2153. }
  2154. static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)
  2155. {
  2156. seq_puts(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n");
  2157. return 0;
  2158. }
  2159. struct sg_proc_deviter {
  2160. loff_t index;
  2161. size_t max;
  2162. };
  2163. static void * dev_seq_start(struct seq_file *s, loff_t *pos)
  2164. {
  2165. struct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL);
  2166. s->private = it;
  2167. if (! it)
  2168. return NULL;
  2169. it->index = *pos;
  2170. it->max = sg_last_dev();
  2171. if (it->index >= it->max)
  2172. return NULL;
  2173. return it;
  2174. }
  2175. static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos)
  2176. {
  2177. struct sg_proc_deviter * it = s->private;
  2178. *pos = ++it->index;
  2179. return (it->index < it->max) ? it : NULL;
  2180. }
  2181. static void dev_seq_stop(struct seq_file *s, void *v)
  2182. {
  2183. kfree(s->private);
  2184. }
  2185. static int sg_proc_seq_show_dev(struct seq_file *s, void *v)
  2186. {
  2187. struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
  2188. Sg_device *sdp;
  2189. struct scsi_device *scsidp;
  2190. unsigned long iflags;
  2191. read_lock_irqsave(&sg_index_lock, iflags);
  2192. sdp = it ? sg_lookup_dev(it->index) : NULL;
  2193. if ((NULL == sdp) || (NULL == sdp->device) ||
  2194. (atomic_read(&sdp->detaching)))
  2195. seq_puts(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n");
  2196. else {
  2197. scsidp = sdp->device;
  2198. seq_printf(s, "%d\t%d\t%d\t%llu\t%d\t%d\t%d\t%d\t%d\n",
  2199. scsidp->host->host_no, scsidp->channel,
  2200. scsidp->id, scsidp->lun, (int) scsidp->type,
  2201. 1,
  2202. (int) scsidp->queue_depth,
  2203. (int) scsi_device_busy(scsidp),
  2204. (int) scsi_device_online(scsidp));
  2205. }
  2206. read_unlock_irqrestore(&sg_index_lock, iflags);
  2207. return 0;
  2208. }
  2209. static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v)
  2210. {
  2211. struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
  2212. Sg_device *sdp;
  2213. struct scsi_device *scsidp;
  2214. unsigned long iflags;
  2215. read_lock_irqsave(&sg_index_lock, iflags);
  2216. sdp = it ? sg_lookup_dev(it->index) : NULL;
  2217. scsidp = sdp ? sdp->device : NULL;
  2218. if (sdp && scsidp && (!atomic_read(&sdp->detaching)))
  2219. seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n",
  2220. scsidp->vendor, scsidp->model, scsidp->rev);
  2221. else
  2222. seq_puts(s, "<no active device>\n");
  2223. read_unlock_irqrestore(&sg_index_lock, iflags);
  2224. return 0;
  2225. }
  2226. /* must be called while holding sg_index_lock */
  2227. static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp)
  2228. {
  2229. int k, new_interface, blen, usg;
  2230. Sg_request *srp;
  2231. Sg_fd *fp;
  2232. const sg_io_hdr_t *hp;
  2233. const char * cp;
  2234. unsigned int ms;
  2235. k = 0;
  2236. list_for_each_entry(fp, &sdp->sfds, sfd_siblings) {
  2237. k++;
  2238. read_lock(&fp->rq_list_lock); /* irqs already disabled */
  2239. seq_printf(s, " FD(%d): timeout=%dms bufflen=%d "
  2240. "(res)sgat=%d low_dma=%d\n", k,
  2241. jiffies_to_msecs(fp->timeout),
  2242. fp->reserve.bufflen,
  2243. (int) fp->reserve.k_use_sg, 0);
  2244. seq_printf(s, " cmd_q=%d f_packid=%d k_orphan=%d closed=0\n",
  2245. (int) fp->cmd_q, (int) fp->force_packid,
  2246. (int) fp->keep_orphan);
  2247. list_for_each_entry(srp, &fp->rq_list, entry) {
  2248. hp = &srp->header;
  2249. new_interface = (hp->interface_id == '\0') ? 0 : 1;
  2250. if (srp->res_used) {
  2251. if (new_interface &&
  2252. (SG_FLAG_MMAP_IO & hp->flags))
  2253. cp = " mmap>> ";
  2254. else
  2255. cp = " rb>> ";
  2256. } else {
  2257. if (SG_INFO_DIRECT_IO_MASK & hp->info)
  2258. cp = " dio>> ";
  2259. else
  2260. cp = " ";
  2261. }
  2262. seq_puts(s, cp);
  2263. blen = srp->data.bufflen;
  2264. usg = srp->data.k_use_sg;
  2265. seq_puts(s, srp->done ?
  2266. ((1 == srp->done) ? "rcv:" : "fin:")
  2267. : "act:");
  2268. seq_printf(s, " id=%d blen=%d",
  2269. srp->header.pack_id, blen);
  2270. if (srp->done)
  2271. seq_printf(s, " dur=%d", hp->duration);
  2272. else {
  2273. ms = jiffies_to_msecs(jiffies);
  2274. seq_printf(s, " t_o/elap=%d/%d",
  2275. (new_interface ? hp->timeout :
  2276. jiffies_to_msecs(fp->timeout)),
  2277. (ms > hp->duration ? ms - hp->duration : 0));
  2278. }
  2279. seq_printf(s, "ms sgat=%d op=0x%02x\n", usg,
  2280. (int) srp->data.cmd_opcode);
  2281. }
  2282. if (list_empty(&fp->rq_list))
  2283. seq_puts(s, " No requests active\n");
  2284. read_unlock(&fp->rq_list_lock);
  2285. }
  2286. }
  2287. static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
  2288. {
  2289. struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
  2290. Sg_device *sdp;
  2291. unsigned long iflags;
  2292. if (it && (0 == it->index))
  2293. seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
  2294. (int)it->max, sg_big_buff);
  2295. read_lock_irqsave(&sg_index_lock, iflags);
  2296. sdp = it ? sg_lookup_dev(it->index) : NULL;
  2297. if (NULL == sdp)
  2298. goto skip;
  2299. read_lock(&sdp->sfd_lock);
  2300. if (!list_empty(&sdp->sfds)) {
  2301. seq_printf(s, " >>> device=%s ", sdp->name);
  2302. if (atomic_read(&sdp->detaching))
  2303. seq_puts(s, "detaching pending close ");
  2304. else if (sdp->device) {
  2305. struct scsi_device *scsidp = sdp->device;
  2306. seq_printf(s, "%d:%d:%d:%llu em=%d",
  2307. scsidp->host->host_no,
  2308. scsidp->channel, scsidp->id,
  2309. scsidp->lun,
  2310. scsidp->host->hostt->emulated);
  2311. }
  2312. seq_printf(s, " sg_tablesize=%d excl=%d open_cnt=%d\n",
  2313. sdp->sg_tablesize, sdp->exclude, sdp->open_cnt);
  2314. sg_proc_debug_helper(s, sdp);
  2315. }
  2316. read_unlock(&sdp->sfd_lock);
  2317. skip:
  2318. read_unlock_irqrestore(&sg_index_lock, iflags);
  2319. return 0;
  2320. }
  2321. #endif /* CONFIG_SCSI_PROC_FS */
  2322. module_init(init_sg);
  2323. module_exit(exit_sg);