bsg: simplify __bsg_alloc_command failpath
[safe/jmp/linux-2.6] / block / bsg.c
1 /*
2  * bsg.c - block layer implementation of the sg v3 interface
3  *
4  * Copyright (C) 2004 Jens Axboe <axboe@suse.de> SUSE Labs
5  * Copyright (C) 2004 Peter M. Jones <pjones@redhat.com>
6  *
7  *  This file is subject to the terms and conditions of the GNU General Public
8  *  License version 2.  See the file "COPYING" in the main directory of this
9  *  archive for more details.
10  *
11  */
12 /*
13  * TODO
14  *      - Should this get merged, block/scsi_ioctl.c will be migrated into
15  *        this file. To keep maintenance down, it's easier to have them
16  *        seperated right now.
17  *
18  */
19 #include <linux/module.h>
20 #include <linux/init.h>
21 #include <linux/file.h>
22 #include <linux/blkdev.h>
23 #include <linux/poll.h>
24 #include <linux/cdev.h>
25 #include <linux/percpu.h>
26 #include <linux/uio.h>
27 #include <linux/bsg.h>
28
29 #include <scsi/scsi.h>
30 #include <scsi/scsi_ioctl.h>
31 #include <scsi/scsi_cmnd.h>
32 #include <scsi/sg.h>
33
34 static char bsg_version[] = "block layer sg (bsg) 0.4";
35
36 struct bsg_device {
37         struct gendisk *disk;
38         request_queue_t *queue;
39         spinlock_t lock;
40         struct list_head busy_list;
41         struct list_head done_list;
42         struct hlist_node dev_list;
43         atomic_t ref_count;
44         int minor;
45         int queued_cmds;
46         int done_cmds;
47         wait_queue_head_t wq_done;
48         wait_queue_head_t wq_free;
49         char name[BDEVNAME_SIZE];
50         int max_queue;
51         unsigned long flags;
52 };
53
54 enum {
55         BSG_F_BLOCK             = 1,
56         BSG_F_WRITE_PERM        = 2,
57 };
58
59 #define BSG_DEFAULT_CMDS        64
60
61 #undef BSG_DEBUG
62
63 #ifdef BSG_DEBUG
64 #define dprintk(fmt, args...) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ##args)
65 #else
66 #define dprintk(fmt, args...)
67 #endif
68
69 #define list_entry_bc(entry)    list_entry((entry), struct bsg_command, list)
70
71 /*
72  * just for testing
73  */
74 #define BSG_MAJOR       (240)
75
76 static DEFINE_MUTEX(bsg_mutex);
77 static int bsg_device_nr;
78
79 #define BSG_LIST_SIZE   (8)
80 #define bsg_list_idx(minor)     ((minor) & (BSG_LIST_SIZE - 1))
81 static struct hlist_head bsg_device_list[BSG_LIST_SIZE];
82
83 static struct class *bsg_class;
84 static LIST_HEAD(bsg_class_list);
85
86 static struct kmem_cache *bsg_cmd_cachep;
87
88 /*
89  * our internal command type
90  */
91 struct bsg_command {
92         struct bsg_device *bd;
93         struct list_head list;
94         struct request *rq;
95         struct bio *bio;
96         int err;
97         struct sg_io_v4 hdr;
98         struct sg_io_v4 __user *uhdr;
99         char sense[SCSI_SENSE_BUFFERSIZE];
100 };
101
102 static void bsg_free_command(struct bsg_command *bc)
103 {
104         struct bsg_device *bd = bc->bd;
105         unsigned long flags;
106
107         kmem_cache_free(bsg_cmd_cachep, bc);
108
109         spin_lock_irqsave(&bd->lock, flags);
110         bd->queued_cmds--;
111         spin_unlock_irqrestore(&bd->lock, flags);
112
113         wake_up(&bd->wq_free);
114 }
115
116 static struct bsg_command *__bsg_alloc_command(struct bsg_device *bd)
117 {
118         struct bsg_command *bc = NULL;
119
120         spin_lock_irq(&bd->lock);
121
122         if (bd->queued_cmds >= bd->max_queue)
123                 goto out;
124
125         bd->queued_cmds++;
126         spin_unlock_irq(&bd->lock);
127
128         bc = kmem_cache_alloc(bsg_cmd_cachep, GFP_USER);
129         if (unlikely(!bc)) {
130                 spin_lock_irq(&bd->lock);
131                 bd->queued_cmds--;
132                 goto out;
133         }
134
135         memset(bc, 0, sizeof(*bc));
136         bc->bd = bd;
137         INIT_LIST_HEAD(&bc->list);
138         dprintk("%s: returning free cmd %p\n", bd->name, bc);
139         return bc;
140 out:
141         spin_unlock_irq(&bd->lock);
142         return bc;
143 }
144
145 static inline void
146 bsg_del_done_cmd(struct bsg_device *bd, struct bsg_command *bc)
147 {
148         bd->done_cmds--;
149         list_del(&bc->list);
150 }
151
152 static inline void
153 bsg_add_done_cmd(struct bsg_device *bd, struct bsg_command *bc)
154 {
155         bd->done_cmds++;
156         list_add_tail(&bc->list, &bd->done_list);
157         wake_up(&bd->wq_done);
158 }
159
160 static inline int bsg_io_schedule(struct bsg_device *bd, int state)
161 {
162         DEFINE_WAIT(wait);
163         int ret = 0;
164
165         spin_lock_irq(&bd->lock);
166
167         BUG_ON(bd->done_cmds > bd->queued_cmds);
168
169         /*
170          * -ENOSPC or -ENODATA?  I'm going for -ENODATA, meaning "I have no
171          * work to do", even though we return -ENOSPC after this same test
172          * during bsg_write() -- there, it means our buffer can't have more
173          * bsg_commands added to it, thus has no space left.
174          */
175         if (bd->done_cmds == bd->queued_cmds) {
176                 ret = -ENODATA;
177                 goto unlock;
178         }
179
180         if (!test_bit(BSG_F_BLOCK, &bd->flags)) {
181                 ret = -EAGAIN;
182                 goto unlock;
183         }
184
185         prepare_to_wait(&bd->wq_done, &wait, state);
186         spin_unlock_irq(&bd->lock);
187         io_schedule();
188         finish_wait(&bd->wq_done, &wait);
189
190         if ((state == TASK_INTERRUPTIBLE) && signal_pending(current))
191                 ret = -ERESTARTSYS;
192
193         return ret;
194 unlock:
195         spin_unlock_irq(&bd->lock);
196         return ret;
197 }
198
199 /*
200  * get a new free command, blocking if needed and specified
201  */
202 static struct bsg_command *bsg_get_command(struct bsg_device *bd)
203 {
204         struct bsg_command *bc;
205         int ret;
206
207         do {
208                 bc = __bsg_alloc_command(bd);
209                 if (bc)
210                         break;
211
212                 ret = bsg_io_schedule(bd, TASK_INTERRUPTIBLE);
213                 if (ret) {
214                         bc = ERR_PTR(ret);
215                         break;
216                 }
217
218         } while (1);
219
220         return bc;
221 }
222
223 static int blk_fill_sgv4_hdr_rq(request_queue_t *q, struct request *rq,
224                                 struct sg_io_v4 *hdr, int has_write_perm)
225 {
226         memset(rq->cmd, 0, BLK_MAX_CDB); /* ATAPI hates garbage after CDB */
227
228         if (copy_from_user(rq->cmd, (void *)(unsigned long)hdr->request,
229                            hdr->request_len))
230                 return -EFAULT;
231         if (blk_verify_command(rq->cmd, has_write_perm))
232                 return -EPERM;
233
234         /*
235          * fill in request structure
236          */
237         rq->cmd_len = hdr->request_len;
238         rq->cmd_type = REQ_TYPE_BLOCK_PC;
239
240         rq->timeout = (hdr->timeout * HZ) / 1000;
241         if (!rq->timeout)
242                 rq->timeout = q->sg_timeout;
243         if (!rq->timeout)
244                 rq->timeout = BLK_DEFAULT_SG_TIMEOUT;
245
246         return 0;
247 }
248
249 /*
250  * Check if sg_io_v4 from user is allowed and valid
251  */
252 static int
253 bsg_validate_sgv4_hdr(request_queue_t *q, struct sg_io_v4 *hdr, int *rw)
254 {
255         if (hdr->guard != 'Q')
256                 return -EINVAL;
257         if (hdr->request_len > BLK_MAX_CDB)
258                 return -EINVAL;
259         if (hdr->dout_xfer_len > (q->max_sectors << 9) ||
260             hdr->din_xfer_len > (q->max_sectors << 9))
261                 return -EIO;
262
263         /* not supported currently */
264         if (hdr->protocol || hdr->subprotocol)
265                 return -EINVAL;
266
267         /*
268          * looks sane, if no data then it should be fine from our POV
269          */
270         if (!hdr->dout_xfer_len && !hdr->din_xfer_len)
271                 return 0;
272
273         /* not supported currently */
274         if (hdr->dout_xfer_len && hdr->din_xfer_len)
275                 return -EINVAL;
276
277         *rw = hdr->dout_xfer_len ? WRITE : READ;
278
279         return 0;
280 }
281
282 /*
283  * map sg_io_v4 to a request.
284  */
285 static struct request *
286 bsg_map_hdr(struct bsg_device *bd, struct sg_io_v4 *hdr)
287 {
288         request_queue_t *q = bd->queue;
289         struct request *rq;
290         int ret, rw = 0; /* shut up gcc */
291         unsigned int dxfer_len;
292         void *dxferp = NULL;
293
294         dprintk("map hdr %llx/%u %llx/%u\n", (unsigned long long) hdr->dout_xferp,
295                 hdr->dout_xfer_len, (unsigned long long) hdr->din_xferp,
296                 hdr->din_xfer_len);
297
298         ret = bsg_validate_sgv4_hdr(q, hdr, &rw);
299         if (ret)
300                 return ERR_PTR(ret);
301
302         /*
303          * map scatter-gather elements seperately and string them to request
304          */
305         rq = blk_get_request(q, rw, GFP_KERNEL);
306         ret = blk_fill_sgv4_hdr_rq(q, rq, hdr, test_bit(BSG_F_WRITE_PERM,
307                                                        &bd->flags));
308         if (ret) {
309                 blk_put_request(rq);
310                 return ERR_PTR(ret);
311         }
312
313         if (hdr->dout_xfer_len) {
314                 dxfer_len = hdr->dout_xfer_len;
315                 dxferp = (void*)(unsigned long)hdr->dout_xferp;
316         } else if (hdr->din_xfer_len) {
317                 dxfer_len = hdr->din_xfer_len;
318                 dxferp = (void*)(unsigned long)hdr->din_xferp;
319         } else
320                 dxfer_len = 0;
321
322         if (dxfer_len) {
323                 ret = blk_rq_map_user(q, rq, dxferp, dxfer_len);
324                 if (ret) {
325                         dprintk("failed map at %d\n", ret);
326                         blk_put_request(rq);
327                         rq = ERR_PTR(ret);
328                 }
329         }
330
331         return rq;
332 }
333
334 /*
335  * async completion call-back from the block layer, when scsi/ide/whatever
336  * calls end_that_request_last() on a request
337  */
338 static void bsg_rq_end_io(struct request *rq, int uptodate)
339 {
340         struct bsg_command *bc = rq->end_io_data;
341         struct bsg_device *bd = bc->bd;
342         unsigned long flags;
343
344         dprintk("%s: finished rq %p bc %p, bio %p stat %d\n",
345                 bd->name, rq, bc, bc->bio, uptodate);
346
347         bc->hdr.duration = jiffies_to_msecs(jiffies - bc->hdr.duration);
348
349         spin_lock_irqsave(&bd->lock, flags);
350         list_del(&bc->list);
351         bsg_add_done_cmd(bd, bc);
352         spin_unlock_irqrestore(&bd->lock, flags);
353 }
354
355 /*
356  * do final setup of a 'bc' and submit the matching 'rq' to the block
357  * layer for io
358  */
359 static void bsg_add_command(struct bsg_device *bd, request_queue_t *q,
360                             struct bsg_command *bc, struct request *rq)
361 {
362         rq->sense = bc->sense;
363         rq->sense_len = 0;
364
365         /*
366          * add bc command to busy queue and submit rq for io
367          */
368         bc->rq = rq;
369         bc->bio = rq->bio;
370         bc->hdr.duration = jiffies;
371         spin_lock_irq(&bd->lock);
372         list_add_tail(&bc->list, &bd->busy_list);
373         spin_unlock_irq(&bd->lock);
374
375         dprintk("%s: queueing rq %p, bc %p\n", bd->name, rq, bc);
376
377         rq->end_io_data = bc;
378         blk_execute_rq_nowait(q, bd->disk, rq, 1, bsg_rq_end_io);
379 }
380
381 static inline struct bsg_command *bsg_next_done_cmd(struct bsg_device *bd)
382 {
383         struct bsg_command *bc = NULL;
384
385         spin_lock_irq(&bd->lock);
386         if (bd->done_cmds) {
387                 bc = list_entry_bc(bd->done_list.next);
388                 bsg_del_done_cmd(bd, bc);
389         }
390         spin_unlock_irq(&bd->lock);
391
392         return bc;
393 }
394
395 /*
396  * Get a finished command from the done list
397  */
398 static struct bsg_command *__bsg_get_done_cmd(struct bsg_device *bd, int state)
399 {
400         struct bsg_command *bc;
401         int ret;
402
403         do {
404                 bc = bsg_next_done_cmd(bd);
405                 if (bc)
406                         break;
407
408                 ret = bsg_io_schedule(bd, state);
409                 if (ret) {
410                         bc = ERR_PTR(ret);
411                         break;
412                 }
413         } while (1);
414
415         dprintk("%s: returning done %p\n", bd->name, bc);
416
417         return bc;
418 }
419
420 static struct bsg_command *
421 bsg_get_done_cmd(struct bsg_device *bd, const struct iovec *iov)
422 {
423         return __bsg_get_done_cmd(bd, TASK_INTERRUPTIBLE);
424 }
425
426 static struct bsg_command *
427 bsg_get_done_cmd_nosignals(struct bsg_device *bd)
428 {
429         return __bsg_get_done_cmd(bd, TASK_UNINTERRUPTIBLE);
430 }
431
432 static int blk_complete_sgv4_hdr_rq(struct request *rq, struct sg_io_v4 *hdr,
433                                     struct bio *bio)
434 {
435         int ret = 0;
436
437         dprintk("rq %p bio %p %u\n", rq, bio, rq->errors);
438         /*
439          * fill in all the output members
440          */
441         hdr->device_status = status_byte(rq->errors);
442         hdr->transport_status = host_byte(rq->errors);
443         hdr->driver_status = driver_byte(rq->errors);
444         hdr->info = 0;
445         if (hdr->device_status || hdr->transport_status || hdr->driver_status)
446                 hdr->info |= SG_INFO_CHECK;
447         hdr->din_resid = rq->data_len;
448         hdr->response_len = 0;
449
450         if (rq->sense_len && hdr->response) {
451                 int len = min((unsigned int) hdr->max_response_len,
452                               rq->sense_len);
453
454                 ret = copy_to_user((void*)(unsigned long)hdr->response,
455                                    rq->sense, len);
456                 if (!ret)
457                         hdr->response_len = len;
458                 else
459                         ret = -EFAULT;
460         }
461
462         blk_rq_unmap_user(bio);
463         blk_put_request(rq);
464
465         return ret;
466 }
467
468 static int bsg_complete_all_commands(struct bsg_device *bd)
469 {
470         struct bsg_command *bc;
471         int ret, tret;
472
473         dprintk("%s: entered\n", bd->name);
474
475         set_bit(BSG_F_BLOCK, &bd->flags);
476
477         /*
478          * wait for all commands to complete
479          */
480         ret = 0;
481         do {
482                 ret = bsg_io_schedule(bd, TASK_UNINTERRUPTIBLE);
483                 /*
484                  * look for -ENODATA specifically -- we'll sometimes get
485                  * -ERESTARTSYS when we've taken a signal, but we can't
486                  * return until we're done freeing the queue, so ignore
487                  * it.  The signal will get handled when we're done freeing
488                  * the bsg_device.
489                  */
490         } while (ret != -ENODATA);
491
492         /*
493          * discard done commands
494          */
495         ret = 0;
496         do {
497                 bc = bsg_get_done_cmd_nosignals(bd);
498
499                 /*
500                  * we _must_ complete before restarting, because
501                  * bsg_release can't handle this failing.
502                  */
503                 if (PTR_ERR(bc) == -ERESTARTSYS)
504                         continue;
505                 if (IS_ERR(bc)) {
506                         ret = PTR_ERR(bc);
507                         break;
508                 }
509
510                 tret = blk_complete_sgv4_hdr_rq(bc->rq, &bc->hdr, bc->bio);
511                 if (!ret)
512                         ret = tret;
513
514                 bsg_free_command(bc);
515         } while (1);
516
517         return ret;
518 }
519
520 typedef struct bsg_command *(*bsg_command_callback)(struct bsg_device *bd, const struct iovec *iov);
521
522 static ssize_t
523 __bsg_read(char __user *buf, size_t count, bsg_command_callback get_bc,
524            struct bsg_device *bd, const struct iovec *iov, ssize_t *bytes_read)
525 {
526         struct bsg_command *bc;
527         int nr_commands, ret;
528
529         if (count % sizeof(struct sg_io_v4))
530                 return -EINVAL;
531
532         ret = 0;
533         nr_commands = count / sizeof(struct sg_io_v4);
534         while (nr_commands) {
535                 bc = get_bc(bd, iov);
536                 if (IS_ERR(bc)) {
537                         ret = PTR_ERR(bc);
538                         break;
539                 }
540
541                 /*
542                  * this is the only case where we need to copy data back
543                  * after completing the request. so do that here,
544                  * bsg_complete_work() cannot do that for us
545                  */
546                 ret = blk_complete_sgv4_hdr_rq(bc->rq, &bc->hdr, bc->bio);
547
548                 if (copy_to_user(buf, (char *) &bc->hdr, sizeof(bc->hdr)))
549                         ret = -EFAULT;
550
551                 bsg_free_command(bc);
552
553                 if (ret)
554                         break;
555
556                 buf += sizeof(struct sg_io_v4);
557                 *bytes_read += sizeof(struct sg_io_v4);
558                 nr_commands--;
559         }
560
561         return ret;
562 }
563
564 static inline void bsg_set_block(struct bsg_device *bd, struct file *file)
565 {
566         if (file->f_flags & O_NONBLOCK)
567                 clear_bit(BSG_F_BLOCK, &bd->flags);
568         else
569                 set_bit(BSG_F_BLOCK, &bd->flags);
570 }
571
572 static inline void bsg_set_write_perm(struct bsg_device *bd, struct file *file)
573 {
574         if (file->f_mode & FMODE_WRITE)
575                 set_bit(BSG_F_WRITE_PERM, &bd->flags);
576         else
577                 clear_bit(BSG_F_WRITE_PERM, &bd->flags);
578 }
579
580 static inline int err_block_err(int ret)
581 {
582         if (ret && ret != -ENOSPC && ret != -ENODATA && ret != -EAGAIN)
583                 return 1;
584
585         return 0;
586 }
587
588 static ssize_t
589 bsg_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
590 {
591         struct bsg_device *bd = file->private_data;
592         int ret;
593         ssize_t bytes_read;
594
595         dprintk("%s: read %Zd bytes\n", bd->name, count);
596
597         bsg_set_block(bd, file);
598         bytes_read = 0;
599         ret = __bsg_read(buf, count, bsg_get_done_cmd,
600                         bd, NULL, &bytes_read);
601         *ppos = bytes_read;
602
603         if (!bytes_read || (bytes_read && err_block_err(ret)))
604                 bytes_read = ret;
605
606         return bytes_read;
607 }
608
609 static ssize_t __bsg_write(struct bsg_device *bd, const char __user *buf,
610                            size_t count, ssize_t *bytes_read)
611 {
612         struct bsg_command *bc;
613         struct request *rq;
614         int ret, nr_commands;
615
616         if (count % sizeof(struct sg_io_v4))
617                 return -EINVAL;
618
619         nr_commands = count / sizeof(struct sg_io_v4);
620         rq = NULL;
621         bc = NULL;
622         ret = 0;
623         while (nr_commands) {
624                 request_queue_t *q = bd->queue;
625
626                 bc = bsg_get_command(bd);
627                 if (!bc)
628                         break;
629                 if (IS_ERR(bc)) {
630                         ret = PTR_ERR(bc);
631                         bc = NULL;
632                         break;
633                 }
634
635                 bc->uhdr = (struct sg_io_v4 __user *) buf;
636                 if (copy_from_user(&bc->hdr, buf, sizeof(bc->hdr))) {
637                         ret = -EFAULT;
638                         break;
639                 }
640
641                 /*
642                  * get a request, fill in the blanks, and add to request queue
643                  */
644                 rq = bsg_map_hdr(bd, &bc->hdr);
645                 if (IS_ERR(rq)) {
646                         ret = PTR_ERR(rq);
647                         rq = NULL;
648                         break;
649                 }
650
651                 bsg_add_command(bd, q, bc, rq);
652                 bc = NULL;
653                 rq = NULL;
654                 nr_commands--;
655                 buf += sizeof(struct sg_io_v4);
656                 *bytes_read += sizeof(struct sg_io_v4);
657         }
658
659         if (bc)
660                 bsg_free_command(bc);
661
662         return ret;
663 }
664
665 static ssize_t
666 bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
667 {
668         struct bsg_device *bd = file->private_data;
669         ssize_t bytes_read;
670         int ret;
671
672         dprintk("%s: write %Zd bytes\n", bd->name, count);
673
674         bsg_set_block(bd, file);
675         bsg_set_write_perm(bd, file);
676
677         bytes_read = 0;
678         ret = __bsg_write(bd, buf, count, &bytes_read);
679         *ppos = bytes_read;
680
681         /*
682          * return bytes written on non-fatal errors
683          */
684         if (!bytes_read || (bytes_read && err_block_err(ret)))
685                 bytes_read = ret;
686
687         dprintk("%s: returning %Zd\n", bd->name, bytes_read);
688         return bytes_read;
689 }
690
691 static struct bsg_device *bsg_alloc_device(void)
692 {
693         struct bsg_device *bd;
694
695         bd = kzalloc(sizeof(struct bsg_device), GFP_KERNEL);
696         if (unlikely(!bd))
697                 return NULL;
698
699         spin_lock_init(&bd->lock);
700
701         bd->max_queue = BSG_DEFAULT_CMDS;
702
703         INIT_LIST_HEAD(&bd->busy_list);
704         INIT_LIST_HEAD(&bd->done_list);
705         INIT_HLIST_NODE(&bd->dev_list);
706
707         init_waitqueue_head(&bd->wq_free);
708         init_waitqueue_head(&bd->wq_done);
709         return bd;
710 }
711
712 static int bsg_put_device(struct bsg_device *bd)
713 {
714         int ret = 0;
715
716         mutex_lock(&bsg_mutex);
717
718         if (!atomic_dec_and_test(&bd->ref_count))
719                 goto out;
720
721         dprintk("%s: tearing down\n", bd->name);
722
723         /*
724          * close can always block
725          */
726         set_bit(BSG_F_BLOCK, &bd->flags);
727
728         /*
729          * correct error detection baddies here again. it's the responsibility
730          * of the app to properly reap commands before close() if it wants
731          * fool-proof error detection
732          */
733         ret = bsg_complete_all_commands(bd);
734
735         blk_put_queue(bd->queue);
736         hlist_del(&bd->dev_list);
737         kfree(bd);
738 out:
739         mutex_unlock(&bsg_mutex);
740         return ret;
741 }
742
743 static struct bsg_device *bsg_add_device(struct inode *inode,
744                                          struct gendisk *disk,
745                                          struct file *file)
746 {
747         struct bsg_device *bd = NULL;
748 #ifdef BSG_DEBUG
749         unsigned char buf[32];
750 #endif
751
752         bd = bsg_alloc_device();
753         if (!bd)
754                 return ERR_PTR(-ENOMEM);
755
756         bd->disk = disk;
757         bd->queue = disk->queue;
758         kobject_get(&disk->queue->kobj);
759         bsg_set_block(bd, file);
760
761         atomic_set(&bd->ref_count, 1);
762         bd->minor = iminor(inode);
763         mutex_lock(&bsg_mutex);
764         hlist_add_head(&bd->dev_list,&bsg_device_list[bsg_list_idx(bd->minor)]);
765
766         strncpy(bd->name, disk->disk_name, sizeof(bd->name) - 1);
767         dprintk("bound to <%s>, max queue %d\n",
768                 format_dev_t(buf, inode->i_rdev), bd->max_queue);
769
770         mutex_unlock(&bsg_mutex);
771         return bd;
772 }
773
774 static struct bsg_device *__bsg_get_device(int minor)
775 {
776         struct hlist_head *list = &bsg_device_list[bsg_list_idx(minor)];
777         struct bsg_device *bd = NULL;
778         struct hlist_node *entry;
779
780         mutex_lock(&bsg_mutex);
781
782         hlist_for_each(entry, list) {
783                 bd = hlist_entry(entry, struct bsg_device, dev_list);
784                 if (bd->minor == minor) {
785                         atomic_inc(&bd->ref_count);
786                         break;
787                 }
788
789                 bd = NULL;
790         }
791
792         mutex_unlock(&bsg_mutex);
793         return bd;
794 }
795
796 static struct bsg_device *bsg_get_device(struct inode *inode, struct file *file)
797 {
798         struct bsg_device *bd = __bsg_get_device(iminor(inode));
799         struct bsg_class_device *bcd, *__bcd;
800
801         if (bd)
802                 return bd;
803
804         /*
805          * find the class device
806          */
807         bcd = NULL;
808         mutex_lock(&bsg_mutex);
809         list_for_each_entry(__bcd, &bsg_class_list, list) {
810                 if (__bcd->minor == iminor(inode)) {
811                         bcd = __bcd;
812                         break;
813                 }
814         }
815         mutex_unlock(&bsg_mutex);
816
817         if (!bcd)
818                 return ERR_PTR(-ENODEV);
819
820         return bsg_add_device(inode, bcd->disk, file);
821 }
822
823 static int bsg_open(struct inode *inode, struct file *file)
824 {
825         struct bsg_device *bd = bsg_get_device(inode, file);
826
827         if (IS_ERR(bd))
828                 return PTR_ERR(bd);
829
830         file->private_data = bd;
831         return 0;
832 }
833
834 static int bsg_release(struct inode *inode, struct file *file)
835 {
836         struct bsg_device *bd = file->private_data;
837
838         file->private_data = NULL;
839         return bsg_put_device(bd);
840 }
841
842 static unsigned int bsg_poll(struct file *file, poll_table *wait)
843 {
844         struct bsg_device *bd = file->private_data;
845         unsigned int mask = 0;
846
847         poll_wait(file, &bd->wq_done, wait);
848         poll_wait(file, &bd->wq_free, wait);
849
850         spin_lock_irq(&bd->lock);
851         if (!list_empty(&bd->done_list))
852                 mask |= POLLIN | POLLRDNORM;
853         if (bd->queued_cmds >= bd->max_queue)
854                 mask |= POLLOUT;
855         spin_unlock_irq(&bd->lock);
856
857         return mask;
858 }
859
860 static int
861 bsg_ioctl(struct inode *inode, struct file *file, unsigned int cmd,
862           unsigned long arg)
863 {
864         struct bsg_device *bd = file->private_data;
865         int __user *uarg = (int __user *) arg;
866
867         if (!bd)
868                 return -ENXIO;
869
870         switch (cmd) {
871                 /*
872                  * our own ioctls
873                  */
874         case SG_GET_COMMAND_Q:
875                 return put_user(bd->max_queue, uarg);
876         case SG_SET_COMMAND_Q: {
877                 int queue;
878
879                 if (get_user(queue, uarg))
880                         return -EFAULT;
881                 if (queue < 1)
882                         return -EINVAL;
883
884                 spin_lock_irq(&bd->lock);
885                 bd->max_queue = queue;
886                 spin_unlock_irq(&bd->lock);
887                 return 0;
888         }
889
890         /*
891          * SCSI/sg ioctls
892          */
893         case SG_GET_VERSION_NUM:
894         case SCSI_IOCTL_GET_IDLUN:
895         case SCSI_IOCTL_GET_BUS_NUMBER:
896         case SG_SET_TIMEOUT:
897         case SG_GET_TIMEOUT:
898         case SG_GET_RESERVED_SIZE:
899         case SG_SET_RESERVED_SIZE:
900         case SG_EMULATED_HOST:
901         case SCSI_IOCTL_SEND_COMMAND: {
902                 void __user *uarg = (void __user *) arg;
903                 return scsi_cmd_ioctl(file, bd->disk, cmd, uarg);
904         }
905         case SG_IO: {
906                 struct request *rq;
907                 struct bio *bio;
908                 struct sg_io_v4 hdr;
909
910                 if (copy_from_user(&hdr, uarg, sizeof(hdr)))
911                         return -EFAULT;
912
913                 rq = bsg_map_hdr(bd, &hdr);
914                 if (IS_ERR(rq))
915                         return PTR_ERR(rq);
916
917                 bio = rq->bio;
918                 blk_execute_rq(bd->queue, bd->disk, rq, 0);
919                 blk_complete_sgv4_hdr_rq(rq, &hdr, bio);
920
921                 if (copy_to_user(uarg, &hdr, sizeof(hdr)))
922                         return -EFAULT;
923
924                 return 0;
925         }
926         /*
927          * block device ioctls
928          */
929         default:
930 #if 0
931                 return ioctl_by_bdev(bd->bdev, cmd, arg);
932 #else
933                 return -ENOTTY;
934 #endif
935         }
936 }
937
938 static struct file_operations bsg_fops = {
939         .read           =       bsg_read,
940         .write          =       bsg_write,
941         .poll           =       bsg_poll,
942         .open           =       bsg_open,
943         .release        =       bsg_release,
944         .ioctl          =       bsg_ioctl,
945         .owner          =       THIS_MODULE,
946 };
947
948 void bsg_unregister_disk(struct gendisk *disk)
949 {
950         struct bsg_class_device *bcd = &disk->bsg_dev;
951
952         if (!bcd->class_dev)
953                 return;
954
955         mutex_lock(&bsg_mutex);
956         sysfs_remove_link(&bcd->disk->queue->kobj, "bsg");
957         class_device_destroy(bsg_class, MKDEV(BSG_MAJOR, bcd->minor));
958         bcd->class_dev = NULL;
959         list_del_init(&bcd->list);
960         mutex_unlock(&bsg_mutex);
961 }
962
963 int bsg_register_disk(struct gendisk *disk)
964 {
965         request_queue_t *q = disk->queue;
966         struct bsg_class_device *bcd;
967         dev_t dev;
968
969         /*
970          * we need a proper transport to send commands, not a stacked device
971          */
972         if (!q->request_fn)
973                 return 0;
974
975         bcd = &disk->bsg_dev;
976         memset(bcd, 0, sizeof(*bcd));
977         INIT_LIST_HEAD(&bcd->list);
978
979         mutex_lock(&bsg_mutex);
980         dev = MKDEV(BSG_MAJOR, bsg_device_nr);
981         bcd->minor = bsg_device_nr;
982         bsg_device_nr++;
983         bcd->disk = disk;
984         bcd->class_dev = class_device_create(bsg_class, NULL, dev, bcd->dev, "%s", disk->disk_name);
985         if (!bcd->class_dev)
986                 goto err;
987         list_add_tail(&bcd->list, &bsg_class_list);
988         if (sysfs_create_link(&q->kobj, &bcd->class_dev->kobj, "bsg"))
989                 goto err;
990         mutex_unlock(&bsg_mutex);
991         return 0;
992 err:
993         bsg_device_nr--;
994         if (bcd->class_dev)
995                 class_device_destroy(bsg_class, MKDEV(BSG_MAJOR, bcd->minor));
996         mutex_unlock(&bsg_mutex);
997         return -ENOMEM;
998 }
999
1000 static int __init bsg_init(void)
1001 {
1002         int ret, i;
1003
1004         bsg_cmd_cachep = kmem_cache_create("bsg_cmd",
1005                                 sizeof(struct bsg_command), 0, 0, NULL, NULL);
1006         if (!bsg_cmd_cachep) {
1007                 printk(KERN_ERR "bsg: failed creating slab cache\n");
1008                 return -ENOMEM;
1009         }
1010
1011         for (i = 0; i < BSG_LIST_SIZE; i++)
1012                 INIT_HLIST_HEAD(&bsg_device_list[i]);
1013
1014         bsg_class = class_create(THIS_MODULE, "bsg");
1015         if (IS_ERR(bsg_class)) {
1016                 kmem_cache_destroy(bsg_cmd_cachep);
1017                 return PTR_ERR(bsg_class);
1018         }
1019
1020         ret = register_chrdev(BSG_MAJOR, "bsg", &bsg_fops);
1021         if (ret) {
1022                 kmem_cache_destroy(bsg_cmd_cachep);
1023                 class_destroy(bsg_class);
1024                 return ret;
1025         }
1026
1027         printk(KERN_INFO "%s loaded\n", bsg_version);
1028         return 0;
1029 }
1030
1031 MODULE_AUTHOR("Jens Axboe");
1032 MODULE_DESCRIPTION("Block layer SGSI generic (sg) driver");
1033 MODULE_LICENSE("GPL");
1034
1035 subsys_initcall(bsg_init);