sg.c 74 KB

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