]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/ctl/ctl_backend_block.c
Move setting of media parameters inside open routines.
[FreeBSD/FreeBSD.git] / sys / cam / ctl / ctl_backend_block.c
1 /*-
2  * Copyright (c) 2003 Silicon Graphics International Corp.
3  * Copyright (c) 2009-2011 Spectra Logic Corporation
4  * Copyright (c) 2012 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_backend_block.c#5 $
36  */
37 /*
38  * CAM Target Layer driver backend for block devices.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/types.h>
49 #include <sys/kthread.h>
50 #include <sys/bio.h>
51 #include <sys/fcntl.h>
52 #include <sys/limits.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/condvar.h>
56 #include <sys/malloc.h>
57 #include <sys/conf.h>
58 #include <sys/ioccom.h>
59 #include <sys/queue.h>
60 #include <sys/sbuf.h>
61 #include <sys/endian.h>
62 #include <sys/uio.h>
63 #include <sys/buf.h>
64 #include <sys/taskqueue.h>
65 #include <sys/vnode.h>
66 #include <sys/namei.h>
67 #include <sys/mount.h>
68 #include <sys/disk.h>
69 #include <sys/fcntl.h>
70 #include <sys/filedesc.h>
71 #include <sys/filio.h>
72 #include <sys/proc.h>
73 #include <sys/pcpu.h>
74 #include <sys/module.h>
75 #include <sys/sdt.h>
76 #include <sys/devicestat.h>
77 #include <sys/sysctl.h>
78
79 #include <geom/geom.h>
80
81 #include <cam/cam.h>
82 #include <cam/scsi/scsi_all.h>
83 #include <cam/scsi/scsi_da.h>
84 #include <cam/ctl/ctl_io.h>
85 #include <cam/ctl/ctl.h>
86 #include <cam/ctl/ctl_backend.h>
87 #include <cam/ctl/ctl_ioctl.h>
88 #include <cam/ctl/ctl_scsi_all.h>
89 #include <cam/ctl/ctl_error.h>
90
91 /*
92  * The idea here is that we'll allocate enough S/G space to hold a 1MB
93  * I/O.  If we get an I/O larger than that, we'll split it.
94  */
95 #define CTLBLK_HALF_IO_SIZE     (512 * 1024)
96 #define CTLBLK_MAX_IO_SIZE      (CTLBLK_HALF_IO_SIZE * 2)
97 #define CTLBLK_MAX_SEG          MAXPHYS
98 #define CTLBLK_HALF_SEGS        MAX(CTLBLK_HALF_IO_SIZE / CTLBLK_MAX_SEG, 1)
99 #define CTLBLK_MAX_SEGS         (CTLBLK_HALF_SEGS * 2)
100
101 #ifdef CTLBLK_DEBUG
102 #define DPRINTF(fmt, args...) \
103     printf("cbb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
104 #else
105 #define DPRINTF(fmt, args...) do {} while(0)
106 #endif
107
108 #define PRIV(io)        \
109     ((struct ctl_ptr_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_BACKEND])
110 #define ARGS(io)        \
111     ((struct ctl_lba_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_LBA_LEN])
112
113 SDT_PROVIDER_DEFINE(cbb);
114
115 typedef enum {
116         CTL_BE_BLOCK_LUN_UNCONFIGURED   = 0x01,
117         CTL_BE_BLOCK_LUN_CONFIG_ERR     = 0x02,
118         CTL_BE_BLOCK_LUN_WAITING        = 0x04,
119 } ctl_be_block_lun_flags;
120
121 typedef enum {
122         CTL_BE_BLOCK_NONE,
123         CTL_BE_BLOCK_DEV,
124         CTL_BE_BLOCK_FILE
125 } ctl_be_block_type;
126
127 struct ctl_be_block_devdata {
128         struct cdev *cdev;
129         struct cdevsw *csw;
130         int dev_ref;
131 };
132
133 struct ctl_be_block_filedata {
134         struct ucred *cred;
135 };
136
137 union ctl_be_block_bedata {
138         struct ctl_be_block_devdata dev;
139         struct ctl_be_block_filedata file;
140 };
141
142 struct ctl_be_block_io;
143 struct ctl_be_block_lun;
144
145 typedef void (*cbb_dispatch_t)(struct ctl_be_block_lun *be_lun,
146                                struct ctl_be_block_io *beio);
147 typedef uint64_t (*cbb_getattr_t)(struct ctl_be_block_lun *be_lun,
148                                   const char *attrname);
149
150 /*
151  * Backend LUN structure.  There is a 1:1 mapping between a block device
152  * and a backend block LUN, and between a backend block LUN and a CTL LUN.
153  */
154 struct ctl_be_block_lun {
155         struct ctl_lun_create_params params;
156         char lunname[32];
157         char *dev_path;
158         ctl_be_block_type dev_type;
159         struct vnode *vn;
160         union ctl_be_block_bedata backend;
161         cbb_dispatch_t dispatch;
162         cbb_dispatch_t lun_flush;
163         cbb_dispatch_t unmap;
164         cbb_dispatch_t get_lba_status;
165         cbb_getattr_t getattr;
166         uma_zone_t lun_zone;
167         uint64_t size_blocks;
168         uint64_t size_bytes;
169         struct ctl_be_block_softc *softc;
170         struct devstat *disk_stats;
171         ctl_be_block_lun_flags flags;
172         STAILQ_ENTRY(ctl_be_block_lun) links;
173         struct ctl_be_lun cbe_lun;
174         struct taskqueue *io_taskqueue;
175         struct task io_task;
176         int num_threads;
177         STAILQ_HEAD(, ctl_io_hdr) input_queue;
178         STAILQ_HEAD(, ctl_io_hdr) config_read_queue;
179         STAILQ_HEAD(, ctl_io_hdr) config_write_queue;
180         STAILQ_HEAD(, ctl_io_hdr) datamove_queue;
181         struct mtx_padalign io_lock;
182         struct mtx_padalign queue_lock;
183 };
184
185 /*
186  * Overall softc structure for the block backend module.
187  */
188 struct ctl_be_block_softc {
189         struct mtx                       lock;
190         int                              num_luns;
191         STAILQ_HEAD(, ctl_be_block_lun)  lun_list;
192 };
193
194 static struct ctl_be_block_softc backend_block_softc;
195
196 /*
197  * Per-I/O information.
198  */
199 struct ctl_be_block_io {
200         union ctl_io                    *io;
201         struct ctl_sg_entry             sg_segs[CTLBLK_MAX_SEGS];
202         struct iovec                    xiovecs[CTLBLK_MAX_SEGS];
203         int                             bio_cmd;
204         int                             num_segs;
205         int                             num_bios_sent;
206         int                             num_bios_done;
207         int                             send_complete;
208         int                             num_errors;
209         struct bintime                  ds_t0;
210         devstat_tag_type                ds_tag_type;
211         devstat_trans_flags             ds_trans_type;
212         uint64_t                        io_len;
213         uint64_t                        io_offset;
214         int                             io_arg;
215         struct ctl_be_block_softc       *softc;
216         struct ctl_be_block_lun         *lun;
217         void (*beio_cont)(struct ctl_be_block_io *beio); /* to continue processing */
218 };
219
220 static int cbb_num_threads = 14;
221 SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, block, CTLFLAG_RD, 0,
222             "CAM Target Layer Block Backend");
223 SYSCTL_INT(_kern_cam_ctl_block, OID_AUTO, num_threads, CTLFLAG_RWTUN,
224            &cbb_num_threads, 0, "Number of threads per backing file");
225
226 static struct ctl_be_block_io *ctl_alloc_beio(struct ctl_be_block_softc *softc);
227 static void ctl_free_beio(struct ctl_be_block_io *beio);
228 static void ctl_complete_beio(struct ctl_be_block_io *beio);
229 static int ctl_be_block_move_done(union ctl_io *io);
230 static void ctl_be_block_biodone(struct bio *bio);
231 static void ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
232                                     struct ctl_be_block_io *beio);
233 static void ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
234                                        struct ctl_be_block_io *beio);
235 static void ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
236                                   struct ctl_be_block_io *beio);
237 static uint64_t ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun,
238                                          const char *attrname);
239 static void ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
240                                    struct ctl_be_block_io *beio);
241 static void ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
242                                    struct ctl_be_block_io *beio);
243 static void ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
244                                       struct ctl_be_block_io *beio);
245 static uint64_t ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun,
246                                          const char *attrname);
247 static void ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
248                                     union ctl_io *io);
249 static void ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
250                                     union ctl_io *io);
251 static void ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
252                                   union ctl_io *io);
253 static void ctl_be_block_worker(void *context, int pending);
254 static int ctl_be_block_submit(union ctl_io *io);
255 static int ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
256                                    int flag, struct thread *td);
257 static int ctl_be_block_open_file(struct ctl_be_block_lun *be_lun,
258                                   struct ctl_lun_req *req);
259 static int ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun,
260                                  struct ctl_lun_req *req);
261 static int ctl_be_block_close(struct ctl_be_block_lun *be_lun);
262 static int ctl_be_block_open(struct ctl_be_block_softc *softc,
263                              struct ctl_be_block_lun *be_lun,
264                              struct ctl_lun_req *req);
265 static int ctl_be_block_create(struct ctl_be_block_softc *softc,
266                                struct ctl_lun_req *req);
267 static int ctl_be_block_rm(struct ctl_be_block_softc *softc,
268                            struct ctl_lun_req *req);
269 static int ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
270                                   struct ctl_lun_req *req);
271 static int ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
272                                  struct ctl_lun_req *req);
273 static int ctl_be_block_modify(struct ctl_be_block_softc *softc,
274                            struct ctl_lun_req *req);
275 static void ctl_be_block_lun_shutdown(void *be_lun);
276 static void ctl_be_block_lun_config_status(void *be_lun,
277                                            ctl_lun_config_status status);
278 static int ctl_be_block_config_write(union ctl_io *io);
279 static int ctl_be_block_config_read(union ctl_io *io);
280 static int ctl_be_block_lun_info(void *be_lun, struct sbuf *sb);
281 static uint64_t ctl_be_block_lun_attr(void *be_lun, const char *attrname);
282 int ctl_be_block_init(void);
283
284 static struct ctl_backend_driver ctl_be_block_driver = 
285 {
286         .name = "block",
287         .flags = CTL_BE_FLAG_HAS_CONFIG,
288         .init = ctl_be_block_init,
289         .data_submit = ctl_be_block_submit,
290         .data_move_done = ctl_be_block_move_done,
291         .config_read = ctl_be_block_config_read,
292         .config_write = ctl_be_block_config_write,
293         .ioctl = ctl_be_block_ioctl,
294         .lun_info = ctl_be_block_lun_info,
295         .lun_attr = ctl_be_block_lun_attr
296 };
297
298 MALLOC_DEFINE(M_CTLBLK, "ctlblk", "Memory used for CTL block backend");
299 CTL_BACKEND_DECLARE(cbb, ctl_be_block_driver);
300
301 static uma_zone_t beio_zone;
302
303 static struct ctl_be_block_io *
304 ctl_alloc_beio(struct ctl_be_block_softc *softc)
305 {
306         struct ctl_be_block_io *beio;
307
308         beio = uma_zalloc(beio_zone, M_WAITOK | M_ZERO);
309         beio->softc = softc;
310         return (beio);
311 }
312
313 static void
314 ctl_free_beio(struct ctl_be_block_io *beio)
315 {
316         int duplicate_free;
317         int i;
318
319         duplicate_free = 0;
320
321         for (i = 0; i < beio->num_segs; i++) {
322                 if (beio->sg_segs[i].addr == NULL)
323                         duplicate_free++;
324
325                 uma_zfree(beio->lun->lun_zone, beio->sg_segs[i].addr);
326                 beio->sg_segs[i].addr = NULL;
327
328                 /* For compare we had two equal S/G lists. */
329                 if (ARGS(beio->io)->flags & CTL_LLF_COMPARE) {
330                         uma_zfree(beio->lun->lun_zone,
331                             beio->sg_segs[i + CTLBLK_HALF_SEGS].addr);
332                         beio->sg_segs[i + CTLBLK_HALF_SEGS].addr = NULL;
333                 }
334         }
335
336         if (duplicate_free > 0) {
337                 printf("%s: %d duplicate frees out of %d segments\n", __func__,
338                        duplicate_free, beio->num_segs);
339         }
340
341         uma_zfree(beio_zone, beio);
342 }
343
344 static void
345 ctl_complete_beio(struct ctl_be_block_io *beio)
346 {
347         union ctl_io *io = beio->io;
348
349         if (beio->beio_cont != NULL) {
350                 beio->beio_cont(beio);
351         } else {
352                 ctl_free_beio(beio);
353                 ctl_data_submit_done(io);
354         }
355 }
356
357 static int
358 ctl_be_block_move_done(union ctl_io *io)
359 {
360         struct ctl_be_block_io *beio;
361         struct ctl_be_block_lun *be_lun;
362         struct ctl_lba_len_flags *lbalen;
363 #ifdef CTL_TIME_IO
364         struct bintime cur_bt;
365 #endif
366         int i;
367
368         beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
369         be_lun = beio->lun;
370
371         DPRINTF("entered\n");
372
373 #ifdef CTL_TIME_IO
374         getbintime(&cur_bt);
375         bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
376         bintime_add(&io->io_hdr.dma_bt, &cur_bt);
377         io->io_hdr.num_dmas++;
378 #endif  
379         io->scsiio.kern_rel_offset += io->scsiio.kern_data_len;
380
381         /*
382          * We set status at this point for read commands, and write
383          * commands with errors.
384          */
385         if (io->io_hdr.flags & CTL_FLAG_ABORT) {
386                 ;
387         } else if ((io->io_hdr.port_status == 0) &&
388             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)) {
389                 lbalen = ARGS(beio->io);
390                 if (lbalen->flags & CTL_LLF_READ) {
391                         ctl_set_success(&io->scsiio);
392                 } else if (lbalen->flags & CTL_LLF_COMPARE) {
393                         /* We have two data blocks ready for comparison. */
394                         for (i = 0; i < beio->num_segs; i++) {
395                                 if (memcmp(beio->sg_segs[i].addr,
396                                     beio->sg_segs[i + CTLBLK_HALF_SEGS].addr,
397                                     beio->sg_segs[i].len) != 0)
398                                         break;
399                         }
400                         if (i < beio->num_segs)
401                                 ctl_set_sense(&io->scsiio,
402                                     /*current_error*/ 1,
403                                     /*sense_key*/ SSD_KEY_MISCOMPARE,
404                                     /*asc*/ 0x1D,
405                                     /*ascq*/ 0x00,
406                                     SSD_ELEM_NONE);
407                         else
408                                 ctl_set_success(&io->scsiio);
409                 }
410         } else if ((io->io_hdr.port_status != 0) &&
411             ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
412              (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
413                 /*
414                  * For hardware error sense keys, the sense key
415                  * specific value is defined to be a retry count,
416                  * but we use it to pass back an internal FETD
417                  * error code.  XXX KDM  Hopefully the FETD is only
418                  * using 16 bits for an error code, since that's
419                  * all the space we have in the sks field.
420                  */
421                 ctl_set_internal_failure(&io->scsiio,
422                                          /*sks_valid*/ 1,
423                                          /*retry_count*/
424                                          io->io_hdr.port_status);
425         }
426
427         /*
428          * If this is a read, or a write with errors, it is done.
429          */
430         if ((beio->bio_cmd == BIO_READ)
431          || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)
432          || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)) {
433                 ctl_complete_beio(beio);
434                 return (0);
435         }
436
437         /*
438          * At this point, we have a write and the DMA completed
439          * successfully.  We now have to queue it to the task queue to
440          * execute the backend I/O.  That is because we do blocking
441          * memory allocations, and in the file backing case, blocking I/O.
442          * This move done routine is generally called in the SIM's
443          * interrupt context, and therefore we cannot block.
444          */
445         mtx_lock(&be_lun->queue_lock);
446         /*
447          * XXX KDM make sure that links is okay to use at this point.
448          * Otherwise, we either need to add another field to ctl_io_hdr,
449          * or deal with resource allocation here.
450          */
451         STAILQ_INSERT_TAIL(&be_lun->datamove_queue, &io->io_hdr, links);
452         mtx_unlock(&be_lun->queue_lock);
453
454         taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
455
456         return (0);
457 }
458
459 static void
460 ctl_be_block_biodone(struct bio *bio)
461 {
462         struct ctl_be_block_io *beio;
463         struct ctl_be_block_lun *be_lun;
464         union ctl_io *io;
465         int error;
466
467         beio = bio->bio_caller1;
468         be_lun = beio->lun;
469         io = beio->io;
470
471         DPRINTF("entered\n");
472
473         error = bio->bio_error;
474         mtx_lock(&be_lun->io_lock);
475         if (error != 0)
476                 beio->num_errors++;
477
478         beio->num_bios_done++;
479
480         /*
481          * XXX KDM will this cause WITNESS to complain?  Holding a lock
482          * during the free might cause it to complain.
483          */
484         g_destroy_bio(bio);
485
486         /*
487          * If the send complete bit isn't set, or we aren't the last I/O to
488          * complete, then we're done.
489          */
490         if ((beio->send_complete == 0)
491          || (beio->num_bios_done < beio->num_bios_sent)) {
492                 mtx_unlock(&be_lun->io_lock);
493                 return;
494         }
495
496         /*
497          * At this point, we've verified that we are the last I/O to
498          * complete, so it's safe to drop the lock.
499          */
500         devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
501             beio->ds_tag_type, beio->ds_trans_type,
502             /*now*/ NULL, /*then*/&beio->ds_t0);
503         mtx_unlock(&be_lun->io_lock);
504
505         /*
506          * If there are any errors from the backing device, we fail the
507          * entire I/O with a medium error.
508          */
509         if (beio->num_errors > 0) {
510                 if (error == EOPNOTSUPP) {
511                         ctl_set_invalid_opcode(&io->scsiio);
512                 } else if (error == ENOSPC || error == EDQUOT) {
513                         ctl_set_space_alloc_fail(&io->scsiio);
514                 } else if (beio->bio_cmd == BIO_FLUSH) {
515                         /* XXX KDM is there is a better error here? */
516                         ctl_set_internal_failure(&io->scsiio,
517                                                  /*sks_valid*/ 1,
518                                                  /*retry_count*/ 0xbad2);
519                 } else
520                         ctl_set_medium_error(&io->scsiio);
521                 ctl_complete_beio(beio);
522                 return;
523         }
524
525         /*
526          * If this is a write, a flush, a delete or verify, we're all done.
527          * If this is a read, we can now send the data to the user.
528          */
529         if ((beio->bio_cmd == BIO_WRITE)
530          || (beio->bio_cmd == BIO_FLUSH)
531          || (beio->bio_cmd == BIO_DELETE)
532          || (ARGS(io)->flags & CTL_LLF_VERIFY)) {
533                 ctl_set_success(&io->scsiio);
534                 ctl_complete_beio(beio);
535         } else {
536                 if ((ARGS(io)->flags & CTL_LLF_READ) &&
537                     beio->beio_cont == NULL)
538                         ctl_set_success(&io->scsiio);
539 #ifdef CTL_TIME_IO
540                 getbintime(&io->io_hdr.dma_start_bt);
541 #endif  
542                 ctl_datamove(io);
543         }
544 }
545
546 static void
547 ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
548                         struct ctl_be_block_io *beio)
549 {
550         union ctl_io *io = beio->io;
551         struct mount *mountpoint;
552         int error, lock_flags;
553
554         DPRINTF("entered\n");
555
556         binuptime(&beio->ds_t0);
557         mtx_lock(&be_lun->io_lock);
558         devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
559         mtx_unlock(&be_lun->io_lock);
560
561         (void) vn_start_write(be_lun->vn, &mountpoint, V_WAIT);
562
563         if (MNT_SHARED_WRITES(mountpoint)
564          || ((mountpoint == NULL)
565           && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
566                 lock_flags = LK_SHARED;
567         else
568                 lock_flags = LK_EXCLUSIVE;
569
570         vn_lock(be_lun->vn, lock_flags | LK_RETRY);
571
572         error = VOP_FSYNC(be_lun->vn, beio->io_arg ? MNT_NOWAIT : MNT_WAIT,
573             curthread);
574         VOP_UNLOCK(be_lun->vn, 0);
575
576         vn_finished_write(mountpoint);
577
578         mtx_lock(&be_lun->io_lock);
579         devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
580             beio->ds_tag_type, beio->ds_trans_type,
581             /*now*/ NULL, /*then*/&beio->ds_t0);
582         mtx_unlock(&be_lun->io_lock);
583
584         if (error == 0)
585                 ctl_set_success(&io->scsiio);
586         else {
587                 /* XXX KDM is there is a better error here? */
588                 ctl_set_internal_failure(&io->scsiio,
589                                          /*sks_valid*/ 1,
590                                          /*retry_count*/ 0xbad1);
591         }
592
593         ctl_complete_beio(beio);
594 }
595
596 SDT_PROBE_DEFINE1(cbb, kernel, read, file_start, "uint64_t");
597 SDT_PROBE_DEFINE1(cbb, kernel, write, file_start, "uint64_t");
598 SDT_PROBE_DEFINE1(cbb, kernel, read, file_done,"uint64_t");
599 SDT_PROBE_DEFINE1(cbb, kernel, write, file_done, "uint64_t");
600
601 static void
602 ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
603                            struct ctl_be_block_io *beio)
604 {
605         struct ctl_be_block_filedata *file_data;
606         union ctl_io *io;
607         struct uio xuio;
608         struct iovec *xiovec;
609         int flags;
610         int error, i;
611
612         DPRINTF("entered\n");
613
614         file_data = &be_lun->backend.file;
615         io = beio->io;
616         flags = 0;
617         if (ARGS(io)->flags & CTL_LLF_DPO)
618                 flags |= IO_DIRECT;
619         if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
620                 flags |= IO_SYNC;
621
622         bzero(&xuio, sizeof(xuio));
623         if (beio->bio_cmd == BIO_READ) {
624                 SDT_PROBE(cbb, kernel, read, file_start, 0, 0, 0, 0, 0);
625                 xuio.uio_rw = UIO_READ;
626         } else {
627                 SDT_PROBE(cbb, kernel, write, file_start, 0, 0, 0, 0, 0);
628                 xuio.uio_rw = UIO_WRITE;
629         }
630         xuio.uio_offset = beio->io_offset;
631         xuio.uio_resid = beio->io_len;
632         xuio.uio_segflg = UIO_SYSSPACE;
633         xuio.uio_iov = beio->xiovecs;
634         xuio.uio_iovcnt = beio->num_segs;
635         xuio.uio_td = curthread;
636
637         for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
638                 xiovec->iov_base = beio->sg_segs[i].addr;
639                 xiovec->iov_len = beio->sg_segs[i].len;
640         }
641
642         binuptime(&beio->ds_t0);
643         mtx_lock(&be_lun->io_lock);
644         devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
645         mtx_unlock(&be_lun->io_lock);
646
647         if (beio->bio_cmd == BIO_READ) {
648                 vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
649
650                 /*
651                  * UFS pays attention to IO_DIRECT for reads.  If the
652                  * DIRECTIO option is configured into the kernel, it calls
653                  * ffs_rawread().  But that only works for single-segment
654                  * uios with user space addresses.  In our case, with a
655                  * kernel uio, it still reads into the buffer cache, but it
656                  * will just try to release the buffer from the cache later
657                  * on in ffs_read().
658                  *
659                  * ZFS does not pay attention to IO_DIRECT for reads.
660                  *
661                  * UFS does not pay attention to IO_SYNC for reads.
662                  *
663                  * ZFS pays attention to IO_SYNC (which translates into the
664                  * Solaris define FRSYNC for zfs_read()) for reads.  It
665                  * attempts to sync the file before reading.
666                  */
667                 error = VOP_READ(be_lun->vn, &xuio, flags, file_data->cred);
668
669                 VOP_UNLOCK(be_lun->vn, 0);
670                 SDT_PROBE(cbb, kernel, read, file_done, 0, 0, 0, 0, 0);
671         } else {
672                 struct mount *mountpoint;
673                 int lock_flags;
674
675                 (void)vn_start_write(be_lun->vn, &mountpoint, V_WAIT);
676
677                 if (MNT_SHARED_WRITES(mountpoint)
678                  || ((mountpoint == NULL)
679                   && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
680                         lock_flags = LK_SHARED;
681                 else
682                         lock_flags = LK_EXCLUSIVE;
683
684                 vn_lock(be_lun->vn, lock_flags | LK_RETRY);
685
686                 /*
687                  * UFS pays attention to IO_DIRECT for writes.  The write
688                  * is done asynchronously.  (Normally the write would just
689                  * get put into cache.
690                  *
691                  * UFS pays attention to IO_SYNC for writes.  It will
692                  * attempt to write the buffer out synchronously if that
693                  * flag is set.
694                  *
695                  * ZFS does not pay attention to IO_DIRECT for writes.
696                  *
697                  * ZFS pays attention to IO_SYNC (a.k.a. FSYNC or FRSYNC)
698                  * for writes.  It will flush the transaction from the
699                  * cache before returning.
700                  */
701                 error = VOP_WRITE(be_lun->vn, &xuio, flags, file_data->cred);
702                 VOP_UNLOCK(be_lun->vn, 0);
703
704                 vn_finished_write(mountpoint);
705                 SDT_PROBE(cbb, kernel, write, file_done, 0, 0, 0, 0, 0);
706         }
707
708         mtx_lock(&be_lun->io_lock);
709         devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
710             beio->ds_tag_type, beio->ds_trans_type,
711             /*now*/ NULL, /*then*/&beio->ds_t0);
712         mtx_unlock(&be_lun->io_lock);
713
714         /*
715          * If we got an error, set the sense data to "MEDIUM ERROR" and
716          * return the I/O to the user.
717          */
718         if (error != 0) {
719                 char path_str[32];
720
721                 ctl_scsi_path_string(io, path_str, sizeof(path_str));
722                 printf("%s%s command returned errno %d\n", path_str,
723                        (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE", error);
724                 if (error == ENOSPC || error == EDQUOT) {
725                         ctl_set_space_alloc_fail(&io->scsiio);
726                 } else
727                         ctl_set_medium_error(&io->scsiio);
728                 ctl_complete_beio(beio);
729                 return;
730         }
731
732         /*
733          * If this is a write or a verify, we're all done.
734          * If this is a read, we can now send the data to the user.
735          */
736         if ((beio->bio_cmd == BIO_WRITE) ||
737             (ARGS(io)->flags & CTL_LLF_VERIFY)) {
738                 ctl_set_success(&io->scsiio);
739                 ctl_complete_beio(beio);
740         } else {
741                 if ((ARGS(io)->flags & CTL_LLF_READ) &&
742                     beio->beio_cont == NULL)
743                         ctl_set_success(&io->scsiio);
744 #ifdef CTL_TIME_IO
745                 getbintime(&io->io_hdr.dma_start_bt);
746 #endif  
747                 ctl_datamove(io);
748         }
749 }
750
751 static void
752 ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
753                         struct ctl_be_block_io *beio)
754 {
755         union ctl_io *io = beio->io;
756         struct ctl_lba_len_flags *lbalen = ARGS(io);
757         struct scsi_get_lba_status_data *data;
758         off_t roff, off;
759         int error, status;
760
761         DPRINTF("entered\n");
762
763         off = roff = ((off_t)lbalen->lba) * be_lun->cbe_lun.blocksize;
764         vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
765         error = VOP_IOCTL(be_lun->vn, FIOSEEKHOLE, &off,
766             0, curthread->td_ucred, curthread);
767         if (error == 0 && off > roff)
768                 status = 0;     /* mapped up to off */
769         else {
770                 error = VOP_IOCTL(be_lun->vn, FIOSEEKDATA, &off,
771                     0, curthread->td_ucred, curthread);
772                 if (error == 0 && off > roff)
773                         status = 1;     /* deallocated up to off */
774                 else {
775                         status = 0;     /* unknown up to the end */
776                         off = be_lun->size_bytes;
777                 }
778         }
779         VOP_UNLOCK(be_lun->vn, 0);
780
781         data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
782         scsi_u64to8b(lbalen->lba, data->descr[0].addr);
783         scsi_ulto4b(MIN(UINT32_MAX, off / be_lun->cbe_lun.blocksize -
784             lbalen->lba), data->descr[0].length);
785         data->descr[0].status = status;
786
787         ctl_complete_beio(beio);
788 }
789
790 static uint64_t
791 ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun, const char *attrname)
792 {
793         struct vattr            vattr;
794         struct statfs           statfs;
795         uint64_t                val;
796         int                     error;
797
798         val = UINT64_MAX;
799         if (be_lun->vn == NULL)
800                 return (val);
801         vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
802         if (strcmp(attrname, "blocksused") == 0) {
803                 error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
804                 if (error == 0)
805                         val = vattr.va_bytes / be_lun->cbe_lun.blocksize;
806         }
807         if (strcmp(attrname, "blocksavail") == 0 &&
808             (be_lun->vn->v_iflag & VI_DOOMED) == 0) {
809                 error = VFS_STATFS(be_lun->vn->v_mount, &statfs);
810                 if (error == 0)
811                         val = statfs.f_bavail * statfs.f_bsize /
812                             be_lun->cbe_lun.blocksize;
813         }
814         VOP_UNLOCK(be_lun->vn, 0);
815         return (val);
816 }
817
818 static void
819 ctl_be_block_dispatch_zvol(struct ctl_be_block_lun *be_lun,
820                            struct ctl_be_block_io *beio)
821 {
822         struct ctl_be_block_devdata *dev_data;
823         union ctl_io *io;
824         struct uio xuio;
825         struct iovec *xiovec;
826         int flags;
827         int error, i;
828
829         DPRINTF("entered\n");
830
831         dev_data = &be_lun->backend.dev;
832         io = beio->io;
833         flags = 0;
834         if (ARGS(io)->flags & CTL_LLF_DPO)
835                 flags |= IO_DIRECT;
836         if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
837                 flags |= IO_SYNC;
838
839         bzero(&xuio, sizeof(xuio));
840         if (beio->bio_cmd == BIO_READ) {
841                 SDT_PROBE(cbb, kernel, read, file_start, 0, 0, 0, 0, 0);
842                 xuio.uio_rw = UIO_READ;
843         } else {
844                 SDT_PROBE(cbb, kernel, write, file_start, 0, 0, 0, 0, 0);
845                 xuio.uio_rw = UIO_WRITE;
846         }
847         xuio.uio_offset = beio->io_offset;
848         xuio.uio_resid = beio->io_len;
849         xuio.uio_segflg = UIO_SYSSPACE;
850         xuio.uio_iov = beio->xiovecs;
851         xuio.uio_iovcnt = beio->num_segs;
852         xuio.uio_td = curthread;
853
854         for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
855                 xiovec->iov_base = beio->sg_segs[i].addr;
856                 xiovec->iov_len = beio->sg_segs[i].len;
857         }
858
859         binuptime(&beio->ds_t0);
860         mtx_lock(&be_lun->io_lock);
861         devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
862         mtx_unlock(&be_lun->io_lock);
863
864         if (beio->bio_cmd == BIO_READ) {
865                 error = (*dev_data->csw->d_read)(dev_data->cdev, &xuio, flags);
866                 SDT_PROBE(cbb, kernel, read, file_done, 0, 0, 0, 0, 0);
867         } else {
868                 error = (*dev_data->csw->d_write)(dev_data->cdev, &xuio, flags);
869                 SDT_PROBE(cbb, kernel, write, file_done, 0, 0, 0, 0, 0);
870         }
871
872         mtx_lock(&be_lun->io_lock);
873         devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
874             beio->ds_tag_type, beio->ds_trans_type,
875             /*now*/ NULL, /*then*/&beio->ds_t0);
876         mtx_unlock(&be_lun->io_lock);
877
878         /*
879          * If we got an error, set the sense data to "MEDIUM ERROR" and
880          * return the I/O to the user.
881          */
882         if (error != 0) {
883                 if (error == ENOSPC || error == EDQUOT) {
884                         ctl_set_space_alloc_fail(&io->scsiio);
885                 } else
886                         ctl_set_medium_error(&io->scsiio);
887                 ctl_complete_beio(beio);
888                 return;
889         }
890
891         /*
892          * If this is a write or a verify, we're all done.
893          * If this is a read, we can now send the data to the user.
894          */
895         if ((beio->bio_cmd == BIO_WRITE) ||
896             (ARGS(io)->flags & CTL_LLF_VERIFY)) {
897                 ctl_set_success(&io->scsiio);
898                 ctl_complete_beio(beio);
899         } else {
900                 if ((ARGS(io)->flags & CTL_LLF_READ) &&
901                     beio->beio_cont == NULL)
902                         ctl_set_success(&io->scsiio);
903 #ifdef CTL_TIME_IO
904                 getbintime(&io->io_hdr.dma_start_bt);
905 #endif  
906                 ctl_datamove(io);
907         }
908 }
909
910 static void
911 ctl_be_block_gls_zvol(struct ctl_be_block_lun *be_lun,
912                         struct ctl_be_block_io *beio)
913 {
914         struct ctl_be_block_devdata *dev_data = &be_lun->backend.dev;
915         union ctl_io *io = beio->io;
916         struct ctl_lba_len_flags *lbalen = ARGS(io);
917         struct scsi_get_lba_status_data *data;
918         off_t roff, off;
919         int error, status;
920
921         DPRINTF("entered\n");
922
923         off = roff = ((off_t)lbalen->lba) * be_lun->cbe_lun.blocksize;
924         error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKHOLE,
925             (caddr_t)&off, FREAD, curthread);
926         if (error == 0 && off > roff)
927                 status = 0;     /* mapped up to off */
928         else {
929                 error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKDATA,
930                     (caddr_t)&off, FREAD, curthread);
931                 if (error == 0 && off > roff)
932                         status = 1;     /* deallocated up to off */
933                 else {
934                         status = 0;     /* unknown up to the end */
935                         off = be_lun->size_bytes;
936                 }
937         }
938
939         data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
940         scsi_u64to8b(lbalen->lba, data->descr[0].addr);
941         scsi_ulto4b(MIN(UINT32_MAX, off / be_lun->cbe_lun.blocksize -
942             lbalen->lba), data->descr[0].length);
943         data->descr[0].status = status;
944
945         ctl_complete_beio(beio);
946 }
947
948 static void
949 ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
950                        struct ctl_be_block_io *beio)
951 {
952         struct bio *bio;
953         union ctl_io *io;
954         struct ctl_be_block_devdata *dev_data;
955
956         dev_data = &be_lun->backend.dev;
957         io = beio->io;
958
959         DPRINTF("entered\n");
960
961         /* This can't fail, it's a blocking allocation. */
962         bio = g_alloc_bio();
963
964         bio->bio_cmd        = BIO_FLUSH;
965         bio->bio_dev        = dev_data->cdev;
966         bio->bio_offset     = 0;
967         bio->bio_data       = 0;
968         bio->bio_done       = ctl_be_block_biodone;
969         bio->bio_caller1    = beio;
970         bio->bio_pblkno     = 0;
971
972         /*
973          * We don't need to acquire the LUN lock here, because we are only
974          * sending one bio, and so there is no other context to synchronize
975          * with.
976          */
977         beio->num_bios_sent = 1;
978         beio->send_complete = 1;
979
980         binuptime(&beio->ds_t0);
981         mtx_lock(&be_lun->io_lock);
982         devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
983         mtx_unlock(&be_lun->io_lock);
984
985         (*dev_data->csw->d_strategy)(bio);
986 }
987
988 static void
989 ctl_be_block_unmap_dev_range(struct ctl_be_block_lun *be_lun,
990                        struct ctl_be_block_io *beio,
991                        uint64_t off, uint64_t len, int last)
992 {
993         struct bio *bio;
994         struct ctl_be_block_devdata *dev_data;
995         uint64_t maxlen;
996
997         dev_data = &be_lun->backend.dev;
998         maxlen = LONG_MAX - (LONG_MAX % be_lun->cbe_lun.blocksize);
999         while (len > 0) {
1000                 bio = g_alloc_bio();
1001                 bio->bio_cmd        = BIO_DELETE;
1002                 bio->bio_dev        = dev_data->cdev;
1003                 bio->bio_offset     = off;
1004                 bio->bio_length     = MIN(len, maxlen);
1005                 bio->bio_data       = 0;
1006                 bio->bio_done       = ctl_be_block_biodone;
1007                 bio->bio_caller1    = beio;
1008                 bio->bio_pblkno     = off / be_lun->cbe_lun.blocksize;
1009
1010                 off += bio->bio_length;
1011                 len -= bio->bio_length;
1012
1013                 mtx_lock(&be_lun->io_lock);
1014                 beio->num_bios_sent++;
1015                 if (last && len == 0)
1016                         beio->send_complete = 1;
1017                 mtx_unlock(&be_lun->io_lock);
1018
1019                 (*dev_data->csw->d_strategy)(bio);
1020         }
1021 }
1022
1023 static void
1024 ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
1025                        struct ctl_be_block_io *beio)
1026 {
1027         union ctl_io *io;
1028         struct ctl_be_block_devdata *dev_data;
1029         struct ctl_ptr_len_flags *ptrlen;
1030         struct scsi_unmap_desc *buf, *end;
1031         uint64_t len;
1032
1033         dev_data = &be_lun->backend.dev;
1034         io = beio->io;
1035
1036         DPRINTF("entered\n");
1037
1038         binuptime(&beio->ds_t0);
1039         mtx_lock(&be_lun->io_lock);
1040         devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1041         mtx_unlock(&be_lun->io_lock);
1042
1043         if (beio->io_offset == -1) {
1044                 beio->io_len = 0;
1045                 ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1046                 buf = (struct scsi_unmap_desc *)ptrlen->ptr;
1047                 end = buf + ptrlen->len / sizeof(*buf);
1048                 for (; buf < end; buf++) {
1049                         len = (uint64_t)scsi_4btoul(buf->length) *
1050                             be_lun->cbe_lun.blocksize;
1051                         beio->io_len += len;
1052                         ctl_be_block_unmap_dev_range(be_lun, beio,
1053                             scsi_8btou64(buf->lba) * be_lun->cbe_lun.blocksize,
1054                             len, (end - buf < 2) ? TRUE : FALSE);
1055                 }
1056         } else
1057                 ctl_be_block_unmap_dev_range(be_lun, beio,
1058                     beio->io_offset, beio->io_len, TRUE);
1059 }
1060
1061 static void
1062 ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
1063                           struct ctl_be_block_io *beio)
1064 {
1065         TAILQ_HEAD(, bio) queue = TAILQ_HEAD_INITIALIZER(queue);
1066         int i;
1067         struct bio *bio;
1068         struct ctl_be_block_devdata *dev_data;
1069         off_t cur_offset;
1070         int max_iosize;
1071
1072         DPRINTF("entered\n");
1073
1074         dev_data = &be_lun->backend.dev;
1075
1076         /*
1077          * We have to limit our I/O size to the maximum supported by the
1078          * backend device.  Hopefully it is MAXPHYS.  If the driver doesn't
1079          * set it properly, use DFLTPHYS.
1080          */
1081         max_iosize = dev_data->cdev->si_iosize_max;
1082         if (max_iosize < PAGE_SIZE)
1083                 max_iosize = DFLTPHYS;
1084
1085         cur_offset = beio->io_offset;
1086         for (i = 0; i < beio->num_segs; i++) {
1087                 size_t cur_size;
1088                 uint8_t *cur_ptr;
1089
1090                 cur_size = beio->sg_segs[i].len;
1091                 cur_ptr = beio->sg_segs[i].addr;
1092
1093                 while (cur_size > 0) {
1094                         /* This can't fail, it's a blocking allocation. */
1095                         bio = g_alloc_bio();
1096
1097                         KASSERT(bio != NULL, ("g_alloc_bio() failed!\n"));
1098
1099                         bio->bio_cmd = beio->bio_cmd;
1100                         bio->bio_dev = dev_data->cdev;
1101                         bio->bio_caller1 = beio;
1102                         bio->bio_length = min(cur_size, max_iosize);
1103                         bio->bio_offset = cur_offset;
1104                         bio->bio_data = cur_ptr;
1105                         bio->bio_done = ctl_be_block_biodone;
1106                         bio->bio_pblkno = cur_offset / be_lun->cbe_lun.blocksize;
1107
1108                         cur_offset += bio->bio_length;
1109                         cur_ptr += bio->bio_length;
1110                         cur_size -= bio->bio_length;
1111
1112                         TAILQ_INSERT_TAIL(&queue, bio, bio_queue);
1113                         beio->num_bios_sent++;
1114                 }
1115         }
1116         binuptime(&beio->ds_t0);
1117         mtx_lock(&be_lun->io_lock);
1118         devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1119         beio->send_complete = 1;
1120         mtx_unlock(&be_lun->io_lock);
1121
1122         /*
1123          * Fire off all allocated requests!
1124          */
1125         while ((bio = TAILQ_FIRST(&queue)) != NULL) {
1126                 TAILQ_REMOVE(&queue, bio, bio_queue);
1127                 (*dev_data->csw->d_strategy)(bio);
1128         }
1129 }
1130
1131 static uint64_t
1132 ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun, const char *attrname)
1133 {
1134         struct ctl_be_block_devdata     *dev_data = &be_lun->backend.dev;
1135         struct diocgattr_arg    arg;
1136         int                     error;
1137
1138         if (dev_data->csw == NULL || dev_data->csw->d_ioctl == NULL)
1139                 return (UINT64_MAX);
1140         strlcpy(arg.name, attrname, sizeof(arg.name));
1141         arg.len = sizeof(arg.value.off);
1142         error = dev_data->csw->d_ioctl(dev_data->cdev,
1143             DIOCGATTR, (caddr_t)&arg, FREAD, curthread);
1144         if (error != 0)
1145                 return (UINT64_MAX);
1146         return (arg.value.off);
1147 }
1148
1149 static void
1150 ctl_be_block_cw_dispatch_sync(struct ctl_be_block_lun *be_lun,
1151                             union ctl_io *io)
1152 {
1153         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
1154         struct ctl_be_block_io *beio;
1155         struct ctl_lba_len_flags *lbalen;
1156
1157         DPRINTF("entered\n");
1158         beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1159         lbalen = (struct ctl_lba_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1160
1161         beio->io_len = lbalen->len * cbe_lun->blocksize;
1162         beio->io_offset = lbalen->lba * cbe_lun->blocksize;
1163         beio->io_arg = (lbalen->flags & SSC_IMMED) != 0;
1164         beio->bio_cmd = BIO_FLUSH;
1165         beio->ds_trans_type = DEVSTAT_NO_DATA;
1166         DPRINTF("SYNC\n");
1167         be_lun->lun_flush(be_lun, beio);
1168 }
1169
1170 static void
1171 ctl_be_block_cw_done_ws(struct ctl_be_block_io *beio)
1172 {
1173         union ctl_io *io;
1174
1175         io = beio->io;
1176         ctl_free_beio(beio);
1177         if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1178             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1179              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1180                 ctl_config_write_done(io);
1181                 return;
1182         }
1183
1184         ctl_be_block_config_write(io);
1185 }
1186
1187 static void
1188 ctl_be_block_cw_dispatch_ws(struct ctl_be_block_lun *be_lun,
1189                             union ctl_io *io)
1190 {
1191         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
1192         struct ctl_be_block_io *beio;
1193         struct ctl_lba_len_flags *lbalen;
1194         uint64_t len_left, lba;
1195         uint32_t pb, pbo, adj;
1196         int i, seglen;
1197         uint8_t *buf, *end;
1198
1199         DPRINTF("entered\n");
1200
1201         beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1202         lbalen = ARGS(beio->io);
1203
1204         if (lbalen->flags & ~(SWS_LBDATA | SWS_UNMAP | SWS_ANCHOR | SWS_NDOB) ||
1205             (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR) && be_lun->unmap == NULL)) {
1206                 ctl_free_beio(beio);
1207                 ctl_set_invalid_field(&io->scsiio,
1208                                       /*sks_valid*/ 1,
1209                                       /*command*/ 1,
1210                                       /*field*/ 1,
1211                                       /*bit_valid*/ 0,
1212                                       /*bit*/ 0);
1213                 ctl_config_write_done(io);
1214                 return;
1215         }
1216
1217         if (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR)) {
1218                 beio->io_offset = lbalen->lba * cbe_lun->blocksize;
1219                 beio->io_len = (uint64_t)lbalen->len * cbe_lun->blocksize;
1220                 beio->bio_cmd = BIO_DELETE;
1221                 beio->ds_trans_type = DEVSTAT_FREE;
1222
1223                 be_lun->unmap(be_lun, beio);
1224                 return;
1225         }
1226
1227         beio->bio_cmd = BIO_WRITE;
1228         beio->ds_trans_type = DEVSTAT_WRITE;
1229
1230         DPRINTF("WRITE SAME at LBA %jx len %u\n",
1231                (uintmax_t)lbalen->lba, lbalen->len);
1232
1233         pb = cbe_lun->blocksize << be_lun->cbe_lun.pblockexp;
1234         if (be_lun->cbe_lun.pblockoff > 0)
1235                 pbo = pb - cbe_lun->blocksize * be_lun->cbe_lun.pblockoff;
1236         else
1237                 pbo = 0;
1238         len_left = (uint64_t)lbalen->len * cbe_lun->blocksize;
1239         for (i = 0, lba = 0; i < CTLBLK_MAX_SEGS && len_left > 0; i++) {
1240
1241                 /*
1242                  * Setup the S/G entry for this chunk.
1243                  */
1244                 seglen = MIN(CTLBLK_MAX_SEG, len_left);
1245                 if (pb > cbe_lun->blocksize) {
1246                         adj = ((lbalen->lba + lba) * cbe_lun->blocksize +
1247                             seglen - pbo) % pb;
1248                         if (seglen > adj)
1249                                 seglen -= adj;
1250                         else
1251                                 seglen -= seglen % cbe_lun->blocksize;
1252                 } else
1253                         seglen -= seglen % cbe_lun->blocksize;
1254                 beio->sg_segs[i].len = seglen;
1255                 beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1256
1257                 DPRINTF("segment %d addr %p len %zd\n", i,
1258                         beio->sg_segs[i].addr, beio->sg_segs[i].len);
1259
1260                 beio->num_segs++;
1261                 len_left -= seglen;
1262
1263                 buf = beio->sg_segs[i].addr;
1264                 end = buf + seglen;
1265                 for (; buf < end; buf += cbe_lun->blocksize) {
1266                         memcpy(buf, io->scsiio.kern_data_ptr, cbe_lun->blocksize);
1267                         if (lbalen->flags & SWS_LBDATA)
1268                                 scsi_ulto4b(lbalen->lba + lba, buf);
1269                         lba++;
1270                 }
1271         }
1272
1273         beio->io_offset = lbalen->lba * cbe_lun->blocksize;
1274         beio->io_len = lba * cbe_lun->blocksize;
1275
1276         /* We can not do all in one run. Correct and schedule rerun. */
1277         if (len_left > 0) {
1278                 lbalen->lba += lba;
1279                 lbalen->len -= lba;
1280                 beio->beio_cont = ctl_be_block_cw_done_ws;
1281         }
1282
1283         be_lun->dispatch(be_lun, beio);
1284 }
1285
1286 static void
1287 ctl_be_block_cw_dispatch_unmap(struct ctl_be_block_lun *be_lun,
1288                             union ctl_io *io)
1289 {
1290         struct ctl_be_block_io *beio;
1291         struct ctl_ptr_len_flags *ptrlen;
1292
1293         DPRINTF("entered\n");
1294
1295         beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1296         ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1297
1298         if ((ptrlen->flags & ~SU_ANCHOR) != 0 || be_lun->unmap == NULL) {
1299                 ctl_free_beio(beio);
1300                 ctl_set_invalid_field(&io->scsiio,
1301                                       /*sks_valid*/ 0,
1302                                       /*command*/ 1,
1303                                       /*field*/ 0,
1304                                       /*bit_valid*/ 0,
1305                                       /*bit*/ 0);
1306                 ctl_config_write_done(io);
1307                 return;
1308         }
1309
1310         beio->io_len = 0;
1311         beio->io_offset = -1;
1312         beio->bio_cmd = BIO_DELETE;
1313         beio->ds_trans_type = DEVSTAT_FREE;
1314         DPRINTF("UNMAP\n");
1315         be_lun->unmap(be_lun, beio);
1316 }
1317
1318 static void
1319 ctl_be_block_cr_done(struct ctl_be_block_io *beio)
1320 {
1321         union ctl_io *io;
1322
1323         io = beio->io;
1324         ctl_free_beio(beio);
1325         ctl_config_read_done(io);
1326 }
1327
1328 static void
1329 ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
1330                          union ctl_io *io)
1331 {
1332         struct ctl_be_block_io *beio;
1333         struct ctl_be_block_softc *softc;
1334
1335         DPRINTF("entered\n");
1336
1337         softc = be_lun->softc;
1338         beio = ctl_alloc_beio(softc);
1339         beio->io = io;
1340         beio->lun = be_lun;
1341         beio->beio_cont = ctl_be_block_cr_done;
1342         PRIV(io)->ptr = (void *)beio;
1343
1344         switch (io->scsiio.cdb[0]) {
1345         case SERVICE_ACTION_IN:         /* GET LBA STATUS */
1346                 beio->bio_cmd = -1;
1347                 beio->ds_trans_type = DEVSTAT_NO_DATA;
1348                 beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1349                 beio->io_len = 0;
1350                 if (be_lun->get_lba_status)
1351                         be_lun->get_lba_status(be_lun, beio);
1352                 else
1353                         ctl_be_block_cr_done(beio);
1354                 break;
1355         default:
1356                 panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1357                 break;
1358         }
1359 }
1360
1361 static void
1362 ctl_be_block_cw_done(struct ctl_be_block_io *beio)
1363 {
1364         union ctl_io *io;
1365
1366         io = beio->io;
1367         ctl_free_beio(beio);
1368         ctl_config_write_done(io);
1369 }
1370
1371 static void
1372 ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
1373                          union ctl_io *io)
1374 {
1375         struct ctl_be_block_io *beio;
1376         struct ctl_be_block_softc *softc;
1377
1378         DPRINTF("entered\n");
1379
1380         softc = be_lun->softc;
1381         beio = ctl_alloc_beio(softc);
1382         beio->io = io;
1383         beio->lun = be_lun;
1384         beio->beio_cont = ctl_be_block_cw_done;
1385         switch (io->scsiio.tag_type) {
1386         case CTL_TAG_ORDERED:
1387                 beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1388                 break;
1389         case CTL_TAG_HEAD_OF_QUEUE:
1390                 beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1391                 break;
1392         case CTL_TAG_UNTAGGED:
1393         case CTL_TAG_SIMPLE:
1394         case CTL_TAG_ACA:
1395         default:
1396                 beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1397                 break;
1398         }
1399         PRIV(io)->ptr = (void *)beio;
1400
1401         switch (io->scsiio.cdb[0]) {
1402         case SYNCHRONIZE_CACHE:
1403         case SYNCHRONIZE_CACHE_16:
1404                 ctl_be_block_cw_dispatch_sync(be_lun, io);
1405                 break;
1406         case WRITE_SAME_10:
1407         case WRITE_SAME_16:
1408                 ctl_be_block_cw_dispatch_ws(be_lun, io);
1409                 break;
1410         case UNMAP:
1411                 ctl_be_block_cw_dispatch_unmap(be_lun, io);
1412                 break;
1413         default:
1414                 panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1415                 break;
1416         }
1417 }
1418
1419 SDT_PROBE_DEFINE1(cbb, kernel, read, start, "uint64_t");
1420 SDT_PROBE_DEFINE1(cbb, kernel, write, start, "uint64_t");
1421 SDT_PROBE_DEFINE1(cbb, kernel, read, alloc_done, "uint64_t");
1422 SDT_PROBE_DEFINE1(cbb, kernel, write, alloc_done, "uint64_t");
1423
1424 static void
1425 ctl_be_block_next(struct ctl_be_block_io *beio)
1426 {
1427         struct ctl_be_block_lun *be_lun;
1428         union ctl_io *io;
1429
1430         io = beio->io;
1431         be_lun = beio->lun;
1432         ctl_free_beio(beio);
1433         if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1434             ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1435              (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1436                 ctl_data_submit_done(io);
1437                 return;
1438         }
1439
1440         io->io_hdr.status &= ~CTL_STATUS_MASK;
1441         io->io_hdr.status |= CTL_STATUS_NONE;
1442
1443         mtx_lock(&be_lun->queue_lock);
1444         /*
1445          * XXX KDM make sure that links is okay to use at this point.
1446          * Otherwise, we either need to add another field to ctl_io_hdr,
1447          * or deal with resource allocation here.
1448          */
1449         STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1450         mtx_unlock(&be_lun->queue_lock);
1451
1452         taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1453 }
1454
1455 static void
1456 ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
1457                            union ctl_io *io)
1458 {
1459         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
1460         struct ctl_be_block_io *beio;
1461         struct ctl_be_block_softc *softc;
1462         struct ctl_lba_len_flags *lbalen;
1463         struct ctl_ptr_len_flags *bptrlen;
1464         uint64_t len_left, lbas;
1465         int i;
1466
1467         softc = be_lun->softc;
1468
1469         DPRINTF("entered\n");
1470
1471         lbalen = ARGS(io);
1472         if (lbalen->flags & CTL_LLF_WRITE) {
1473                 SDT_PROBE(cbb, kernel, write, start, 0, 0, 0, 0, 0);
1474         } else {
1475                 SDT_PROBE(cbb, kernel, read, start, 0, 0, 0, 0, 0);
1476         }
1477
1478         beio = ctl_alloc_beio(softc);
1479         beio->io = io;
1480         beio->lun = be_lun;
1481         bptrlen = PRIV(io);
1482         bptrlen->ptr = (void *)beio;
1483
1484         switch (io->scsiio.tag_type) {
1485         case CTL_TAG_ORDERED:
1486                 beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1487                 break;
1488         case CTL_TAG_HEAD_OF_QUEUE:
1489                 beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1490                 break;
1491         case CTL_TAG_UNTAGGED:
1492         case CTL_TAG_SIMPLE:
1493         case CTL_TAG_ACA:
1494         default:
1495                 beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1496                 break;
1497         }
1498
1499         if (lbalen->flags & CTL_LLF_WRITE) {
1500                 beio->bio_cmd = BIO_WRITE;
1501                 beio->ds_trans_type = DEVSTAT_WRITE;
1502         } else {
1503                 beio->bio_cmd = BIO_READ;
1504                 beio->ds_trans_type = DEVSTAT_READ;
1505         }
1506
1507         DPRINTF("%s at LBA %jx len %u @%ju\n",
1508                (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE",
1509                (uintmax_t)lbalen->lba, lbalen->len, bptrlen->len);
1510         if (lbalen->flags & CTL_LLF_COMPARE)
1511                 lbas = CTLBLK_HALF_IO_SIZE;
1512         else
1513                 lbas = CTLBLK_MAX_IO_SIZE;
1514         lbas = MIN(lbalen->len - bptrlen->len, lbas / cbe_lun->blocksize);
1515         beio->io_offset = (lbalen->lba + bptrlen->len) * cbe_lun->blocksize;
1516         beio->io_len = lbas * cbe_lun->blocksize;
1517         bptrlen->len += lbas;
1518
1519         for (i = 0, len_left = beio->io_len; len_left > 0; i++) {
1520                 KASSERT(i < CTLBLK_MAX_SEGS, ("Too many segs (%d >= %d)",
1521                     i, CTLBLK_MAX_SEGS));
1522
1523                 /*
1524                  * Setup the S/G entry for this chunk.
1525                  */
1526                 beio->sg_segs[i].len = min(CTLBLK_MAX_SEG, len_left);
1527                 beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1528
1529                 DPRINTF("segment %d addr %p len %zd\n", i,
1530                         beio->sg_segs[i].addr, beio->sg_segs[i].len);
1531
1532                 /* Set up second segment for compare operation. */
1533                 if (lbalen->flags & CTL_LLF_COMPARE) {
1534                         beio->sg_segs[i + CTLBLK_HALF_SEGS].len =
1535                             beio->sg_segs[i].len;
1536                         beio->sg_segs[i + CTLBLK_HALF_SEGS].addr =
1537                             uma_zalloc(be_lun->lun_zone, M_WAITOK);
1538                 }
1539
1540                 beio->num_segs++;
1541                 len_left -= beio->sg_segs[i].len;
1542         }
1543         if (bptrlen->len < lbalen->len)
1544                 beio->beio_cont = ctl_be_block_next;
1545         io->scsiio.be_move_done = ctl_be_block_move_done;
1546         /* For compare we have separate S/G lists for read and datamove. */
1547         if (lbalen->flags & CTL_LLF_COMPARE)
1548                 io->scsiio.kern_data_ptr = (uint8_t *)&beio->sg_segs[CTLBLK_HALF_SEGS];
1549         else
1550                 io->scsiio.kern_data_ptr = (uint8_t *)beio->sg_segs;
1551         io->scsiio.kern_data_len = beio->io_len;
1552         io->scsiio.kern_data_resid = 0;
1553         io->scsiio.kern_sg_entries = beio->num_segs;
1554         io->io_hdr.flags |= CTL_FLAG_ALLOCATED | CTL_FLAG_KDPTR_SGLIST;
1555
1556         /*
1557          * For the read case, we need to read the data into our buffers and
1558          * then we can send it back to the user.  For the write case, we
1559          * need to get the data from the user first.
1560          */
1561         if (beio->bio_cmd == BIO_READ) {
1562                 SDT_PROBE(cbb, kernel, read, alloc_done, 0, 0, 0, 0, 0);
1563                 be_lun->dispatch(be_lun, beio);
1564         } else {
1565                 SDT_PROBE(cbb, kernel, write, alloc_done, 0, 0, 0, 0, 0);
1566 #ifdef CTL_TIME_IO
1567                 getbintime(&io->io_hdr.dma_start_bt);
1568 #endif  
1569                 ctl_datamove(io);
1570         }
1571 }
1572
1573 static void
1574 ctl_be_block_worker(void *context, int pending)
1575 {
1576         struct ctl_be_block_lun *be_lun;
1577         struct ctl_be_block_softc *softc;
1578         union ctl_io *io;
1579
1580         be_lun = (struct ctl_be_block_lun *)context;
1581         softc = be_lun->softc;
1582
1583         DPRINTF("entered\n");
1584
1585         mtx_lock(&be_lun->queue_lock);
1586         for (;;) {
1587                 io = (union ctl_io *)STAILQ_FIRST(&be_lun->datamove_queue);
1588                 if (io != NULL) {
1589                         struct ctl_be_block_io *beio;
1590
1591                         DPRINTF("datamove queue\n");
1592
1593                         STAILQ_REMOVE(&be_lun->datamove_queue, &io->io_hdr,
1594                                       ctl_io_hdr, links);
1595
1596                         mtx_unlock(&be_lun->queue_lock);
1597
1598                         beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1599
1600                         be_lun->dispatch(be_lun, beio);
1601
1602                         mtx_lock(&be_lun->queue_lock);
1603                         continue;
1604                 }
1605                 io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_write_queue);
1606                 if (io != NULL) {
1607                         DPRINTF("config write queue\n");
1608                         STAILQ_REMOVE(&be_lun->config_write_queue, &io->io_hdr,
1609                                       ctl_io_hdr, links);
1610                         mtx_unlock(&be_lun->queue_lock);
1611                         ctl_be_block_cw_dispatch(be_lun, io);
1612                         mtx_lock(&be_lun->queue_lock);
1613                         continue;
1614                 }
1615                 io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_read_queue);
1616                 if (io != NULL) {
1617                         DPRINTF("config read queue\n");
1618                         STAILQ_REMOVE(&be_lun->config_read_queue, &io->io_hdr,
1619                                       ctl_io_hdr, links);
1620                         mtx_unlock(&be_lun->queue_lock);
1621                         ctl_be_block_cr_dispatch(be_lun, io);
1622                         mtx_lock(&be_lun->queue_lock);
1623                         continue;
1624                 }
1625                 io = (union ctl_io *)STAILQ_FIRST(&be_lun->input_queue);
1626                 if (io != NULL) {
1627                         DPRINTF("input queue\n");
1628
1629                         STAILQ_REMOVE(&be_lun->input_queue, &io->io_hdr,
1630                                       ctl_io_hdr, links);
1631                         mtx_unlock(&be_lun->queue_lock);
1632
1633                         /*
1634                          * We must drop the lock, since this routine and
1635                          * its children may sleep.
1636                          */
1637                         ctl_be_block_dispatch(be_lun, io);
1638
1639                         mtx_lock(&be_lun->queue_lock);
1640                         continue;
1641                 }
1642
1643                 /*
1644                  * If we get here, there is no work left in the queues, so
1645                  * just break out and let the task queue go to sleep.
1646                  */
1647                 break;
1648         }
1649         mtx_unlock(&be_lun->queue_lock);
1650 }
1651
1652 /*
1653  * Entry point from CTL to the backend for I/O.  We queue everything to a
1654  * work thread, so this just puts the I/O on a queue and wakes up the
1655  * thread.
1656  */
1657 static int
1658 ctl_be_block_submit(union ctl_io *io)
1659 {
1660         struct ctl_be_block_lun *be_lun;
1661         struct ctl_be_lun *cbe_lun;
1662
1663         DPRINTF("entered\n");
1664
1665         cbe_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
1666                 CTL_PRIV_BACKEND_LUN].ptr;
1667         be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;
1668
1669         /*
1670          * Make sure we only get SCSI I/O.
1671          */
1672         KASSERT(io->io_hdr.io_type == CTL_IO_SCSI, ("Non-SCSI I/O (type "
1673                 "%#x) encountered", io->io_hdr.io_type));
1674
1675         PRIV(io)->len = 0;
1676
1677         mtx_lock(&be_lun->queue_lock);
1678         /*
1679          * XXX KDM make sure that links is okay to use at this point.
1680          * Otherwise, we either need to add another field to ctl_io_hdr,
1681          * or deal with resource allocation here.
1682          */
1683         STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1684         mtx_unlock(&be_lun->queue_lock);
1685         taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1686
1687         return (CTL_RETVAL_COMPLETE);
1688 }
1689
1690 static int
1691 ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
1692                         int flag, struct thread *td)
1693 {
1694         struct ctl_be_block_softc *softc;
1695         int error;
1696
1697         softc = &backend_block_softc;
1698
1699         error = 0;
1700
1701         switch (cmd) {
1702         case CTL_LUN_REQ: {
1703                 struct ctl_lun_req *lun_req;
1704
1705                 lun_req = (struct ctl_lun_req *)addr;
1706
1707                 switch (lun_req->reqtype) {
1708                 case CTL_LUNREQ_CREATE:
1709                         error = ctl_be_block_create(softc, lun_req);
1710                         break;
1711                 case CTL_LUNREQ_RM:
1712                         error = ctl_be_block_rm(softc, lun_req);
1713                         break;
1714                 case CTL_LUNREQ_MODIFY:
1715                         error = ctl_be_block_modify(softc, lun_req);
1716                         break;
1717                 default:
1718                         lun_req->status = CTL_LUN_ERROR;
1719                         snprintf(lun_req->error_str, sizeof(lun_req->error_str),
1720                                  "invalid LUN request type %d",
1721                                  lun_req->reqtype);
1722                         break;
1723                 }
1724                 break;
1725         }
1726         default:
1727                 error = ENOTTY;
1728                 break;
1729         }
1730
1731         return (error);
1732 }
1733
1734 static int
1735 ctl_be_block_open_file(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1736 {
1737         struct ctl_be_lun *cbe_lun;
1738         struct ctl_be_block_filedata *file_data;
1739         struct ctl_lun_create_params *params;
1740         char                         *value;
1741         struct vattr                  vattr;
1742         off_t                         ps, pss, po, pos, us, uss, uo, uos;
1743         int                           error;
1744
1745         error = 0;
1746         cbe_lun = &be_lun->cbe_lun;
1747         file_data = &be_lun->backend.file;
1748         params = &be_lun->params;
1749
1750         be_lun->dev_type = CTL_BE_BLOCK_FILE;
1751         be_lun->dispatch = ctl_be_block_dispatch_file;
1752         be_lun->lun_flush = ctl_be_block_flush_file;
1753         be_lun->get_lba_status = ctl_be_block_gls_file;
1754         be_lun->getattr = ctl_be_block_getattr_file;
1755         be_lun->unmap = NULL;
1756         cbe_lun->flags &= ~CTL_LUN_FLAG_UNMAP;
1757
1758         error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
1759         if (error != 0) {
1760                 snprintf(req->error_str, sizeof(req->error_str),
1761                          "error calling VOP_GETATTR() for file %s",
1762                          be_lun->dev_path);
1763                 return (error);
1764         }
1765
1766         /*
1767          * Verify that we have the ability to upgrade to exclusive
1768          * access on this file so we can trap errors at open instead
1769          * of reporting them during first access.
1770          */
1771         if (VOP_ISLOCKED(be_lun->vn) != LK_EXCLUSIVE) {
1772                 vn_lock(be_lun->vn, LK_UPGRADE | LK_RETRY);
1773                 if (be_lun->vn->v_iflag & VI_DOOMED) {
1774                         error = EBADF;
1775                         snprintf(req->error_str, sizeof(req->error_str),
1776                                  "error locking file %s", be_lun->dev_path);
1777                         return (error);
1778                 }
1779         }
1780
1781         file_data->cred = crhold(curthread->td_ucred);
1782         if (params->lun_size_bytes != 0)
1783                 be_lun->size_bytes = params->lun_size_bytes;
1784         else
1785                 be_lun->size_bytes = vattr.va_size;
1786
1787         /*
1788          * For files we can use any logical block size.  Prefer 512 bytes
1789          * for compatibility reasons.  If file's vattr.va_blocksize
1790          * (preferred I/O block size) is bigger and multiple to chosen
1791          * logical block size -- report it as physical block size.
1792          */
1793         if (params->blocksize_bytes != 0)
1794                 cbe_lun->blocksize = params->blocksize_bytes;
1795         else
1796                 cbe_lun->blocksize = 512;
1797         be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
1798         cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
1799             0 : (be_lun->size_blocks - 1);
1800
1801         us = ps = vattr.va_blocksize;
1802         uo = po = 0;
1803
1804         value = ctl_get_opt(&cbe_lun->options, "pblocksize");
1805         if (value != NULL)
1806                 ctl_expand_number(value, &ps);
1807         value = ctl_get_opt(&cbe_lun->options, "pblockoffset");
1808         if (value != NULL)
1809                 ctl_expand_number(value, &po);
1810         pss = ps / cbe_lun->blocksize;
1811         pos = po / cbe_lun->blocksize;
1812         if ((pss > 0) && (pss * cbe_lun->blocksize == ps) && (pss >= pos) &&
1813             ((pss & (pss - 1)) == 0) && (pos * cbe_lun->blocksize == po)) {
1814                 cbe_lun->pblockexp = fls(pss) - 1;
1815                 cbe_lun->pblockoff = (pss - pos) % pss;
1816         }
1817
1818         value = ctl_get_opt(&cbe_lun->options, "ublocksize");
1819         if (value != NULL)
1820                 ctl_expand_number(value, &us);
1821         value = ctl_get_opt(&cbe_lun->options, "ublockoffset");
1822         if (value != NULL)
1823                 ctl_expand_number(value, &uo);
1824         uss = us / cbe_lun->blocksize;
1825         uos = uo / cbe_lun->blocksize;
1826         if ((uss > 0) && (uss * cbe_lun->blocksize == us) && (uss >= uos) &&
1827             ((uss & (uss - 1)) == 0) && (uos * cbe_lun->blocksize == uo)) {
1828                 cbe_lun->ublockexp = fls(uss) - 1;
1829                 cbe_lun->ublockoff = (uss - uos) % uss;
1830         }
1831
1832         /*
1833          * Sanity check.  The media size has to be at least one
1834          * sector long.
1835          */
1836         if (be_lun->size_bytes < cbe_lun->blocksize) {
1837                 error = EINVAL;
1838                 snprintf(req->error_str, sizeof(req->error_str),
1839                          "file %s size %ju < block size %u", be_lun->dev_path,
1840                          (uintmax_t)be_lun->size_bytes, cbe_lun->blocksize);
1841         }
1842
1843         cbe_lun->opttxferlen = CTLBLK_MAX_IO_SIZE / cbe_lun->blocksize;
1844         return (error);
1845 }
1846
1847 static int
1848 ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1849 {
1850         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
1851         struct ctl_lun_create_params *params;
1852         struct vattr                  vattr;
1853         struct cdev                  *dev;
1854         struct cdevsw                *devsw;
1855         char                         *value;
1856         int                           error, atomic, maxio, unmap, tmp;
1857         off_t                         ps, pss, po, pos, us, uss, uo, uos, otmp;
1858
1859         params = &be_lun->params;
1860
1861         be_lun->dev_type = CTL_BE_BLOCK_DEV;
1862         be_lun->backend.dev.cdev = be_lun->vn->v_rdev;
1863         be_lun->backend.dev.csw = dev_refthread(be_lun->backend.dev.cdev,
1864                                              &be_lun->backend.dev.dev_ref);
1865         if (be_lun->backend.dev.csw == NULL)
1866                 panic("Unable to retrieve device switch");
1867         if (strcmp(be_lun->backend.dev.csw->d_name, "zvol") == 0) {
1868                 be_lun->dispatch = ctl_be_block_dispatch_zvol;
1869                 be_lun->get_lba_status = ctl_be_block_gls_zvol;
1870                 atomic = maxio = CTLBLK_MAX_IO_SIZE;
1871         } else {
1872                 be_lun->dispatch = ctl_be_block_dispatch_dev;
1873                 be_lun->get_lba_status = NULL;
1874                 atomic = 0;
1875                 maxio = be_lun->backend.dev.cdev->si_iosize_max;
1876                 if (maxio <= 0)
1877                         maxio = DFLTPHYS;
1878                 if (maxio > CTLBLK_MAX_IO_SIZE)
1879                         maxio = CTLBLK_MAX_IO_SIZE;
1880         }
1881         be_lun->lun_flush = ctl_be_block_flush_dev;
1882         be_lun->getattr = ctl_be_block_getattr_dev;
1883         be_lun->unmap = ctl_be_block_unmap_dev;
1884
1885         error = VOP_GETATTR(be_lun->vn, &vattr, NOCRED);
1886         if (error) {
1887                 snprintf(req->error_str, sizeof(req->error_str),
1888                          "error getting vnode attributes for device %s",
1889                          be_lun->dev_path);
1890                 return (error);
1891         }
1892
1893         dev = be_lun->vn->v_rdev;
1894         devsw = dev->si_devsw;
1895         if (!devsw->d_ioctl) {
1896                 snprintf(req->error_str, sizeof(req->error_str),
1897                          "no d_ioctl for device %s!",
1898                          be_lun->dev_path);
1899                 return (ENODEV);
1900         }
1901
1902         error = devsw->d_ioctl(dev, DIOCGSECTORSIZE, (caddr_t)&tmp, FREAD,
1903                                curthread);
1904         if (error) {
1905                 snprintf(req->error_str, sizeof(req->error_str),
1906                          "error %d returned for DIOCGSECTORSIZE ioctl "
1907                          "on %s!", error, be_lun->dev_path);
1908                 return (error);
1909         }
1910
1911         /*
1912          * If the user has asked for a blocksize that is greater than the
1913          * backing device's blocksize, we can do it only if the blocksize
1914          * the user is asking for is an even multiple of the underlying 
1915          * device's blocksize.
1916          */
1917         if ((params->blocksize_bytes != 0) &&
1918             (params->blocksize_bytes >= tmp)) {
1919                 if (params->blocksize_bytes % tmp == 0) {
1920                         cbe_lun->blocksize = params->blocksize_bytes;
1921                 } else {
1922                         snprintf(req->error_str, sizeof(req->error_str),
1923                                  "requested blocksize %u is not an even "
1924                                  "multiple of backing device blocksize %u",
1925                                  params->blocksize_bytes, tmp);
1926                         return (EINVAL);
1927                         
1928                 }
1929         } else if (params->blocksize_bytes != 0) {
1930                 snprintf(req->error_str, sizeof(req->error_str),
1931                          "requested blocksize %u < backing device "
1932                          "blocksize %u", params->blocksize_bytes, tmp);
1933                 return (EINVAL);
1934         } else
1935                 cbe_lun->blocksize = tmp;
1936
1937         error = devsw->d_ioctl(dev, DIOCGMEDIASIZE, (caddr_t)&otmp, FREAD,
1938                                curthread);
1939         if (error) {
1940                 snprintf(req->error_str, sizeof(req->error_str),
1941                          "error %d returned for DIOCGMEDIASIZE "
1942                          " ioctl on %s!", error,
1943                          be_lun->dev_path);
1944                 return (error);
1945         }
1946
1947         if (params->lun_size_bytes != 0) {
1948                 if (params->lun_size_bytes > otmp) {
1949                         snprintf(req->error_str, sizeof(req->error_str),
1950                                  "requested LUN size %ju > backing device "
1951                                  "size %ju",
1952                                  (uintmax_t)params->lun_size_bytes,
1953                                  (uintmax_t)otmp);
1954                         return (EINVAL);
1955                 }
1956
1957                 be_lun->size_bytes = params->lun_size_bytes;
1958         } else
1959                 be_lun->size_bytes = otmp;
1960         be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
1961         cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
1962             0 : (be_lun->size_blocks - 1);
1963
1964         error = devsw->d_ioctl(dev, DIOCGSTRIPESIZE,
1965                                (caddr_t)&ps, FREAD, curthread);
1966         if (error)
1967                 ps = po = 0;
1968         else {
1969                 error = devsw->d_ioctl(dev, DIOCGSTRIPEOFFSET,
1970                                        (caddr_t)&po, FREAD, curthread);
1971                 if (error)
1972                         po = 0;
1973         }
1974         us = ps;
1975         uo = po;
1976
1977         value = ctl_get_opt(&cbe_lun->options, "pblocksize");
1978         if (value != NULL)
1979                 ctl_expand_number(value, &ps);
1980         value = ctl_get_opt(&cbe_lun->options, "pblockoffset");
1981         if (value != NULL)
1982                 ctl_expand_number(value, &po);
1983         pss = ps / cbe_lun->blocksize;
1984         pos = po / cbe_lun->blocksize;
1985         if ((pss > 0) && (pss * cbe_lun->blocksize == ps) && (pss >= pos) &&
1986             ((pss & (pss - 1)) == 0) && (pos * cbe_lun->blocksize == po)) {
1987                 cbe_lun->pblockexp = fls(pss) - 1;
1988                 cbe_lun->pblockoff = (pss - pos) % pss;
1989         }
1990
1991         value = ctl_get_opt(&cbe_lun->options, "ublocksize");
1992         if (value != NULL)
1993                 ctl_expand_number(value, &us);
1994         value = ctl_get_opt(&cbe_lun->options, "ublockoffset");
1995         if (value != NULL)
1996                 ctl_expand_number(value, &uo);
1997         uss = us / cbe_lun->blocksize;
1998         uos = uo / cbe_lun->blocksize;
1999         if ((uss > 0) && (uss * cbe_lun->blocksize == us) && (uss >= uos) &&
2000             ((uss & (uss - 1)) == 0) && (uos * cbe_lun->blocksize == uo)) {
2001                 cbe_lun->ublockexp = fls(uss) - 1;
2002                 cbe_lun->ublockoff = (uss - uos) % uss;
2003         }
2004
2005         cbe_lun->atomicblock = atomic / cbe_lun->blocksize;
2006         cbe_lun->opttxferlen = maxio / cbe_lun->blocksize;
2007
2008         if (be_lun->dispatch == ctl_be_block_dispatch_zvol) {
2009                 unmap = 1;
2010         } else {
2011                 struct diocgattr_arg    arg;
2012
2013                 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
2014                 arg.len = sizeof(arg.value.i);
2015                 error = devsw->d_ioctl(dev, DIOCGATTR,
2016                     (caddr_t)&arg, FREAD, curthread);
2017                 unmap = (error == 0) ? arg.value.i : 0;
2018         }
2019         value = ctl_get_opt(&cbe_lun->options, "unmap");
2020         if (value != NULL)
2021                 unmap = (strcmp(value, "on") == 0);
2022         if (unmap)
2023                 cbe_lun->flags |= CTL_LUN_FLAG_UNMAP;
2024         else
2025                 cbe_lun->flags &= ~CTL_LUN_FLAG_UNMAP;
2026
2027         return (0);
2028 }
2029
2030 static int
2031 ctl_be_block_close(struct ctl_be_block_lun *be_lun)
2032 {
2033         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
2034         int flags;
2035
2036         if (be_lun->vn) {
2037                 switch (be_lun->dev_type) {
2038                 case CTL_BE_BLOCK_DEV:
2039                         if (be_lun->backend.dev.csw) {
2040                                 dev_relthread(be_lun->backend.dev.cdev,
2041                                               be_lun->backend.dev.dev_ref);
2042                                 be_lun->backend.dev.csw  = NULL;
2043                                 be_lun->backend.dev.cdev = NULL;
2044                         }
2045                         break;
2046                 case CTL_BE_BLOCK_FILE:
2047                         break;
2048                 case CTL_BE_BLOCK_NONE:
2049                         break;
2050                 default:
2051                         panic("Unexpected backend type.");
2052                         break;
2053                 }
2054
2055                 flags = FREAD;
2056                 if ((cbe_lun->flags & CTL_LUN_FLAG_READONLY) == 0)
2057                         flags |= FWRITE;
2058                 (void)vn_close(be_lun->vn, flags, NOCRED, curthread);
2059                 be_lun->vn = NULL;
2060
2061                 switch (be_lun->dev_type) {
2062                 case CTL_BE_BLOCK_DEV:
2063                         break;
2064                 case CTL_BE_BLOCK_FILE:
2065                         if (be_lun->backend.file.cred != NULL) {
2066                                 crfree(be_lun->backend.file.cred);
2067                                 be_lun->backend.file.cred = NULL;
2068                         }
2069                         break;
2070                 case CTL_BE_BLOCK_NONE:
2071                         break;
2072                 default:
2073                         panic("Unexpected backend type.");
2074                         break;
2075                 }
2076                 be_lun->dev_type = CTL_BE_BLOCK_NONE;
2077         }
2078         return (0);
2079 }
2080
2081 static int
2082 ctl_be_block_open(struct ctl_be_block_softc *softc,
2083                   struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
2084 {
2085         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
2086         struct nameidata nd;
2087         char            *value;
2088         int              error, flags;
2089
2090         error = 0;
2091         if (rootvnode == NULL) {
2092                 snprintf(req->error_str, sizeof(req->error_str),
2093                          "Root filesystem is not mounted");
2094                 return (1);
2095         }
2096         pwd_ensure_dirs();
2097
2098         value = ctl_get_opt(&cbe_lun->options, "file");
2099         if (value == NULL) {
2100                 snprintf(req->error_str, sizeof(req->error_str),
2101                          "no file argument specified");
2102                 return (1);
2103         }
2104         free(be_lun->dev_path, M_CTLBLK);
2105         be_lun->dev_path = strdup(value, M_CTLBLK);
2106
2107         flags = FREAD;
2108         value = ctl_get_opt(&cbe_lun->options, "readonly");
2109         if (value == NULL || strcmp(value, "on") != 0)
2110                 flags |= FWRITE;
2111
2112 again:
2113         NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, be_lun->dev_path, curthread);
2114         error = vn_open(&nd, &flags, 0, NULL);
2115         if ((error == EROFS || error == EACCES) && (flags & FWRITE)) {
2116                 flags &= ~FWRITE;
2117                 goto again;
2118         }
2119         if (error) {
2120                 /*
2121                  * This is the only reasonable guess we can make as far as
2122                  * path if the user doesn't give us a fully qualified path.
2123                  * If they want to specify a file, they need to specify the
2124                  * full path.
2125                  */
2126                 if (be_lun->dev_path[0] != '/') {
2127                         char *dev_name;
2128
2129                         asprintf(&dev_name, M_CTLBLK, "/dev/%s",
2130                                 be_lun->dev_path);
2131                         free(be_lun->dev_path, M_CTLBLK);
2132                         be_lun->dev_path = dev_name;
2133                         goto again;
2134                 }
2135                 snprintf(req->error_str, sizeof(req->error_str),
2136                     "error opening %s: %d", be_lun->dev_path, error);
2137                 return (error);
2138         }
2139         if (flags & FWRITE)
2140                 cbe_lun->flags &= ~CTL_LUN_FLAG_READONLY;
2141         else
2142                 cbe_lun->flags |= CTL_LUN_FLAG_READONLY;
2143
2144         NDFREE(&nd, NDF_ONLY_PNBUF);
2145         be_lun->vn = nd.ni_vp;
2146
2147         /* We only support disks and files. */
2148         if (vn_isdisk(be_lun->vn, &error)) {
2149                 error = ctl_be_block_open_dev(be_lun, req);
2150         } else if (be_lun->vn->v_type == VREG) {
2151                 error = ctl_be_block_open_file(be_lun, req);
2152         } else {
2153                 error = EINVAL;
2154                 snprintf(req->error_str, sizeof(req->error_str),
2155                          "%s is not a disk or plain file", be_lun->dev_path);
2156         }
2157         VOP_UNLOCK(be_lun->vn, 0);
2158
2159         if (error != 0)
2160                 ctl_be_block_close(be_lun);
2161         cbe_lun->serseq = CTL_LUN_SERSEQ_OFF;
2162         if (be_lun->dispatch != ctl_be_block_dispatch_dev)
2163                 cbe_lun->serseq = CTL_LUN_SERSEQ_READ;
2164         value = ctl_get_opt(&cbe_lun->options, "serseq");
2165         if (value != NULL && strcmp(value, "on") == 0)
2166                 cbe_lun->serseq = CTL_LUN_SERSEQ_ON;
2167         else if (value != NULL && strcmp(value, "read") == 0)
2168                 cbe_lun->serseq = CTL_LUN_SERSEQ_READ;
2169         else if (value != NULL && strcmp(value, "off") == 0)
2170                 cbe_lun->serseq = CTL_LUN_SERSEQ_OFF;
2171         return (0);
2172 }
2173
2174 static int
2175 ctl_be_block_create(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2176 {
2177         struct ctl_be_lun *cbe_lun;
2178         struct ctl_be_block_lun *be_lun;
2179         struct ctl_lun_create_params *params;
2180         char num_thread_str[16];
2181         char tmpstr[32];
2182         char *value;
2183         int retval, num_threads;
2184         int tmp_num_threads;
2185
2186         params = &req->reqdata.create;
2187         retval = 0;
2188         req->status = CTL_LUN_OK;
2189
2190         be_lun = malloc(sizeof(*be_lun), M_CTLBLK, M_ZERO | M_WAITOK);
2191         cbe_lun = &be_lun->cbe_lun;
2192         cbe_lun->be_lun = be_lun;
2193         be_lun->params = req->reqdata.create;
2194         be_lun->softc = softc;
2195         STAILQ_INIT(&be_lun->input_queue);
2196         STAILQ_INIT(&be_lun->config_read_queue);
2197         STAILQ_INIT(&be_lun->config_write_queue);
2198         STAILQ_INIT(&be_lun->datamove_queue);
2199         sprintf(be_lun->lunname, "cblk%d", softc->num_luns);
2200         mtx_init(&be_lun->io_lock, "cblk io lock", NULL, MTX_DEF);
2201         mtx_init(&be_lun->queue_lock, "cblk queue lock", NULL, MTX_DEF);
2202         ctl_init_opts(&cbe_lun->options,
2203             req->num_be_args, req->kern_be_args);
2204         be_lun->lun_zone = uma_zcreate(be_lun->lunname, CTLBLK_MAX_SEG,
2205             NULL, NULL, NULL, NULL, /*align*/ 0, /*flags*/0);
2206         if (be_lun->lun_zone == NULL) {
2207                 snprintf(req->error_str, sizeof(req->error_str),
2208                          "error allocating UMA zone");
2209                 goto bailout_error;
2210         }
2211
2212         if (params->flags & CTL_LUN_FLAG_DEV_TYPE)
2213                 cbe_lun->lun_type = params->device_type;
2214         else
2215                 cbe_lun->lun_type = T_DIRECT;
2216         be_lun->flags = CTL_BE_BLOCK_LUN_UNCONFIGURED;
2217         cbe_lun->flags = CTL_LUN_FLAG_PRIMARY;
2218
2219         if (cbe_lun->lun_type == T_DIRECT) {
2220                 be_lun->size_bytes = params->lun_size_bytes;
2221                 if (params->blocksize_bytes != 0)
2222                         cbe_lun->blocksize = params->blocksize_bytes;
2223                 else
2224                         cbe_lun->blocksize = 512;
2225                 be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
2226                 cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
2227                     0 : (be_lun->size_blocks - 1);
2228
2229                 retval = ctl_be_block_open(softc, be_lun, req);
2230                 if (retval != 0) {
2231                         retval = 0;
2232                         req->status = CTL_LUN_WARNING;
2233                 }
2234                 num_threads = cbb_num_threads;
2235         } else {
2236                 num_threads = 1;
2237         }
2238
2239         /*
2240          * XXX This searching loop might be refactored to be combined with
2241          * the loop above,
2242          */
2243         value = ctl_get_opt(&cbe_lun->options, "num_threads");
2244         if (value != NULL) {
2245                 tmp_num_threads = strtol(value, NULL, 0);
2246
2247                 /*
2248                  * We don't let the user specify less than one
2249                  * thread, but hope he's clueful enough not to
2250                  * specify 1000 threads.
2251                  */
2252                 if (tmp_num_threads < 1) {
2253                         snprintf(req->error_str, sizeof(req->error_str),
2254                                  "invalid number of threads %s",
2255                                  num_thread_str);
2256                         goto bailout_error;
2257                 }
2258                 num_threads = tmp_num_threads;
2259         }
2260
2261         if (be_lun->vn == NULL)
2262                 cbe_lun->flags |= CTL_LUN_FLAG_OFFLINE;
2263         /* Tell the user the blocksize we ended up using */
2264         params->lun_size_bytes = be_lun->size_bytes;
2265         params->blocksize_bytes = cbe_lun->blocksize;
2266         if (params->flags & CTL_LUN_FLAG_ID_REQ) {
2267                 cbe_lun->req_lun_id = params->req_lun_id;
2268                 cbe_lun->flags |= CTL_LUN_FLAG_ID_REQ;
2269         } else
2270                 cbe_lun->req_lun_id = 0;
2271
2272         cbe_lun->lun_shutdown = ctl_be_block_lun_shutdown;
2273         cbe_lun->lun_config_status = ctl_be_block_lun_config_status;
2274         cbe_lun->be = &ctl_be_block_driver;
2275
2276         if ((params->flags & CTL_LUN_FLAG_SERIAL_NUM) == 0) {
2277                 snprintf(tmpstr, sizeof(tmpstr), "MYSERIAL%4d",
2278                          softc->num_luns);
2279                 strncpy((char *)cbe_lun->serial_num, tmpstr,
2280                         MIN(sizeof(cbe_lun->serial_num), sizeof(tmpstr)));
2281
2282                 /* Tell the user what we used for a serial number */
2283                 strncpy((char *)params->serial_num, tmpstr,
2284                         MIN(sizeof(params->serial_num), sizeof(tmpstr)));
2285         } else { 
2286                 strncpy((char *)cbe_lun->serial_num, params->serial_num,
2287                         MIN(sizeof(cbe_lun->serial_num),
2288                         sizeof(params->serial_num)));
2289         }
2290         if ((params->flags & CTL_LUN_FLAG_DEVID) == 0) {
2291                 snprintf(tmpstr, sizeof(tmpstr), "MYDEVID%4d", softc->num_luns);
2292                 strncpy((char *)cbe_lun->device_id, tmpstr,
2293                         MIN(sizeof(cbe_lun->device_id), sizeof(tmpstr)));
2294
2295                 /* Tell the user what we used for a device ID */
2296                 strncpy((char *)params->device_id, tmpstr,
2297                         MIN(sizeof(params->device_id), sizeof(tmpstr)));
2298         } else {
2299                 strncpy((char *)cbe_lun->device_id, params->device_id,
2300                         MIN(sizeof(cbe_lun->device_id),
2301                             sizeof(params->device_id)));
2302         }
2303
2304         TASK_INIT(&be_lun->io_task, /*priority*/0, ctl_be_block_worker, be_lun);
2305
2306         be_lun->io_taskqueue = taskqueue_create(be_lun->lunname, M_WAITOK,
2307             taskqueue_thread_enqueue, /*context*/&be_lun->io_taskqueue);
2308
2309         if (be_lun->io_taskqueue == NULL) {
2310                 snprintf(req->error_str, sizeof(req->error_str),
2311                          "unable to create taskqueue");
2312                 goto bailout_error;
2313         }
2314
2315         /*
2316          * Note that we start the same number of threads by default for
2317          * both the file case and the block device case.  For the file
2318          * case, we need multiple threads to allow concurrency, because the
2319          * vnode interface is designed to be a blocking interface.  For the
2320          * block device case, ZFS zvols at least will block the caller's
2321          * context in many instances, and so we need multiple threads to
2322          * overcome that problem.  Other block devices don't need as many
2323          * threads, but they shouldn't cause too many problems.
2324          *
2325          * If the user wants to just have a single thread for a block
2326          * device, he can specify that when the LUN is created, or change
2327          * the tunable/sysctl to alter the default number of threads.
2328          */
2329         retval = taskqueue_start_threads(&be_lun->io_taskqueue,
2330                                          /*num threads*/num_threads,
2331                                          /*priority*/PWAIT,
2332                                          /*thread name*/
2333                                          "%s taskq", be_lun->lunname);
2334
2335         if (retval != 0)
2336                 goto bailout_error;
2337
2338         be_lun->num_threads = num_threads;
2339
2340         mtx_lock(&softc->lock);
2341         softc->num_luns++;
2342         STAILQ_INSERT_TAIL(&softc->lun_list, be_lun, links);
2343
2344         mtx_unlock(&softc->lock);
2345
2346         retval = ctl_add_lun(&be_lun->cbe_lun);
2347         if (retval != 0) {
2348                 mtx_lock(&softc->lock);
2349                 STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2350                               links);
2351                 softc->num_luns--;
2352                 mtx_unlock(&softc->lock);
2353                 snprintf(req->error_str, sizeof(req->error_str),
2354                          "ctl_add_lun() returned error %d, see dmesg for "
2355                          "details", retval);
2356                 retval = 0;
2357                 goto bailout_error;
2358         }
2359
2360         mtx_lock(&softc->lock);
2361
2362         /*
2363          * Tell the config_status routine that we're waiting so it won't
2364          * clean up the LUN in the event of an error.
2365          */
2366         be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2367
2368         while (be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) {
2369                 retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2370                 if (retval == EINTR)
2371                         break;
2372         }
2373         be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2374
2375         if (be_lun->flags & CTL_BE_BLOCK_LUN_CONFIG_ERR) {
2376                 snprintf(req->error_str, sizeof(req->error_str),
2377                          "LUN configuration error, see dmesg for details");
2378                 STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2379                               links);
2380                 softc->num_luns--;
2381                 mtx_unlock(&softc->lock);
2382                 goto bailout_error;
2383         } else {
2384                 params->req_lun_id = cbe_lun->lun_id;
2385         }
2386
2387         mtx_unlock(&softc->lock);
2388
2389         be_lun->disk_stats = devstat_new_entry("cbb", params->req_lun_id,
2390                                                cbe_lun->blocksize,
2391                                                DEVSTAT_ALL_SUPPORTED,
2392                                                cbe_lun->lun_type
2393                                                | DEVSTAT_TYPE_IF_OTHER,
2394                                                DEVSTAT_PRIORITY_OTHER);
2395
2396         return (retval);
2397
2398 bailout_error:
2399         req->status = CTL_LUN_ERROR;
2400
2401         if (be_lun->io_taskqueue != NULL)
2402                 taskqueue_free(be_lun->io_taskqueue);
2403         ctl_be_block_close(be_lun);
2404         if (be_lun->dev_path != NULL)
2405                 free(be_lun->dev_path, M_CTLBLK);
2406         if (be_lun->lun_zone != NULL)
2407                 uma_zdestroy(be_lun->lun_zone);
2408         ctl_free_opts(&cbe_lun->options);
2409         mtx_destroy(&be_lun->queue_lock);
2410         mtx_destroy(&be_lun->io_lock);
2411         free(be_lun, M_CTLBLK);
2412
2413         return (retval);
2414 }
2415
2416 static int
2417 ctl_be_block_rm(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2418 {
2419         struct ctl_lun_rm_params *params;
2420         struct ctl_be_block_lun *be_lun;
2421         int retval;
2422
2423         params = &req->reqdata.rm;
2424
2425         mtx_lock(&softc->lock);
2426
2427         be_lun = NULL;
2428
2429         STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2430                 if (be_lun->cbe_lun.lun_id == params->lun_id)
2431                         break;
2432         }
2433         mtx_unlock(&softc->lock);
2434
2435         if (be_lun == NULL) {
2436                 snprintf(req->error_str, sizeof(req->error_str),
2437                          "LUN %u is not managed by the block backend",
2438                          params->lun_id);
2439                 goto bailout_error;
2440         }
2441
2442         retval = ctl_disable_lun(&be_lun->cbe_lun);
2443
2444         if (retval != 0) {
2445                 snprintf(req->error_str, sizeof(req->error_str),
2446                          "error %d returned from ctl_disable_lun() for "
2447                          "LUN %d", retval, params->lun_id);
2448                 goto bailout_error;
2449
2450         }
2451
2452         retval = ctl_invalidate_lun(&be_lun->cbe_lun);
2453         if (retval != 0) {
2454                 snprintf(req->error_str, sizeof(req->error_str),
2455                          "error %d returned from ctl_invalidate_lun() for "
2456                          "LUN %d", retval, params->lun_id);
2457                 goto bailout_error;
2458         }
2459
2460         mtx_lock(&softc->lock);
2461
2462         be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2463
2464         while ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2465                 retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2466                 if (retval == EINTR)
2467                         break;
2468         }
2469
2470         be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2471
2472         if ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2473                 snprintf(req->error_str, sizeof(req->error_str),
2474                          "interrupted waiting for LUN to be freed");
2475                 mtx_unlock(&softc->lock);
2476                 goto bailout_error;
2477         }
2478
2479         STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun, links);
2480
2481         softc->num_luns--;
2482         mtx_unlock(&softc->lock);
2483
2484         taskqueue_drain(be_lun->io_taskqueue, &be_lun->io_task);
2485
2486         taskqueue_free(be_lun->io_taskqueue);
2487
2488         ctl_be_block_close(be_lun);
2489
2490         if (be_lun->disk_stats != NULL)
2491                 devstat_remove_entry(be_lun->disk_stats);
2492
2493         uma_zdestroy(be_lun->lun_zone);
2494
2495         ctl_free_opts(&be_lun->cbe_lun.options);
2496         free(be_lun->dev_path, M_CTLBLK);
2497         mtx_destroy(&be_lun->queue_lock);
2498         mtx_destroy(&be_lun->io_lock);
2499         free(be_lun, M_CTLBLK);
2500
2501         req->status = CTL_LUN_OK;
2502
2503         return (0);
2504
2505 bailout_error:
2506
2507         req->status = CTL_LUN_ERROR;
2508
2509         return (0);
2510 }
2511
2512 static int
2513 ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
2514                          struct ctl_lun_req *req)
2515 {
2516         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
2517         struct vattr vattr;
2518         int error;
2519         struct ctl_lun_create_params *params = &be_lun->params;
2520
2521         if (params->lun_size_bytes != 0) {
2522                 be_lun->size_bytes = params->lun_size_bytes;
2523         } else  {
2524                 vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
2525                 error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
2526                 VOP_UNLOCK(be_lun->vn, 0);
2527                 if (error != 0) {
2528                         snprintf(req->error_str, sizeof(req->error_str),
2529                                  "error calling VOP_GETATTR() for file %s",
2530                                  be_lun->dev_path);
2531                         return (error);
2532                 }
2533                 be_lun->size_bytes = vattr.va_size;
2534         }
2535         be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
2536         cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
2537             0 : (be_lun->size_blocks - 1);
2538         return (0);
2539 }
2540
2541 static int
2542 ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
2543                         struct ctl_lun_req *req)
2544 {
2545         struct ctl_be_lun *cbe_lun = &be_lun->cbe_lun;
2546         struct ctl_be_block_devdata *dev_data;
2547         int error;
2548         struct ctl_lun_create_params *params = &be_lun->params;
2549         uint64_t size_bytes;
2550
2551         dev_data = &be_lun->backend.dev;
2552         if (!dev_data->csw->d_ioctl) {
2553                 snprintf(req->error_str, sizeof(req->error_str),
2554                          "no d_ioctl for device %s!", be_lun->dev_path);
2555                 return (ENODEV);
2556         }
2557
2558         error = dev_data->csw->d_ioctl(dev_data->cdev, DIOCGMEDIASIZE,
2559                                (caddr_t)&size_bytes, FREAD,
2560                                curthread);
2561         if (error) {
2562                 snprintf(req->error_str, sizeof(req->error_str),
2563                          "error %d returned for DIOCGMEDIASIZE ioctl "
2564                          "on %s!", error, be_lun->dev_path);
2565                 return (error);
2566         }
2567
2568         if (params->lun_size_bytes != 0) {
2569                 if (params->lun_size_bytes > size_bytes) {
2570                         snprintf(req->error_str, sizeof(req->error_str),
2571                                  "requested LUN size %ju > backing device "
2572                                  "size %ju",
2573                                  (uintmax_t)params->lun_size_bytes,
2574                                  (uintmax_t)size_bytes);
2575                         return (EINVAL);
2576                 }
2577                 be_lun->size_bytes = params->lun_size_bytes;
2578         } else {
2579                 be_lun->size_bytes = size_bytes;
2580         }
2581         be_lun->size_blocks = be_lun->size_bytes / cbe_lun->blocksize;
2582         cbe_lun->maxlba = (be_lun->size_blocks == 0) ?
2583             0 : (be_lun->size_blocks - 1);
2584         return (0);
2585 }
2586
2587 static int
2588 ctl_be_block_modify(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2589 {
2590         struct ctl_lun_modify_params *params;
2591         struct ctl_be_block_lun *be_lun;
2592         uint64_t oldsize;
2593         int error;
2594
2595         params = &req->reqdata.modify;
2596
2597         mtx_lock(&softc->lock);
2598         be_lun = NULL;
2599         STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2600                 if (be_lun->cbe_lun.lun_id == params->lun_id)
2601                         break;
2602         }
2603         mtx_unlock(&softc->lock);
2604
2605         if (be_lun == NULL) {
2606                 snprintf(req->error_str, sizeof(req->error_str),
2607                          "LUN %u is not managed by the block backend",
2608                          params->lun_id);
2609                 goto bailout_error;
2610         }
2611
2612         be_lun->params.lun_size_bytes = params->lun_size_bytes;
2613
2614         oldsize = be_lun->size_blocks;
2615         if (be_lun->vn == NULL)
2616                 error = ctl_be_block_open(softc, be_lun, req);
2617         else if (vn_isdisk(be_lun->vn, &error))
2618                 error = ctl_be_block_modify_dev(be_lun, req);
2619         else if (be_lun->vn->v_type == VREG)
2620                 error = ctl_be_block_modify_file(be_lun, req);
2621         else
2622                 error = EINVAL;
2623
2624         if (be_lun->size_blocks != oldsize)
2625                 ctl_lun_capacity_changed(&be_lun->cbe_lun);
2626         if ((be_lun->cbe_lun.flags & CTL_LUN_FLAG_OFFLINE) &&
2627             be_lun->vn != NULL) {
2628                 be_lun->cbe_lun.flags &= ~CTL_LUN_FLAG_OFFLINE;
2629                 ctl_lun_online(&be_lun->cbe_lun);
2630         }
2631
2632         /* Tell the user the exact size we ended up using */
2633         params->lun_size_bytes = be_lun->size_bytes;
2634
2635         req->status = error ? CTL_LUN_WARNING : CTL_LUN_OK;
2636         return (0);
2637
2638 bailout_error:
2639         req->status = CTL_LUN_ERROR;
2640         return (0);
2641 }
2642
2643 static void
2644 ctl_be_block_lun_shutdown(void *be_lun)
2645 {
2646         struct ctl_be_block_lun *lun;
2647         struct ctl_be_block_softc *softc;
2648
2649         lun = (struct ctl_be_block_lun *)be_lun;
2650
2651         softc = lun->softc;
2652
2653         mtx_lock(&softc->lock);
2654         lun->flags |= CTL_BE_BLOCK_LUN_UNCONFIGURED;
2655         if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2656                 wakeup(lun);
2657         mtx_unlock(&softc->lock);
2658
2659 }
2660
2661 static void
2662 ctl_be_block_lun_config_status(void *be_lun, ctl_lun_config_status status)
2663 {
2664         struct ctl_be_block_lun *lun;
2665         struct ctl_be_block_softc *softc;
2666
2667         lun = (struct ctl_be_block_lun *)be_lun;
2668         softc = lun->softc;
2669
2670         if (status == CTL_LUN_CONFIG_OK) {
2671                 mtx_lock(&softc->lock);
2672                 lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2673                 if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2674                         wakeup(lun);
2675                 mtx_unlock(&softc->lock);
2676
2677                 /*
2678                  * We successfully added the LUN, attempt to enable it.
2679                  */
2680                 if (ctl_enable_lun(&lun->cbe_lun) != 0) {
2681                         printf("%s: ctl_enable_lun() failed!\n", __func__);
2682                         if (ctl_invalidate_lun(&lun->cbe_lun) != 0) {
2683                                 printf("%s: ctl_invalidate_lun() failed!\n",
2684                                        __func__);
2685                         }
2686                 }
2687
2688                 return;
2689         }
2690
2691
2692         mtx_lock(&softc->lock);
2693         lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2694         lun->flags |= CTL_BE_BLOCK_LUN_CONFIG_ERR;
2695         wakeup(lun);
2696         mtx_unlock(&softc->lock);
2697 }
2698
2699
2700 static int
2701 ctl_be_block_config_write(union ctl_io *io)
2702 {
2703         struct ctl_be_block_lun *be_lun;
2704         struct ctl_be_lun *cbe_lun;
2705         int retval;
2706
2707         retval = 0;
2708
2709         DPRINTF("entered\n");
2710
2711         cbe_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2712                 CTL_PRIV_BACKEND_LUN].ptr;
2713         be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;
2714
2715         switch (io->scsiio.cdb[0]) {
2716         case SYNCHRONIZE_CACHE:
2717         case SYNCHRONIZE_CACHE_16:
2718         case WRITE_SAME_10:
2719         case WRITE_SAME_16:
2720         case UNMAP:
2721                 /*
2722                  * The upper level CTL code will filter out any CDBs with
2723                  * the immediate bit set and return the proper error.
2724                  *
2725                  * We don't really need to worry about what LBA range the
2726                  * user asked to be synced out.  When they issue a sync
2727                  * cache command, we'll sync out the whole thing.
2728                  */
2729                 mtx_lock(&be_lun->queue_lock);
2730                 STAILQ_INSERT_TAIL(&be_lun->config_write_queue, &io->io_hdr,
2731                                    links);
2732                 mtx_unlock(&be_lun->queue_lock);
2733                 taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
2734                 break;
2735         case START_STOP_UNIT: {
2736                 struct scsi_start_stop_unit *cdb;
2737
2738                 cdb = (struct scsi_start_stop_unit *)io->scsiio.cdb;
2739
2740                 if (cdb->how & SSS_START)
2741                         retval = ctl_start_lun(cbe_lun);
2742                 else {
2743                         retval = ctl_stop_lun(cbe_lun);
2744                         /*
2745                          * XXX KDM Copan-specific offline behavior.
2746                          * Figure out a reasonable way to port this?
2747                          */
2748 #ifdef NEEDTOPORT
2749                         if ((retval == 0)
2750                          && (cdb->byte2 & SSS_ONOFFLINE))
2751                                 retval = ctl_lun_offline(cbe_lun);
2752 #endif
2753                 }
2754
2755                 /*
2756                  * In general, the above routines should not fail.  They
2757                  * just set state for the LUN.  So we've got something
2758                  * pretty wrong here if we can't start or stop the LUN.
2759                  */
2760                 if (retval != 0) {
2761                         ctl_set_internal_failure(&io->scsiio,
2762                                                  /*sks_valid*/ 1,
2763                                                  /*retry_count*/ 0xf051);
2764                         retval = CTL_RETVAL_COMPLETE;
2765                 } else {
2766                         ctl_set_success(&io->scsiio);
2767                 }
2768                 ctl_config_write_done(io);
2769                 break;
2770         }
2771         default:
2772                 ctl_set_invalid_opcode(&io->scsiio);
2773                 ctl_config_write_done(io);
2774                 retval = CTL_RETVAL_COMPLETE;
2775                 break;
2776         }
2777
2778         return (retval);
2779 }
2780
2781 static int
2782 ctl_be_block_config_read(union ctl_io *io)
2783 {
2784         struct ctl_be_block_lun *be_lun;
2785         struct ctl_be_lun *cbe_lun;
2786         int retval = 0;
2787
2788         DPRINTF("entered\n");
2789
2790         cbe_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2791                 CTL_PRIV_BACKEND_LUN].ptr;
2792         be_lun = (struct ctl_be_block_lun *)cbe_lun->be_lun;
2793
2794         switch (io->scsiio.cdb[0]) {
2795         case SERVICE_ACTION_IN:
2796                 if (io->scsiio.cdb[1] == SGLS_SERVICE_ACTION) {
2797                         mtx_lock(&be_lun->queue_lock);
2798                         STAILQ_INSERT_TAIL(&be_lun->config_read_queue,
2799                             &io->io_hdr, links);
2800                         mtx_unlock(&be_lun->queue_lock);
2801                         taskqueue_enqueue(be_lun->io_taskqueue,
2802                             &be_lun->io_task);
2803                         retval = CTL_RETVAL_QUEUED;
2804                         break;
2805                 }
2806                 ctl_set_invalid_field(&io->scsiio,
2807                                       /*sks_valid*/ 1,
2808                                       /*command*/ 1,
2809                                       /*field*/ 1,
2810                                       /*bit_valid*/ 1,
2811                                       /*bit*/ 4);
2812                 ctl_config_read_done(io);
2813                 retval = CTL_RETVAL_COMPLETE;
2814                 break;
2815         default:
2816                 ctl_set_invalid_opcode(&io->scsiio);
2817                 ctl_config_read_done(io);
2818                 retval = CTL_RETVAL_COMPLETE;
2819                 break;
2820         }
2821
2822         return (retval);
2823 }
2824
2825 static int
2826 ctl_be_block_lun_info(void *be_lun, struct sbuf *sb)
2827 {
2828         struct ctl_be_block_lun *lun;
2829         int retval;
2830
2831         lun = (struct ctl_be_block_lun *)be_lun;
2832         retval = 0;
2833
2834         retval = sbuf_printf(sb, "\t<num_threads>");
2835
2836         if (retval != 0)
2837                 goto bailout;
2838
2839         retval = sbuf_printf(sb, "%d", lun->num_threads);
2840
2841         if (retval != 0)
2842                 goto bailout;
2843
2844         retval = sbuf_printf(sb, "</num_threads>\n");
2845
2846 bailout:
2847
2848         return (retval);
2849 }
2850
2851 static uint64_t
2852 ctl_be_block_lun_attr(void *be_lun, const char *attrname)
2853 {
2854         struct ctl_be_block_lun *lun = (struct ctl_be_block_lun *)be_lun;
2855
2856         if (lun->getattr == NULL)
2857                 return (UINT64_MAX);
2858         return (lun->getattr(lun, attrname));
2859 }
2860
2861 int
2862 ctl_be_block_init(void)
2863 {
2864         struct ctl_be_block_softc *softc;
2865         int retval;
2866
2867         softc = &backend_block_softc;
2868         retval = 0;
2869
2870         mtx_init(&softc->lock, "ctlblock", NULL, MTX_DEF);
2871         beio_zone = uma_zcreate("beio", sizeof(struct ctl_be_block_io),
2872             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2873         STAILQ_INIT(&softc->lun_list);
2874
2875         return (retval);
2876 }