xref: /freebsd-14.2/sys/dev/xen/blkfront/blkfront.c (revision 11432d8f)
1 /*
2  * XenBSD block device driver
3  *
4  * Copyright (c) 2010-2013 Spectra Logic Corporation
5  * Copyright (c) 2009 Scott Long, Yahoo!
6  * Copyright (c) 2009 Frank Suchomel, Citrix
7  * Copyright (c) 2009 Doug F. Rabson, Citrix
8  * Copyright (c) 2005 Kip Macy
9  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
10  * Modifications by Mark A. Williamson are (c) Intel Research Cambridge
11  *
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining a copy
14  * of this software and associated documentation files (the "Software"), to
15  * deal in the Software without restriction, including without limitation the
16  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
17  * sell copies of the Software, and to permit persons to whom the Software is
18  * furnished to do so, subject to the following conditions:
19  *
20  * The above copyright notice and this permission notice shall be included in
21  * all copies or substantial portions of the Software.
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28  * DEALINGS IN THE SOFTWARE.
29  */
30 
31 #include <sys/cdefs.h>
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/malloc.h>
35 #include <sys/kernel.h>
36 #include <vm/vm.h>
37 #include <vm/pmap.h>
38 
39 #include <sys/bio.h>
40 #include <sys/bus.h>
41 #include <sys/conf.h>
42 #include <sys/module.h>
43 #include <sys/sysctl.h>
44 
45 #include <machine/bus.h>
46 #include <sys/rman.h>
47 #include <machine/resource.h>
48 #include <machine/vmparam.h>
49 
50 #include <xen/xen-os.h>
51 #include <xen/hypervisor.h>
52 #include <xen/xen_intr.h>
53 #include <xen/gnttab.h>
54 #include <contrib/xen/grant_table.h>
55 #include <contrib/xen/io/protocols.h>
56 #include <xen/xenbus/xenbusvar.h>
57 
58 #include <machine/_inttypes.h>
59 
60 #include <geom/geom_disk.h>
61 
62 #include <dev/xen/blkfront/block.h>
63 
64 #include "xenbus_if.h"
65 
66 /*--------------------------- Forward Declarations ---------------------------*/
67 static void xbd_closing(device_t);
68 static void xbd_startio(struct xbd_softc *sc);
69 
70 /*---------------------------------- Macros ----------------------------------*/
71 #if 0
72 #define DPRINTK(fmt, args...) printf("[XEN] %s:%d: " fmt ".\n", __func__, __LINE__, ##args)
73 #else
74 #define DPRINTK(fmt, args...)
75 #endif
76 
77 #define XBD_SECTOR_SHFT		9
78 
79 /*---------------------------- Global Static Data ----------------------------*/
80 static MALLOC_DEFINE(M_XENBLOCKFRONT, "xbd", "Xen Block Front driver data");
81 
82 static int xbd_enable_indirect = 1;
83 SYSCTL_NODE(_hw, OID_AUTO, xbd, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
84     "xbd driver parameters");
85 SYSCTL_INT(_hw_xbd, OID_AUTO, xbd_enable_indirect, CTLFLAG_RDTUN,
86     &xbd_enable_indirect, 0, "Enable xbd indirect segments");
87 
88 /*---------------------------- Command Processing ----------------------------*/
89 static void
xbd_freeze(struct xbd_softc * sc,xbd_flag_t xbd_flag)90 xbd_freeze(struct xbd_softc *sc, xbd_flag_t xbd_flag)
91 {
92 	if (xbd_flag != XBDF_NONE && (sc->xbd_flags & xbd_flag) != 0)
93 		return;
94 
95 	sc->xbd_flags |= xbd_flag;
96 	sc->xbd_qfrozen_cnt++;
97 }
98 
99 static void
xbd_thaw(struct xbd_softc * sc,xbd_flag_t xbd_flag)100 xbd_thaw(struct xbd_softc *sc, xbd_flag_t xbd_flag)
101 {
102 	if (xbd_flag != XBDF_NONE && (sc->xbd_flags & xbd_flag) == 0)
103 		return;
104 
105 	if (sc->xbd_qfrozen_cnt == 0)
106 		panic("%s: Thaw with flag 0x%x while not frozen.",
107 		    __func__, xbd_flag);
108 
109 	sc->xbd_flags &= ~xbd_flag;
110 	sc->xbd_qfrozen_cnt--;
111 }
112 
113 static void
xbd_cm_freeze(struct xbd_softc * sc,struct xbd_command * cm,xbdc_flag_t cm_flag)114 xbd_cm_freeze(struct xbd_softc *sc, struct xbd_command *cm, xbdc_flag_t cm_flag)
115 {
116 	if ((cm->cm_flags & XBDCF_FROZEN) != 0)
117 		return;
118 
119 	cm->cm_flags |= XBDCF_FROZEN|cm_flag;
120 	xbd_freeze(sc, XBDF_NONE);
121 }
122 
123 static void
xbd_cm_thaw(struct xbd_softc * sc,struct xbd_command * cm)124 xbd_cm_thaw(struct xbd_softc *sc, struct xbd_command *cm)
125 {
126 	if ((cm->cm_flags & XBDCF_FROZEN) == 0)
127 		return;
128 
129 	cm->cm_flags &= ~XBDCF_FROZEN;
130 	xbd_thaw(sc, XBDF_NONE);
131 }
132 
133 static inline void
xbd_flush_requests(struct xbd_softc * sc)134 xbd_flush_requests(struct xbd_softc *sc)
135 {
136 	int notify;
137 
138 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->xbd_ring, notify);
139 
140 	if (notify)
141 		xen_intr_signal(sc->xen_intr_handle);
142 }
143 
144 static void
xbd_free_command(struct xbd_command * cm)145 xbd_free_command(struct xbd_command *cm)
146 {
147 
148 	KASSERT((cm->cm_flags & XBDCF_Q_MASK) == XBD_Q_NONE,
149 	    ("Freeing command that is still on queue %d.",
150 	    cm->cm_flags & XBDCF_Q_MASK));
151 
152 	cm->cm_flags = XBDCF_INITIALIZER;
153 	cm->cm_bp = NULL;
154 	cm->cm_complete = NULL;
155 	xbd_enqueue_cm(cm, XBD_Q_FREE);
156 	xbd_thaw(cm->cm_sc, XBDF_CM_SHORTAGE);
157 }
158 
159 static void
xbd_mksegarray(bus_dma_segment_t * segs,int nsegs,grant_ref_t * gref_head,int otherend_id,int readonly,grant_ref_t * sg_ref,struct blkif_request_segment * sg,unsigned int sector_size)160 xbd_mksegarray(bus_dma_segment_t *segs, int nsegs,
161     grant_ref_t * gref_head, int otherend_id, int readonly,
162     grant_ref_t * sg_ref, struct blkif_request_segment *sg,
163     unsigned int sector_size)
164 {
165 	struct blkif_request_segment *last_block_sg = sg + nsegs;
166 	vm_paddr_t buffer_ma;
167 	uint64_t fsect, lsect;
168 	int ref;
169 
170 	while (sg < last_block_sg) {
171 		KASSERT((segs->ds_addr & (sector_size - 1)) == 0,
172 		    ("XEN disk driver I/O must be sector aligned"));
173 		KASSERT((segs->ds_len & (sector_size - 1)) == 0,
174 		    ("XEN disk driver I/Os must be a multiple of "
175 		    "the sector length"));
176 		buffer_ma = segs->ds_addr;
177 		fsect = (buffer_ma & PAGE_MASK) >> XBD_SECTOR_SHFT;
178 		lsect = fsect + (segs->ds_len  >> XBD_SECTOR_SHFT) - 1;
179 
180 		KASSERT(lsect <= 7, ("XEN disk driver data cannot "
181 		    "cross a page boundary"));
182 
183 		/* install a grant reference. */
184 		ref = gnttab_claim_grant_reference(gref_head);
185 
186 		/*
187 		 * GNTTAB_LIST_END == 0xffffffff, but it is private
188 		 * to gnttab.c.
189 		 */
190 		KASSERT(ref != ~0, ("grant_reference failed"));
191 
192 		gnttab_grant_foreign_access_ref(
193 		    ref,
194 		    otherend_id,
195 		    buffer_ma >> PAGE_SHIFT,
196 		    readonly);
197 
198 		*sg_ref = ref;
199 		*sg = (struct blkif_request_segment) {
200 			.gref       = ref,
201 			.first_sect = fsect,
202 			.last_sect  = lsect
203 		};
204 		sg++;
205 		sg_ref++;
206 		segs++;
207 	}
208 }
209 
210 static void
xbd_queue_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)211 xbd_queue_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
212 {
213 	struct xbd_softc *sc;
214 	struct xbd_command *cm;
215 	int op;
216 
217 	cm = arg;
218 	sc = cm->cm_sc;
219 
220 	if (error) {
221 		cm->cm_bp->bio_error = EIO;
222 		biodone(cm->cm_bp);
223 		xbd_free_command(cm);
224 		return;
225 	}
226 
227 	KASSERT(nsegs <= sc->xbd_max_request_segments,
228 	    ("Too many segments in a blkfront I/O"));
229 
230 	if (nsegs <= BLKIF_MAX_SEGMENTS_PER_REQUEST) {
231 		blkif_request_t	*ring_req;
232 
233 		/* Fill out a blkif_request_t structure. */
234 		ring_req = (blkif_request_t *)
235 		    RING_GET_REQUEST(&sc->xbd_ring, sc->xbd_ring.req_prod_pvt);
236 		sc->xbd_ring.req_prod_pvt++;
237 		ring_req->id = cm->cm_id;
238 		ring_req->operation = cm->cm_operation;
239 		ring_req->sector_number = cm->cm_sector_number;
240 		ring_req->handle = (blkif_vdev_t)(uintptr_t)sc->xbd_disk;
241 		ring_req->nr_segments = nsegs;
242 		cm->cm_nseg = nsegs;
243 		xbd_mksegarray(segs, nsegs, &cm->cm_gref_head,
244 		    xenbus_get_otherend_id(sc->xbd_dev),
245 		    cm->cm_operation == BLKIF_OP_WRITE,
246 		    cm->cm_sg_refs, ring_req->seg,
247 		    sc->xbd_disk->d_sectorsize);
248 	} else {
249 		blkif_request_indirect_t *ring_req;
250 
251 		/* Fill out a blkif_request_indirect_t structure. */
252 		ring_req = (blkif_request_indirect_t *)
253 		    RING_GET_REQUEST(&sc->xbd_ring, sc->xbd_ring.req_prod_pvt);
254 		sc->xbd_ring.req_prod_pvt++;
255 		ring_req->id = cm->cm_id;
256 		ring_req->operation = BLKIF_OP_INDIRECT;
257 		ring_req->indirect_op = cm->cm_operation;
258 		ring_req->sector_number = cm->cm_sector_number;
259 		ring_req->handle = (blkif_vdev_t)(uintptr_t)sc->xbd_disk;
260 		ring_req->nr_segments = nsegs;
261 		cm->cm_nseg = nsegs;
262 		xbd_mksegarray(segs, nsegs, &cm->cm_gref_head,
263 		    xenbus_get_otherend_id(sc->xbd_dev),
264 		    cm->cm_operation == BLKIF_OP_WRITE,
265 		    cm->cm_sg_refs, cm->cm_indirectionpages,
266 		    sc->xbd_disk->d_sectorsize);
267 		memcpy(ring_req->indirect_grefs, &cm->cm_indirectionrefs,
268 		    sizeof(grant_ref_t) * sc->xbd_max_request_indirectpages);
269 	}
270 
271 	if (cm->cm_operation == BLKIF_OP_READ)
272 		op = BUS_DMASYNC_PREREAD;
273 	else if (cm->cm_operation == BLKIF_OP_WRITE)
274 		op = BUS_DMASYNC_PREWRITE;
275 	else
276 		op = 0;
277 	bus_dmamap_sync(sc->xbd_io_dmat, cm->cm_map, op);
278 
279 	gnttab_free_grant_references(cm->cm_gref_head);
280 
281 	xbd_enqueue_cm(cm, XBD_Q_BUSY);
282 
283 	/*
284 	 * If bus dma had to asynchronously call us back to dispatch
285 	 * this command, we are no longer executing in the context of
286 	 * xbd_startio().  Thus we cannot rely on xbd_startio()'s call to
287 	 * xbd_flush_requests() to publish this command to the backend
288 	 * along with any other commands that it could batch.
289 	 */
290 	if ((cm->cm_flags & XBDCF_ASYNC_MAPPING) != 0)
291 		xbd_flush_requests(sc);
292 
293 	return;
294 }
295 
296 static int
xbd_queue_request(struct xbd_softc * sc,struct xbd_command * cm)297 xbd_queue_request(struct xbd_softc *sc, struct xbd_command *cm)
298 {
299 	int error;
300 
301 	if (cm->cm_bp != NULL)
302 		error = bus_dmamap_load_bio(sc->xbd_io_dmat, cm->cm_map,
303 		    cm->cm_bp, xbd_queue_cb, cm, 0);
304 	else
305 		error = bus_dmamap_load(sc->xbd_io_dmat, cm->cm_map,
306 		    cm->cm_data, cm->cm_datalen, xbd_queue_cb, cm, 0);
307 	if (error == EINPROGRESS) {
308 		/*
309 		 * Maintain queuing order by freezing the queue.  The next
310 		 * command may not require as many resources as the command
311 		 * we just attempted to map, so we can't rely on bus dma
312 		 * blocking for it too.
313 		 */
314 		xbd_cm_freeze(sc, cm, XBDCF_ASYNC_MAPPING);
315 		return (0);
316 	}
317 
318 	return (error);
319 }
320 
321 static void
xbd_restart_queue_callback(void * arg)322 xbd_restart_queue_callback(void *arg)
323 {
324 	struct xbd_softc *sc = arg;
325 
326 	mtx_lock(&sc->xbd_io_lock);
327 
328 	xbd_thaw(sc, XBDF_GNT_SHORTAGE);
329 
330 	xbd_startio(sc);
331 
332 	mtx_unlock(&sc->xbd_io_lock);
333 }
334 
335 static struct xbd_command *
xbd_bio_command(struct xbd_softc * sc)336 xbd_bio_command(struct xbd_softc *sc)
337 {
338 	struct xbd_command *cm;
339 	struct bio *bp;
340 
341 	if (__predict_false(sc->xbd_state != XBD_STATE_CONNECTED))
342 		return (NULL);
343 
344 	bp = xbd_dequeue_bio(sc);
345 	if (bp == NULL)
346 		return (NULL);
347 
348 	if ((cm = xbd_dequeue_cm(sc, XBD_Q_FREE)) == NULL) {
349 		xbd_freeze(sc, XBDF_CM_SHORTAGE);
350 		xbd_requeue_bio(sc, bp);
351 		return (NULL);
352 	}
353 
354 	if (gnttab_alloc_grant_references(sc->xbd_max_request_segments,
355 	    &cm->cm_gref_head) != 0) {
356 		gnttab_request_free_callback(&sc->xbd_callback,
357 		    xbd_restart_queue_callback, sc,
358 		    sc->xbd_max_request_segments);
359 		xbd_freeze(sc, XBDF_GNT_SHORTAGE);
360 		xbd_requeue_bio(sc, bp);
361 		xbd_enqueue_cm(cm, XBD_Q_FREE);
362 		return (NULL);
363 	}
364 
365 	cm->cm_bp = bp;
366 	cm->cm_sector_number =
367 	    ((blkif_sector_t)bp->bio_pblkno * sc->xbd_disk->d_sectorsize) >>
368 	    XBD_SECTOR_SHFT;
369 
370 	switch (bp->bio_cmd) {
371 	case BIO_READ:
372 		cm->cm_operation = BLKIF_OP_READ;
373 		break;
374 	case BIO_WRITE:
375 		cm->cm_operation = BLKIF_OP_WRITE;
376 		if ((bp->bio_flags & BIO_ORDERED) != 0) {
377 			if ((sc->xbd_flags & XBDF_BARRIER) != 0) {
378 				cm->cm_operation = BLKIF_OP_WRITE_BARRIER;
379 			} else {
380 				/*
381 				 * Single step this command.
382 				 */
383 				cm->cm_flags |= XBDCF_Q_FREEZE;
384 				if (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
385 					/*
386 					 * Wait for in-flight requests to
387 					 * finish.
388 					 */
389 					xbd_freeze(sc, XBDF_WAIT_IDLE);
390 					xbd_requeue_cm(cm, XBD_Q_READY);
391 					return (NULL);
392 				}
393 			}
394 		}
395 		break;
396 	case BIO_FLUSH:
397 		if ((sc->xbd_flags & XBDF_FLUSH) != 0)
398 			cm->cm_operation = BLKIF_OP_FLUSH_DISKCACHE;
399 		else if ((sc->xbd_flags & XBDF_BARRIER) != 0)
400 			cm->cm_operation = BLKIF_OP_WRITE_BARRIER;
401 		else
402 			panic("flush request, but no flush support available");
403 		break;
404 	default:
405 		biofinish(bp, NULL, EOPNOTSUPP);
406 		xbd_enqueue_cm(cm, XBD_Q_FREE);
407 		return (NULL);
408 	}
409 
410 	return (cm);
411 }
412 
413 /*
414  * Dequeue buffers and place them in the shared communication ring.
415  * Return when no more requests can be accepted or all buffers have
416  * been queued.
417  *
418  * Signal XEN once the ring has been filled out.
419  */
420 static void
xbd_startio(struct xbd_softc * sc)421 xbd_startio(struct xbd_softc *sc)
422 {
423 	struct xbd_command *cm;
424 	int error, queued = 0;
425 
426 	mtx_assert(&sc->xbd_io_lock, MA_OWNED);
427 
428 	if (sc->xbd_state != XBD_STATE_CONNECTED)
429 		return;
430 
431 	while (!RING_FULL(&sc->xbd_ring)) {
432 		if (sc->xbd_qfrozen_cnt != 0)
433 			break;
434 
435 		cm = xbd_dequeue_cm(sc, XBD_Q_READY);
436 
437 		if (cm == NULL)
438 		    cm = xbd_bio_command(sc);
439 
440 		if (cm == NULL)
441 			break;
442 
443 		if ((cm->cm_flags & XBDCF_Q_FREEZE) != 0) {
444 			/*
445 			 * Single step command.  Future work is
446 			 * held off until this command completes.
447 			 */
448 			xbd_cm_freeze(sc, cm, XBDCF_Q_FREEZE);
449 		}
450 
451 		if ((error = xbd_queue_request(sc, cm)) != 0) {
452 			printf("xbd_queue_request returned %d\n", error);
453 			break;
454 		}
455 		queued++;
456 	}
457 
458 	if (queued != 0)
459 		xbd_flush_requests(sc);
460 }
461 
462 static void
xbd_bio_complete(struct xbd_softc * sc,struct xbd_command * cm)463 xbd_bio_complete(struct xbd_softc *sc, struct xbd_command *cm)
464 {
465 	struct bio *bp;
466 
467 	bp = cm->cm_bp;
468 
469 	if (__predict_false(cm->cm_status != BLKIF_RSP_OKAY)) {
470 		disk_err(bp, "disk error" , -1, 0);
471 		printf(" status: %x\n", cm->cm_status);
472 		bp->bio_flags |= BIO_ERROR;
473 	}
474 
475 	if (bp->bio_flags & BIO_ERROR)
476 		bp->bio_error = EIO;
477 	else
478 		bp->bio_resid = 0;
479 
480 	xbd_free_command(cm);
481 	biodone(bp);
482 }
483 
484 static void
xbd_int(void * xsc)485 xbd_int(void *xsc)
486 {
487 	struct xbd_softc *sc = xsc;
488 	struct xbd_command *cm;
489 	blkif_response_t *bret;
490 	RING_IDX i, rp;
491 	int op;
492 
493 	mtx_lock(&sc->xbd_io_lock);
494 
495 	if (__predict_false(sc->xbd_state == XBD_STATE_DISCONNECTED)) {
496 		mtx_unlock(&sc->xbd_io_lock);
497 		return;
498 	}
499 
500  again:
501 	rp = sc->xbd_ring.sring->rsp_prod;
502 	rmb(); /* Ensure we see queued responses up to 'rp'. */
503 
504 	for (i = sc->xbd_ring.rsp_cons; i != rp;) {
505 		bret = RING_GET_RESPONSE(&sc->xbd_ring, i);
506 		cm   = &sc->xbd_shadow[bret->id];
507 
508 		xbd_remove_cm(cm, XBD_Q_BUSY);
509 		gnttab_end_foreign_access_references(cm->cm_nseg,
510 		    cm->cm_sg_refs);
511 		i++;
512 
513 		if (cm->cm_operation == BLKIF_OP_READ)
514 			op = BUS_DMASYNC_POSTREAD;
515 		else if (cm->cm_operation == BLKIF_OP_WRITE ||
516 		    cm->cm_operation == BLKIF_OP_WRITE_BARRIER)
517 			op = BUS_DMASYNC_POSTWRITE;
518 		else
519 			op = 0;
520 		bus_dmamap_sync(sc->xbd_io_dmat, cm->cm_map, op);
521 		bus_dmamap_unload(sc->xbd_io_dmat, cm->cm_map);
522 
523 		/*
524 		 * Release any hold this command has on future command
525 		 * dispatch.
526 		 */
527 		xbd_cm_thaw(sc, cm);
528 
529 		/*
530 		 * Directly call the i/o complete routine to save an
531 		 * an indirection in the common case.
532 		 */
533 		cm->cm_status = bret->status;
534 		if (cm->cm_bp)
535 			xbd_bio_complete(sc, cm);
536 		else if (cm->cm_complete != NULL)
537 			cm->cm_complete(cm);
538 		else
539 			xbd_free_command(cm);
540 	}
541 
542 	sc->xbd_ring.rsp_cons = i;
543 
544 	if (i != sc->xbd_ring.req_prod_pvt) {
545 		int more_to_do;
546 		RING_FINAL_CHECK_FOR_RESPONSES(&sc->xbd_ring, more_to_do);
547 		if (more_to_do)
548 			goto again;
549 	} else {
550 		sc->xbd_ring.sring->rsp_event = i + 1;
551 	}
552 
553 	if (xbd_queue_length(sc, XBD_Q_BUSY) == 0)
554 		xbd_thaw(sc, XBDF_WAIT_IDLE);
555 
556 	xbd_startio(sc);
557 
558 	if (__predict_false(sc->xbd_state == XBD_STATE_SUSPENDED))
559 		wakeup(&sc->xbd_cm_q[XBD_Q_BUSY]);
560 
561 	mtx_unlock(&sc->xbd_io_lock);
562 }
563 
564 /*------------------------------- Dump Support -------------------------------*/
565 /**
566  * Quiesce the disk writes for a dump file before allowing the next buffer.
567  */
568 static void
xbd_quiesce(struct xbd_softc * sc)569 xbd_quiesce(struct xbd_softc *sc)
570 {
571 	int mtd;
572 
573 	// While there are outstanding requests
574 	while (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
575 		RING_FINAL_CHECK_FOR_RESPONSES(&sc->xbd_ring, mtd);
576 		if (mtd) {
577 			/* Received request completions, update queue. */
578 			xbd_int(sc);
579 		}
580 		if (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
581 			/*
582 			 * Still pending requests, wait for the disk i/o
583 			 * to complete.
584 			 */
585 			HYPERVISOR_yield();
586 		}
587 	}
588 }
589 
590 /* Kernel dump function for a paravirtualized disk device */
591 static void
xbd_dump_complete(struct xbd_command * cm)592 xbd_dump_complete(struct xbd_command *cm)
593 {
594 
595 	xbd_enqueue_cm(cm, XBD_Q_COMPLETE);
596 }
597 
598 static int
xbd_dump(void * arg,void * virtual,off_t offset,size_t length)599 xbd_dump(void *arg, void *virtual, off_t offset, size_t length)
600 {
601 	struct disk *dp = arg;
602 	struct xbd_softc *sc = dp->d_drv1;
603 	struct xbd_command *cm;
604 	size_t chunk;
605 	int rc = 0;
606 
607 	if (length == 0)
608 		return (0);
609 
610 	xbd_quiesce(sc);	/* All quiet on the western front. */
611 
612 	/*
613 	 * If this lock is held, then this module is failing, and a
614 	 * successful kernel dump is highly unlikely anyway.
615 	 */
616 	mtx_lock(&sc->xbd_io_lock);
617 
618 	/* Split the 64KB block as needed */
619 	while (length > 0) {
620 		cm = xbd_dequeue_cm(sc, XBD_Q_FREE);
621 		if (cm == NULL) {
622 			mtx_unlock(&sc->xbd_io_lock);
623 			device_printf(sc->xbd_dev, "dump: no more commands?\n");
624 			return (EBUSY);
625 		}
626 
627 		if (gnttab_alloc_grant_references(sc->xbd_max_request_segments,
628 		    &cm->cm_gref_head) != 0) {
629 			xbd_free_command(cm);
630 			mtx_unlock(&sc->xbd_io_lock);
631 			device_printf(sc->xbd_dev, "no more grant allocs?\n");
632 			return (EBUSY);
633 		}
634 
635 		chunk = length > sc->xbd_max_request_size ?
636 		    sc->xbd_max_request_size : length;
637 		cm->cm_data = virtual;
638 		cm->cm_datalen = chunk;
639 		cm->cm_operation = BLKIF_OP_WRITE;
640 		cm->cm_sector_number = offset >> XBD_SECTOR_SHFT;
641 		cm->cm_complete = xbd_dump_complete;
642 
643 		xbd_enqueue_cm(cm, XBD_Q_READY);
644 
645 		length -= chunk;
646 		offset += chunk;
647 		virtual = (char *) virtual + chunk;
648 	}
649 
650 	/* Tell DOM0 to do the I/O */
651 	xbd_startio(sc);
652 	mtx_unlock(&sc->xbd_io_lock);
653 
654 	/* Poll for the completion. */
655 	xbd_quiesce(sc);	/* All quite on the eastern front */
656 
657 	/* If there were any errors, bail out... */
658 	while ((cm = xbd_dequeue_cm(sc, XBD_Q_COMPLETE)) != NULL) {
659 		if (cm->cm_status != BLKIF_RSP_OKAY) {
660 			device_printf(sc->xbd_dev,
661 			    "Dump I/O failed at sector %jd\n",
662 			    cm->cm_sector_number);
663 			rc = EIO;
664 		}
665 		xbd_free_command(cm);
666 	}
667 
668 	return (rc);
669 }
670 
671 /*----------------------------- Disk Entrypoints -----------------------------*/
672 static int
xbd_open(struct disk * dp)673 xbd_open(struct disk *dp)
674 {
675 	struct xbd_softc *sc = dp->d_drv1;
676 
677 	if (sc == NULL) {
678 		printf("xbd%d: not found", dp->d_unit);
679 		return (ENXIO);
680 	}
681 
682 	sc->xbd_flags |= XBDF_OPEN;
683 	sc->xbd_users++;
684 	return (0);
685 }
686 
687 static int
xbd_close(struct disk * dp)688 xbd_close(struct disk *dp)
689 {
690 	struct xbd_softc *sc = dp->d_drv1;
691 
692 	if (sc == NULL)
693 		return (ENXIO);
694 	sc->xbd_flags &= ~XBDF_OPEN;
695 	if (--(sc->xbd_users) == 0) {
696 		/*
697 		 * Check whether we have been instructed to close.  We will
698 		 * have ignored this request initially, as the device was
699 		 * still mounted.
700 		 */
701 		if (xenbus_get_otherend_state(sc->xbd_dev) ==
702 		    XenbusStateClosing)
703 			xbd_closing(sc->xbd_dev);
704 	}
705 	return (0);
706 }
707 
708 static int
xbd_ioctl(struct disk * dp,u_long cmd,void * addr,int flag,struct thread * td)709 xbd_ioctl(struct disk *dp, u_long cmd, void *addr, int flag, struct thread *td)
710 {
711 	struct xbd_softc *sc = dp->d_drv1;
712 
713 	if (sc == NULL)
714 		return (ENXIO);
715 
716 	return (ENOTTY);
717 }
718 
719 /*
720  * Read/write routine for a buffer.  Finds the proper unit, place it on
721  * the sortq and kick the controller.
722  */
723 static void
xbd_strategy(struct bio * bp)724 xbd_strategy(struct bio *bp)
725 {
726 	struct xbd_softc *sc = bp->bio_disk->d_drv1;
727 
728 	/* bogus disk? */
729 	if (sc == NULL) {
730 		bp->bio_error = EINVAL;
731 		bp->bio_flags |= BIO_ERROR;
732 		bp->bio_resid = bp->bio_bcount;
733 		biodone(bp);
734 		return;
735 	}
736 
737 	/*
738 	 * Place it in the queue of disk activities for this disk
739 	 */
740 	mtx_lock(&sc->xbd_io_lock);
741 
742 	xbd_enqueue_bio(sc, bp);
743 	xbd_startio(sc);
744 
745 	mtx_unlock(&sc->xbd_io_lock);
746 	return;
747 }
748 
749 /*------------------------------ Ring Management -----------------------------*/
750 static int
xbd_alloc_ring(struct xbd_softc * sc)751 xbd_alloc_ring(struct xbd_softc *sc)
752 {
753 	blkif_sring_t *sring;
754 	uintptr_t sring_page_addr;
755 	int error;
756 	int i;
757 
758 	sring = malloc(sc->xbd_ring_pages * PAGE_SIZE, M_XENBLOCKFRONT,
759 	    M_NOWAIT|M_ZERO);
760 	if (sring == NULL) {
761 		xenbus_dev_fatal(sc->xbd_dev, ENOMEM, "allocating shared ring");
762 		return (ENOMEM);
763 	}
764 	SHARED_RING_INIT(sring);
765 	FRONT_RING_INIT(&sc->xbd_ring, sring, sc->xbd_ring_pages * PAGE_SIZE);
766 
767 	for (i = 0, sring_page_addr = (uintptr_t)sring;
768 	     i < sc->xbd_ring_pages;
769 	     i++, sring_page_addr += PAGE_SIZE) {
770 		error = xenbus_grant_ring(sc->xbd_dev,
771 		    (vtophys(sring_page_addr) >> PAGE_SHIFT),
772 		    &sc->xbd_ring_ref[i]);
773 		if (error) {
774 			xenbus_dev_fatal(sc->xbd_dev, error,
775 			    "granting ring_ref(%d)", i);
776 			return (error);
777 		}
778 	}
779 	if (sc->xbd_ring_pages == 1) {
780 		error = xs_printf(XST_NIL, xenbus_get_node(sc->xbd_dev),
781 		    "ring-ref", "%u", sc->xbd_ring_ref[0]);
782 		if (error) {
783 			xenbus_dev_fatal(sc->xbd_dev, error,
784 			    "writing %s/ring-ref",
785 			    xenbus_get_node(sc->xbd_dev));
786 			return (error);
787 		}
788 	} else {
789 		for (i = 0; i < sc->xbd_ring_pages; i++) {
790 			char ring_ref_name[]= "ring_refXX";
791 
792 			snprintf(ring_ref_name, sizeof(ring_ref_name),
793 			    "ring-ref%u", i);
794 			error = xs_printf(XST_NIL, xenbus_get_node(sc->xbd_dev),
795 			     ring_ref_name, "%u", sc->xbd_ring_ref[i]);
796 			if (error) {
797 				xenbus_dev_fatal(sc->xbd_dev, error,
798 				    "writing %s/%s",
799 				    xenbus_get_node(sc->xbd_dev),
800 				    ring_ref_name);
801 				return (error);
802 			}
803 		}
804 	}
805 
806 	error = xen_intr_alloc_and_bind_local_port(sc->xbd_dev,
807 	    xenbus_get_otherend_id(sc->xbd_dev), NULL, xbd_int, sc,
808 	    INTR_TYPE_BIO | INTR_MPSAFE, &sc->xen_intr_handle);
809 	if (error) {
810 		xenbus_dev_fatal(sc->xbd_dev, error,
811 		    "xen_intr_alloc_and_bind_local_port failed");
812 		return (error);
813 	}
814 
815 	return (0);
816 }
817 
818 static void
xbd_free_ring(struct xbd_softc * sc)819 xbd_free_ring(struct xbd_softc *sc)
820 {
821 	int i;
822 
823 	if (sc->xbd_ring.sring == NULL)
824 		return;
825 
826 	for (i = 0; i < sc->xbd_ring_pages; i++) {
827 		if (sc->xbd_ring_ref[i] != GRANT_REF_INVALID) {
828 			gnttab_end_foreign_access_ref(sc->xbd_ring_ref[i]);
829 			sc->xbd_ring_ref[i] = GRANT_REF_INVALID;
830 		}
831 	}
832 	free(sc->xbd_ring.sring, M_XENBLOCKFRONT);
833 	sc->xbd_ring.sring = NULL;
834 }
835 
836 /*-------------------------- Initialization/Teardown -------------------------*/
837 static int
xbd_feature_string(struct xbd_softc * sc,char * features,size_t len)838 xbd_feature_string(struct xbd_softc *sc, char *features, size_t len)
839 {
840 	struct sbuf sb;
841 	int feature_cnt;
842 
843 	sbuf_new(&sb, features, len, SBUF_FIXEDLEN);
844 
845 	feature_cnt = 0;
846 	if ((sc->xbd_flags & XBDF_FLUSH) != 0) {
847 		sbuf_printf(&sb, "flush");
848 		feature_cnt++;
849 	}
850 
851 	if ((sc->xbd_flags & XBDF_BARRIER) != 0) {
852 		if (feature_cnt != 0)
853 			sbuf_printf(&sb, ", ");
854 		sbuf_printf(&sb, "write_barrier");
855 		feature_cnt++;
856 	}
857 
858 	if ((sc->xbd_flags & XBDF_DISCARD) != 0) {
859 		if (feature_cnt != 0)
860 			sbuf_printf(&sb, ", ");
861 		sbuf_printf(&sb, "discard");
862 		feature_cnt++;
863 	}
864 
865 	if ((sc->xbd_flags & XBDF_PERSISTENT) != 0) {
866 		if (feature_cnt != 0)
867 			sbuf_printf(&sb, ", ");
868 		sbuf_printf(&sb, "persistent_grants");
869 		feature_cnt++;
870 	}
871 
872 	(void) sbuf_finish(&sb);
873 	return (sbuf_len(&sb));
874 }
875 
876 static int
xbd_sysctl_features(SYSCTL_HANDLER_ARGS)877 xbd_sysctl_features(SYSCTL_HANDLER_ARGS)
878 {
879 	char features[80];
880 	struct xbd_softc *sc = arg1;
881 	int error;
882 	int len;
883 
884 	error = sysctl_wire_old_buffer(req, 0);
885 	if (error != 0)
886 		return (error);
887 
888 	len = xbd_feature_string(sc, features, sizeof(features));
889 
890 	/* len is -1 on error, which will make the SYSCTL_OUT a no-op. */
891 	return (SYSCTL_OUT(req, features, len + 1/*NUL*/));
892 }
893 
894 static void
xbd_setup_sysctl(struct xbd_softc * xbd)895 xbd_setup_sysctl(struct xbd_softc *xbd)
896 {
897 	struct sysctl_ctx_list *sysctl_ctx = NULL;
898 	struct sysctl_oid *sysctl_tree = NULL;
899 	struct sysctl_oid_list *children;
900 
901 	sysctl_ctx = device_get_sysctl_ctx(xbd->xbd_dev);
902 	if (sysctl_ctx == NULL)
903 		return;
904 
905 	sysctl_tree = device_get_sysctl_tree(xbd->xbd_dev);
906 	if (sysctl_tree == NULL)
907 		return;
908 
909 	children = SYSCTL_CHILDREN(sysctl_tree);
910 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
911 	    "max_requests", CTLFLAG_RD, &xbd->xbd_max_requests, -1,
912 	    "maximum outstanding requests (negotiated)");
913 
914 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
915 	    "max_request_segments", CTLFLAG_RD,
916 	    &xbd->xbd_max_request_segments, 0,
917 	    "maximum number of pages per requests (negotiated)");
918 
919 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
920 	    "max_request_size", CTLFLAG_RD, &xbd->xbd_max_request_size, 0,
921 	    "maximum size in bytes of a request (negotiated)");
922 
923 	SYSCTL_ADD_UINT(sysctl_ctx, children, OID_AUTO,
924 	    "ring_pages", CTLFLAG_RD, &xbd->xbd_ring_pages, 0,
925 	    "communication channel pages (negotiated)");
926 
927 	SYSCTL_ADD_PROC(sysctl_ctx, children, OID_AUTO,
928 	    "features", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, xbd,
929 	    0, xbd_sysctl_features, "A", "protocol features (negotiated)");
930 }
931 
932 /*
933  * Translate Linux major/minor to an appropriate name and unit
934  * number. For HVM guests, this allows us to use the same drive names
935  * with blkfront as the emulated drives, easing transition slightly.
936  */
937 static void
xbd_vdevice_to_unit(uint32_t vdevice,int * unit,const char ** name)938 xbd_vdevice_to_unit(uint32_t vdevice, int *unit, const char **name)
939 {
940 	static struct vdev_info {
941 		int major;
942 		int shift;
943 		int base;
944 		const char *name;
945 	} info[] = {
946 		{3,	6,	0,	"ada"},	/* ide0 */
947 		{22,	6,	2,	"ada"},	/* ide1 */
948 		{33,	6,	4,	"ada"},	/* ide2 */
949 		{34,	6,	6,	"ada"},	/* ide3 */
950 		{56,	6,	8,	"ada"},	/* ide4 */
951 		{57,	6,	10,	"ada"},	/* ide5 */
952 		{88,	6,	12,	"ada"},	/* ide6 */
953 		{89,	6,	14,	"ada"},	/* ide7 */
954 		{90,	6,	16,	"ada"},	/* ide8 */
955 		{91,	6,	18,	"ada"},	/* ide9 */
956 
957 		{8,	4,	0,	"da"},	/* scsi disk0 */
958 		{65,	4,	16,	"da"},	/* scsi disk1 */
959 		{66,	4,	32,	"da"},	/* scsi disk2 */
960 		{67,	4,	48,	"da"},	/* scsi disk3 */
961 		{68,	4,	64,	"da"},	/* scsi disk4 */
962 		{69,	4,	80,	"da"},	/* scsi disk5 */
963 		{70,	4,	96,	"da"},	/* scsi disk6 */
964 		{71,	4,	112,	"da"},	/* scsi disk7 */
965 		{128,	4,	128,	"da"},	/* scsi disk8 */
966 		{129,	4,	144,	"da"},	/* scsi disk9 */
967 		{130,	4,	160,	"da"},	/* scsi disk10 */
968 		{131,	4,	176,	"da"},	/* scsi disk11 */
969 		{132,	4,	192,	"da"},	/* scsi disk12 */
970 		{133,	4,	208,	"da"},	/* scsi disk13 */
971 		{134,	4,	224,	"da"},	/* scsi disk14 */
972 		{135,	4,	240,	"da"},	/* scsi disk15 */
973 
974 		{202,	4,	0,	"xbd"},	/* xbd */
975 
976 		{0,	0,	0,	NULL},
977 	};
978 	int major = vdevice >> 8;
979 	int minor = vdevice & 0xff;
980 	int i;
981 
982 	if (vdevice & (1 << 28)) {
983 		*unit = (vdevice & ((1 << 28) - 1)) >> 8;
984 		*name = "xbd";
985 		return;
986 	}
987 
988 	for (i = 0; info[i].major; i++) {
989 		if (info[i].major == major) {
990 			*unit = info[i].base + (minor >> info[i].shift);
991 			*name = info[i].name;
992 			return;
993 		}
994 	}
995 
996 	*unit = minor >> 4;
997 	*name = "xbd";
998 }
999 
1000 int
xbd_instance_create(struct xbd_softc * sc,blkif_sector_t sectors,int vdevice,uint16_t vdisk_info,unsigned long sector_size,unsigned long phys_sector_size)1001 xbd_instance_create(struct xbd_softc *sc, blkif_sector_t sectors,
1002     int vdevice, uint16_t vdisk_info, unsigned long sector_size,
1003     unsigned long phys_sector_size)
1004 {
1005 	char features[80];
1006 	int unit, error = 0;
1007 	const char *name;
1008 
1009 	xbd_vdevice_to_unit(vdevice, &unit, &name);
1010 
1011 	sc->xbd_unit = unit;
1012 
1013 	if (strcmp(name, "xbd") != 0)
1014 		device_printf(sc->xbd_dev, "attaching as %s%d\n", name, unit);
1015 
1016 	if (xbd_feature_string(sc, features, sizeof(features)) > 0) {
1017 		device_printf(sc->xbd_dev, "features: %s\n",
1018 		    features);
1019 	}
1020 
1021 	sc->xbd_disk = disk_alloc();
1022 	sc->xbd_disk->d_unit = sc->xbd_unit;
1023 	sc->xbd_disk->d_open = xbd_open;
1024 	sc->xbd_disk->d_close = xbd_close;
1025 	sc->xbd_disk->d_ioctl = xbd_ioctl;
1026 	sc->xbd_disk->d_strategy = xbd_strategy;
1027 	sc->xbd_disk->d_dump = xbd_dump;
1028 	sc->xbd_disk->d_name = name;
1029 	sc->xbd_disk->d_drv1 = sc;
1030 	sc->xbd_disk->d_sectorsize = sector_size;
1031 	sc->xbd_disk->d_stripesize = phys_sector_size;
1032 	sc->xbd_disk->d_stripeoffset = 0;
1033 
1034 	/*
1035 	 * The 'sectors' xenbus node is always in units of 512b, regardless of
1036 	 * the 'sector-size' xenbus node value.
1037 	 */
1038 	sc->xbd_disk->d_mediasize = sectors << XBD_SECTOR_SHFT;
1039 	if ((sc->xbd_disk->d_mediasize % sc->xbd_disk->d_sectorsize) != 0) {
1040 		error = EINVAL;
1041 		xenbus_dev_fatal(sc->xbd_dev, error,
1042 		    "Disk size (%ju) not a multiple of sector size (%ju)",
1043 		    (uintmax_t)sc->xbd_disk->d_mediasize,
1044 		    (uintmax_t)sc->xbd_disk->d_sectorsize);
1045 		return (error);
1046 	}
1047 	sc->xbd_disk->d_maxsize = sc->xbd_max_request_size;
1048 	sc->xbd_disk->d_flags = DISKFLAG_UNMAPPED_BIO;
1049 	if ((sc->xbd_flags & (XBDF_FLUSH|XBDF_BARRIER)) != 0) {
1050 		sc->xbd_disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1051 		device_printf(sc->xbd_dev,
1052 		    "synchronize cache commands enabled.\n");
1053 	}
1054 	disk_create(sc->xbd_disk, DISK_VERSION);
1055 
1056 	return error;
1057 }
1058 
1059 static void
xbd_free(struct xbd_softc * sc)1060 xbd_free(struct xbd_softc *sc)
1061 {
1062 	int i;
1063 
1064 	/* Prevent new requests being issued until we fix things up. */
1065 	mtx_lock(&sc->xbd_io_lock);
1066 	sc->xbd_state = XBD_STATE_DISCONNECTED;
1067 	mtx_unlock(&sc->xbd_io_lock);
1068 
1069 	/* Free resources associated with old device channel. */
1070 	xbd_free_ring(sc);
1071 	if (sc->xbd_shadow) {
1072 		for (i = 0; i < sc->xbd_max_requests; i++) {
1073 			struct xbd_command *cm;
1074 
1075 			cm = &sc->xbd_shadow[i];
1076 			if (cm->cm_sg_refs != NULL) {
1077 				free(cm->cm_sg_refs, M_XENBLOCKFRONT);
1078 				cm->cm_sg_refs = NULL;
1079 			}
1080 
1081 			if (cm->cm_indirectionpages != NULL) {
1082 				gnttab_end_foreign_access_references(
1083 				    sc->xbd_max_request_indirectpages,
1084 				    &cm->cm_indirectionrefs[0]);
1085 				contigfree(cm->cm_indirectionpages, PAGE_SIZE *
1086 				    sc->xbd_max_request_indirectpages,
1087 				    M_XENBLOCKFRONT);
1088 				cm->cm_indirectionpages = NULL;
1089 			}
1090 
1091 			bus_dmamap_destroy(sc->xbd_io_dmat, cm->cm_map);
1092 		}
1093 		free(sc->xbd_shadow, M_XENBLOCKFRONT);
1094 		sc->xbd_shadow = NULL;
1095 
1096 		bus_dma_tag_destroy(sc->xbd_io_dmat);
1097 
1098 		xbd_initq_cm(sc, XBD_Q_FREE);
1099 		xbd_initq_cm(sc, XBD_Q_READY);
1100 		xbd_initq_cm(sc, XBD_Q_COMPLETE);
1101 	}
1102 
1103 	xen_intr_unbind(&sc->xen_intr_handle);
1104 
1105 }
1106 
1107 /*--------------------------- State Change Handlers --------------------------*/
1108 static void
xbd_initialize(struct xbd_softc * sc)1109 xbd_initialize(struct xbd_softc *sc)
1110 {
1111 	const char *otherend_path;
1112 	const char *node_path;
1113 	uint32_t max_ring_page_order;
1114 	int error;
1115 
1116 	if (xenbus_get_state(sc->xbd_dev) != XenbusStateInitialising) {
1117 		/* Initialization has already been performed. */
1118 		return;
1119 	}
1120 
1121 	/*
1122 	 * Protocol defaults valid even if negotiation for a
1123 	 * setting fails.
1124 	 */
1125 	max_ring_page_order = 0;
1126 	sc->xbd_ring_pages = 1;
1127 
1128 	/*
1129 	 * Protocol negotiation.
1130 	 *
1131 	 * \note xs_gather() returns on the first encountered error, so
1132 	 *       we must use independent calls in order to guarantee
1133 	 *       we don't miss information in a sparsly populated back-end
1134 	 *       tree.
1135 	 *
1136 	 * \note xs_scanf() does not update variables for unmatched
1137 	 *	 fields.
1138 	 */
1139 	otherend_path = xenbus_get_otherend_path(sc->xbd_dev);
1140 	node_path = xenbus_get_node(sc->xbd_dev);
1141 
1142 	/* Support both backend schemes for relaying ring page limits. */
1143 	(void)xs_scanf(XST_NIL, otherend_path,
1144 	    "max-ring-page-order", NULL, "%" PRIu32,
1145 	    &max_ring_page_order);
1146 	sc->xbd_ring_pages = 1 << max_ring_page_order;
1147 	(void)xs_scanf(XST_NIL, otherend_path,
1148 	    "max-ring-pages", NULL, "%" PRIu32,
1149 	    &sc->xbd_ring_pages);
1150 	if (sc->xbd_ring_pages < 1)
1151 		sc->xbd_ring_pages = 1;
1152 
1153 	if (sc->xbd_ring_pages > XBD_MAX_RING_PAGES) {
1154 		device_printf(sc->xbd_dev,
1155 		    "Back-end specified ring-pages of %u "
1156 		    "limited to front-end limit of %u.\n",
1157 		    sc->xbd_ring_pages, XBD_MAX_RING_PAGES);
1158 		sc->xbd_ring_pages = XBD_MAX_RING_PAGES;
1159 	}
1160 
1161 	if (powerof2(sc->xbd_ring_pages) == 0) {
1162 		uint32_t new_page_limit;
1163 
1164 		new_page_limit = 0x01 << (fls(sc->xbd_ring_pages) - 1);
1165 		device_printf(sc->xbd_dev,
1166 		    "Back-end specified ring-pages of %u "
1167 		    "is not a power of 2. Limited to %u.\n",
1168 		    sc->xbd_ring_pages, new_page_limit);
1169 		sc->xbd_ring_pages = new_page_limit;
1170 	}
1171 
1172 	sc->xbd_max_requests =
1173 	    BLKIF_MAX_RING_REQUESTS(sc->xbd_ring_pages * PAGE_SIZE);
1174 	if (sc->xbd_max_requests > XBD_MAX_REQUESTS) {
1175 		device_printf(sc->xbd_dev,
1176 		    "Back-end specified max_requests of %u "
1177 		    "limited to front-end limit of %zu.\n",
1178 		    sc->xbd_max_requests, XBD_MAX_REQUESTS);
1179 		sc->xbd_max_requests = XBD_MAX_REQUESTS;
1180 	}
1181 
1182 	if (xbd_alloc_ring(sc) != 0)
1183 		return;
1184 
1185 	/* Support both backend schemes for relaying ring page limits. */
1186 	if (sc->xbd_ring_pages > 1) {
1187 		error = xs_printf(XST_NIL, node_path,
1188 		    "num-ring-pages","%u",
1189 		    sc->xbd_ring_pages);
1190 		if (error) {
1191 			xenbus_dev_fatal(sc->xbd_dev, error,
1192 			    "writing %s/num-ring-pages",
1193 			    node_path);
1194 			return;
1195 		}
1196 
1197 		error = xs_printf(XST_NIL, node_path,
1198 		    "ring-page-order", "%u",
1199 		    fls(sc->xbd_ring_pages) - 1);
1200 		if (error) {
1201 			xenbus_dev_fatal(sc->xbd_dev, error,
1202 			    "writing %s/ring-page-order",
1203 			    node_path);
1204 			return;
1205 		}
1206 	}
1207 
1208 	error = xs_printf(XST_NIL, node_path, "event-channel",
1209 	    "%u", xen_intr_port(sc->xen_intr_handle));
1210 	if (error) {
1211 		xenbus_dev_fatal(sc->xbd_dev, error,
1212 		    "writing %s/event-channel",
1213 		    node_path);
1214 		return;
1215 	}
1216 
1217 	error = xs_printf(XST_NIL, node_path, "protocol",
1218 	    "%s", XEN_IO_PROTO_ABI_NATIVE);
1219 	if (error) {
1220 		xenbus_dev_fatal(sc->xbd_dev, error,
1221 		    "writing %s/protocol",
1222 		    node_path);
1223 		return;
1224 	}
1225 
1226 	xenbus_set_state(sc->xbd_dev, XenbusStateInitialised);
1227 }
1228 
1229 /*
1230  * Invoked when the backend is finally 'ready' (and has published
1231  * the details about the physical device - #sectors, size, etc).
1232  */
1233 static void
xbd_connect(struct xbd_softc * sc)1234 xbd_connect(struct xbd_softc *sc)
1235 {
1236 	device_t dev = sc->xbd_dev;
1237 	blkif_sector_t sectors;
1238 	unsigned long sector_size, phys_sector_size;
1239 	unsigned int binfo;
1240 	int err, feature_barrier, feature_flush;
1241 	int i, j;
1242 
1243 	DPRINTK("blkfront.c:connect:%s.\n", xenbus_get_otherend_path(dev));
1244 
1245 	if (sc->xbd_state == XBD_STATE_SUSPENDED) {
1246 		return;
1247 	}
1248 
1249 	if (sc->xbd_state == XBD_STATE_CONNECTED) {
1250 		struct disk *disk;
1251 
1252 		disk = sc->xbd_disk;
1253 		if (disk == NULL) {
1254 			return;
1255 		}
1256 		err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1257 		    "sectors", "%"PRIu64, &sectors, NULL);
1258 		if (err != 0) {
1259 			xenbus_dev_error(dev, err,
1260 			    "reading sectors at %s",
1261 			    xenbus_get_otherend_path(dev));
1262 			return;
1263 		}
1264 		disk->d_mediasize = disk->d_sectorsize * sectors;
1265 		err = disk_resize(disk, M_NOWAIT);
1266 		if (err) {
1267 			xenbus_dev_error(dev, err,
1268 			    "unable to resize disk %s%u",
1269 			    disk->d_name, disk->d_unit);
1270 			return;
1271 		}
1272 		device_printf(sc->xbd_dev,
1273 		    "changed capacity to %jd\n",
1274 		    (intmax_t)disk->d_mediasize);
1275 		return;
1276 	}
1277 
1278 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1279 	    "sectors", "%"PRIu64, &sectors,
1280 	    "info", "%u", &binfo,
1281 	    "sector-size", "%lu", &sector_size,
1282 	    NULL);
1283 	if (err) {
1284 		xenbus_dev_fatal(dev, err,
1285 		    "reading backend fields at %s",
1286 		    xenbus_get_otherend_path(dev));
1287 		return;
1288 	}
1289 	if ((sectors == 0) || (sector_size == 0)) {
1290 		xenbus_dev_fatal(dev, 0,
1291 		    "invalid parameters from %s:"
1292 		    " sectors = %"PRIu64", sector_size = %lu",
1293 		    xenbus_get_otherend_path(dev),
1294 		    sectors, sector_size);
1295 		return;
1296 	}
1297 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1298 	     "physical-sector-size", "%lu", &phys_sector_size,
1299 	     NULL);
1300 	if (err || phys_sector_size <= sector_size)
1301 		phys_sector_size = 0;
1302 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1303 	     "feature-barrier", "%d", &feature_barrier,
1304 	     NULL);
1305 	if (err == 0 && feature_barrier != 0)
1306 		sc->xbd_flags |= XBDF_BARRIER;
1307 
1308 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1309 	     "feature-flush-cache", "%d", &feature_flush,
1310 	     NULL);
1311 	if (err == 0 && feature_flush != 0)
1312 		sc->xbd_flags |= XBDF_FLUSH;
1313 
1314 	err = xs_gather(XST_NIL, xenbus_get_otherend_path(dev),
1315 	    "feature-max-indirect-segments", "%" PRIu32,
1316 	    &sc->xbd_max_request_segments, NULL);
1317 	if ((err != 0) || (xbd_enable_indirect == 0))
1318 		sc->xbd_max_request_segments = 0;
1319 	if (sc->xbd_max_request_segments > XBD_MAX_INDIRECT_SEGMENTS)
1320 		sc->xbd_max_request_segments = XBD_MAX_INDIRECT_SEGMENTS;
1321 	if (sc->xbd_max_request_segments > XBD_SIZE_TO_SEGS(maxphys))
1322 		sc->xbd_max_request_segments = XBD_SIZE_TO_SEGS(maxphys);
1323 	sc->xbd_max_request_indirectpages =
1324 	    XBD_INDIRECT_SEGS_TO_PAGES(sc->xbd_max_request_segments);
1325 	if (sc->xbd_max_request_segments < BLKIF_MAX_SEGMENTS_PER_REQUEST)
1326 		sc->xbd_max_request_segments = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1327 	sc->xbd_max_request_size =
1328 	    XBD_SEGS_TO_SIZE(sc->xbd_max_request_segments);
1329 
1330 	/* Allocate datastructures based on negotiated values. */
1331 	err = bus_dma_tag_create(
1332 	    bus_get_dma_tag(sc->xbd_dev),	/* parent */
1333 	    sector_size, PAGE_SIZE,		/* algnmnt, boundary */
1334 	    BUS_SPACE_MAXADDR,			/* lowaddr */
1335 	    BUS_SPACE_MAXADDR,			/* highaddr */
1336 	    NULL, NULL,				/* filter, filterarg */
1337 	    sc->xbd_max_request_size,
1338 	    sc->xbd_max_request_segments,
1339 	    PAGE_SIZE,				/* maxsegsize */
1340 	    BUS_DMA_ALLOCNOW,			/* flags */
1341 	    busdma_lock_mutex,			/* lockfunc */
1342 	    &sc->xbd_io_lock,			/* lockarg */
1343 	    &sc->xbd_io_dmat);
1344 	if (err != 0) {
1345 		xenbus_dev_fatal(sc->xbd_dev, err,
1346 		    "Cannot allocate parent DMA tag\n");
1347 		return;
1348 	}
1349 
1350 	/* Per-transaction data allocation. */
1351 	sc->xbd_shadow = malloc(sizeof(*sc->xbd_shadow) * sc->xbd_max_requests,
1352 	    M_XENBLOCKFRONT, M_NOWAIT|M_ZERO);
1353 	if (sc->xbd_shadow == NULL) {
1354 		bus_dma_tag_destroy(sc->xbd_io_dmat);
1355 		xenbus_dev_fatal(sc->xbd_dev, ENOMEM,
1356 		    "Cannot allocate request structures\n");
1357 		return;
1358 	}
1359 
1360 	for (i = 0; i < sc->xbd_max_requests; i++) {
1361 		struct xbd_command *cm;
1362 		void * indirectpages;
1363 
1364 		cm = &sc->xbd_shadow[i];
1365 		cm->cm_sg_refs = malloc(
1366 		    sizeof(grant_ref_t) * sc->xbd_max_request_segments,
1367 		    M_XENBLOCKFRONT, M_NOWAIT);
1368 		if (cm->cm_sg_refs == NULL)
1369 			break;
1370 		cm->cm_id = i;
1371 		cm->cm_flags = XBDCF_INITIALIZER;
1372 		cm->cm_sc = sc;
1373 		if (bus_dmamap_create(sc->xbd_io_dmat, 0, &cm->cm_map) != 0)
1374 			break;
1375 		if (sc->xbd_max_request_indirectpages > 0) {
1376 			indirectpages = contigmalloc(
1377 			    PAGE_SIZE * sc->xbd_max_request_indirectpages,
1378 			    M_XENBLOCKFRONT, M_ZERO | M_NOWAIT, 0, ~0,
1379 			    PAGE_SIZE, 0);
1380 			if (indirectpages == NULL)
1381 				sc->xbd_max_request_indirectpages = 0;
1382 		} else {
1383 			indirectpages = NULL;
1384 		}
1385 		for (j = 0; j < sc->xbd_max_request_indirectpages; j++) {
1386 			if (gnttab_grant_foreign_access(
1387 			    xenbus_get_otherend_id(sc->xbd_dev),
1388 			    (vtophys(indirectpages) >> PAGE_SHIFT) + j,
1389 			    1 /* grant read-only access */,
1390 			    &cm->cm_indirectionrefs[j]))
1391 				break;
1392 		}
1393 		if (j < sc->xbd_max_request_indirectpages) {
1394 			contigfree(indirectpages,
1395 			    PAGE_SIZE * sc->xbd_max_request_indirectpages,
1396 			    M_XENBLOCKFRONT);
1397 			break;
1398 		}
1399 		cm->cm_indirectionpages = indirectpages;
1400 		xbd_free_command(cm);
1401 	}
1402 
1403 	if (sc->xbd_disk == NULL) {
1404 		device_printf(dev, "%juMB <%s> at %s",
1405 		    (uintmax_t)((sectors << XBD_SECTOR_SHFT) / 1048576),
1406 		    device_get_desc(dev),
1407 		    xenbus_get_node(dev));
1408 		bus_print_child_footer(device_get_parent(dev), dev);
1409 
1410 		err = xbd_instance_create(sc, sectors, sc->xbd_vdevice, binfo,
1411 		    sector_size, phys_sector_size);
1412 		if (err != 0) {
1413 			xenbus_dev_fatal(dev, err, "Unable to create instance");
1414 			return;
1415 		}
1416 	}
1417 
1418 	(void)xenbus_set_state(dev, XenbusStateConnected);
1419 
1420 	/* Kick pending requests. */
1421 	mtx_lock(&sc->xbd_io_lock);
1422 	sc->xbd_state = XBD_STATE_CONNECTED;
1423 	xbd_startio(sc);
1424 	sc->xbd_flags |= XBDF_READY;
1425 	mtx_unlock(&sc->xbd_io_lock);
1426 }
1427 
1428 /**
1429  * Handle the change of state of the backend to Closing.  We must delete our
1430  * device-layer structures now, to ensure that writes are flushed through to
1431  * the backend.  Once this is done, we can switch to Closed in
1432  * acknowledgement.
1433  */
1434 static void
xbd_closing(device_t dev)1435 xbd_closing(device_t dev)
1436 {
1437 	struct xbd_softc *sc = device_get_softc(dev);
1438 
1439 	xenbus_set_state(dev, XenbusStateClosing);
1440 
1441 	DPRINTK("xbd_closing: %s removed\n", xenbus_get_node(dev));
1442 
1443 	if (sc->xbd_disk != NULL) {
1444 		disk_destroy(sc->xbd_disk);
1445 		sc->xbd_disk = NULL;
1446 	}
1447 
1448 	xenbus_set_state(dev, XenbusStateClosed);
1449 }
1450 
1451 /*---------------------------- NewBus Entrypoints ----------------------------*/
1452 static int
xbd_probe(device_t dev)1453 xbd_probe(device_t dev)
1454 {
1455 	if (strcmp(xenbus_get_type(dev), "vbd") != 0)
1456 		return (ENXIO);
1457 
1458 	if (xen_pv_disks_disabled())
1459 		return (ENXIO);
1460 
1461 	if (xen_hvm_domain()) {
1462 		int error;
1463 		char *type;
1464 
1465 		/*
1466 		 * When running in an HVM domain, IDE disk emulation is
1467 		 * disabled early in boot so that native drivers will
1468 		 * not see emulated hardware.  However, CDROM device
1469 		 * emulation cannot be disabled.
1470 		 *
1471 		 * Through use of FreeBSD's vm_guest and xen_hvm_domain()
1472 		 * APIs, we could modify the native CDROM driver to fail its
1473 		 * probe when running under Xen.  Unfortunatlely, the PV
1474 		 * CDROM support in XenServer (up through at least version
1475 		 * 6.2) isn't functional, so we instead rely on the emulated
1476 		 * CDROM instance, and fail to attach the PV one here in
1477 		 * the blkfront driver.
1478 		 */
1479 		error = xs_read(XST_NIL, xenbus_get_node(dev),
1480 		    "device-type", NULL, (void **) &type);
1481 		if (error)
1482 			return (ENXIO);
1483 
1484 		if (strncmp(type, "cdrom", 5) == 0) {
1485 			free(type, M_XENSTORE);
1486 			return (ENXIO);
1487 		}
1488 		free(type, M_XENSTORE);
1489 	}
1490 
1491 	device_set_desc(dev, "Virtual Block Device");
1492 	device_quiet(dev);
1493 	return (0);
1494 }
1495 
1496 /*
1497  * Setup supplies the backend dir, virtual device.  We place an event
1498  * channel and shared frame entries.  We watch backend to wait if it's
1499  * ok.
1500  */
1501 static int
xbd_attach(device_t dev)1502 xbd_attach(device_t dev)
1503 {
1504 	struct xbd_softc *sc;
1505 	const char *name;
1506 	uint32_t vdevice;
1507 	int error;
1508 	int i;
1509 	int unit;
1510 
1511 	/* FIXME: Use dynamic device id if this is not set. */
1512 	error = xs_scanf(XST_NIL, xenbus_get_node(dev),
1513 	    "virtual-device", NULL, "%" PRIu32, &vdevice);
1514 	if (error)
1515 		error = xs_scanf(XST_NIL, xenbus_get_node(dev),
1516 		    "virtual-device-ext", NULL, "%" PRIu32, &vdevice);
1517 	if (error) {
1518 		xenbus_dev_fatal(dev, error, "reading virtual-device");
1519 		device_printf(dev, "Couldn't determine virtual device.\n");
1520 		return (error);
1521 	}
1522 
1523 	xbd_vdevice_to_unit(vdevice, &unit, &name);
1524 	if (!strcmp(name, "xbd"))
1525 		device_set_unit(dev, unit);
1526 
1527 	sc = device_get_softc(dev);
1528 	mtx_init(&sc->xbd_io_lock, "blkfront i/o lock", NULL, MTX_DEF);
1529 	xbd_initqs(sc);
1530 	for (i = 0; i < XBD_MAX_RING_PAGES; i++)
1531 		sc->xbd_ring_ref[i] = GRANT_REF_INVALID;
1532 
1533 	sc->xbd_dev = dev;
1534 	sc->xbd_vdevice = vdevice;
1535 	sc->xbd_state = XBD_STATE_DISCONNECTED;
1536 
1537 	xbd_setup_sysctl(sc);
1538 
1539 	/* Wait for backend device to publish its protocol capabilities. */
1540 	xenbus_set_state(dev, XenbusStateInitialising);
1541 
1542 	return (0);
1543 }
1544 
1545 static int
xbd_detach(device_t dev)1546 xbd_detach(device_t dev)
1547 {
1548 	struct xbd_softc *sc = device_get_softc(dev);
1549 
1550 	DPRINTK("%s: %s removed\n", __func__, xenbus_get_node(dev));
1551 
1552 	xbd_free(sc);
1553 	mtx_destroy(&sc->xbd_io_lock);
1554 
1555 	return 0;
1556 }
1557 
1558 static int
xbd_suspend(device_t dev)1559 xbd_suspend(device_t dev)
1560 {
1561 	struct xbd_softc *sc = device_get_softc(dev);
1562 	int retval;
1563 	int saved_state;
1564 
1565 	/* Prevent new requests being issued until we fix things up. */
1566 	mtx_lock(&sc->xbd_io_lock);
1567 	saved_state = sc->xbd_state;
1568 	sc->xbd_state = XBD_STATE_SUSPENDED;
1569 
1570 	/* Wait for outstanding I/O to drain. */
1571 	retval = 0;
1572 	while (xbd_queue_length(sc, XBD_Q_BUSY) != 0) {
1573 		if (msleep(&sc->xbd_cm_q[XBD_Q_BUSY], &sc->xbd_io_lock,
1574 		    PRIBIO, "blkf_susp", 30 * hz) == EWOULDBLOCK) {
1575 			retval = EBUSY;
1576 			break;
1577 		}
1578 	}
1579 	mtx_unlock(&sc->xbd_io_lock);
1580 
1581 	if (retval != 0)
1582 		sc->xbd_state = saved_state;
1583 
1584 	return (retval);
1585 }
1586 
1587 static int
xbd_resume(device_t dev)1588 xbd_resume(device_t dev)
1589 {
1590 	struct xbd_softc *sc = device_get_softc(dev);
1591 
1592 	if (xen_suspend_cancelled) {
1593 		sc->xbd_state = XBD_STATE_CONNECTED;
1594 		return (0);
1595 	}
1596 
1597 	DPRINTK("xbd_resume: %s\n", xenbus_get_node(dev));
1598 
1599 	xbd_free(sc);
1600 	xbd_initialize(sc);
1601 	return (0);
1602 }
1603 
1604 /**
1605  * Callback received when the backend's state changes.
1606  */
1607 static void
xbd_backend_changed(device_t dev,XenbusState backend_state)1608 xbd_backend_changed(device_t dev, XenbusState backend_state)
1609 {
1610 	struct xbd_softc *sc = device_get_softc(dev);
1611 
1612 	DPRINTK("backend_state=%d\n", backend_state);
1613 
1614 	switch (backend_state) {
1615 	case XenbusStateUnknown:
1616 	case XenbusStateInitialising:
1617 	case XenbusStateReconfigured:
1618 	case XenbusStateReconfiguring:
1619 	case XenbusStateClosed:
1620 		break;
1621 
1622 	case XenbusStateInitWait:
1623 	case XenbusStateInitialised:
1624 		xbd_initialize(sc);
1625 		break;
1626 
1627 	case XenbusStateConnected:
1628 		xbd_initialize(sc);
1629 		xbd_connect(sc);
1630 		break;
1631 
1632 	case XenbusStateClosing:
1633 		if (sc->xbd_users > 0) {
1634 			device_printf(dev, "detaching with pending users\n");
1635 			KASSERT(sc->xbd_disk != NULL,
1636 			    ("NULL disk with pending users\n"));
1637 			disk_gone(sc->xbd_disk);
1638 		} else {
1639 			xbd_closing(dev);
1640 		}
1641 		break;
1642 	}
1643 }
1644 
1645 /*---------------------------- NewBus Registration ---------------------------*/
1646 static device_method_t xbd_methods[] = {
1647 	/* Device interface */
1648 	DEVMETHOD(device_probe,         xbd_probe),
1649 	DEVMETHOD(device_attach,        xbd_attach),
1650 	DEVMETHOD(device_detach,        xbd_detach),
1651 	DEVMETHOD(device_shutdown,      bus_generic_shutdown),
1652 	DEVMETHOD(device_suspend,       xbd_suspend),
1653 	DEVMETHOD(device_resume,        xbd_resume),
1654 
1655 	/* Xenbus interface */
1656 	DEVMETHOD(xenbus_otherend_changed, xbd_backend_changed),
1657 
1658 	{ 0, 0 }
1659 };
1660 
1661 static driver_t xbd_driver = {
1662 	"xbd",
1663 	xbd_methods,
1664 	sizeof(struct xbd_softc),
1665 };
1666 
1667 DRIVER_MODULE(xbd, xenbusb_front, xbd_driver, 0, 0);
1668