Don't use B_PAGING with geteblk() bufs
[dragonfly.git] / sys / dev / raid / vinum / vinumrequest.c
1 /*-
2  * Copyright (c) 1997, 1998, 1999
3  *  Nan Yang Computer Services Limited.  All rights reserved.
4  *
5  *  Parts copyright (c) 1997, 1998 Cybernet Corporation, NetMAX project.
6  *
7  *  Written by Greg Lehey
8  *
9  *  This software is distributed under the so-called ``Berkeley
10  *  License'':
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by Nan Yang Computer
23  *      Services Limited.
24  * 4. Neither the name of the Company nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * This software is provided ``as is'', and any express or implied
29  * warranties, including, but not limited to, the implied warranties of
30  * merchantability and fitness for a particular purpose are disclaimed.
31  * In no event shall the company or contributors be liable for any
32  * direct, indirect, incidental, special, exemplary, or consequential
33  * damages (including, but not limited to, procurement of substitute
34  * goods or services; loss of use, data, or profits; or business
35  * interruption) however caused and on any theory of liability, whether
36  * in contract, strict liability, or tort (including negligence or
37  * otherwise) arising in any way out of the use of this software, even if
38  * advised of the possibility of such damage.
39  *
40  * $Id: vinumrequest.c,v 1.30 2001/01/09 04:20:55 grog Exp grog $
41  * $FreeBSD: src/sys/dev/vinum/vinumrequest.c,v 1.44.2.5 2002/08/28 04:30:56 grog Exp $
42  * $DragonFly: src/sys/dev/raid/vinum/vinumrequest.c,v 1.15 2006/07/09 22:55:45 corecode Exp $
43  */
44
45 #include "vinumhdr.h"
46 #include "request.h"
47 #include <sys/resourcevar.h>
48
49 enum requeststatus bre(struct request *rq,
50     int plexno,
51     daddr_t * diskstart,
52     daddr_t diskend);
53 enum requeststatus bre5(struct request *rq,
54     int plexno,
55     daddr_t * diskstart,
56     daddr_t diskend);
57 enum requeststatus build_read_request(struct request *rq, int volplexno);
58 enum requeststatus build_write_request(struct request *rq);
59 enum requeststatus build_rq_buffer(struct rqelement *rqe, struct plex *plex);
60 int find_alternate_sd(struct request *rq);
61 int check_range_covered(struct request *);
62 void complete_rqe(struct bio *bio);
63 void complete_raid5_write(struct rqelement *);
64 int abortrequest(struct request *rq, int error);
65 void sdio_done(struct bio *bio);
66 struct bio *vinum_bounds_check(struct bio *bio, struct volume *vol);
67 caddr_t allocdatabuf(struct rqelement *rqe);
68 void freedatabuf(struct rqelement *rqe);
69
70 #ifdef VINUMDEBUG
71 struct rqinfo rqinfo[RQINFO_SIZE];
72 struct rqinfo *rqip = rqinfo;
73
74 void
75 logrq(enum rqinfo_type type, union rqinfou info, struct bio *ubio)
76 {
77     dev_t dev;
78
79     crit_enter();
80
81     microtime(&rqip->timestamp);                            /* when did this happen? */
82     rqip->type = type;
83     rqip->bio = ubio;                                       /* user buffer */
84
85     switch (type) {
86     case loginfo_user_bp:
87     case loginfo_user_bpl:
88     case loginfo_sdio:                                      /* subdisk I/O */
89     case loginfo_sdiol:                                     /* subdisk I/O launch */
90     case loginfo_sdiodone:                                  /* subdisk I/O complete */
91         bcopy(info.bio, &rqip->info.bio, sizeof(struct bio));
92         dev = info.bio->bio_driver_info;
93         rqip->devmajor = major(dev);
94         rqip->devminor = minor(dev);
95         break;
96
97     case loginfo_iodone:
98     case loginfo_rqe:
99     case loginfo_raid5_data:
100     case loginfo_raid5_parity:
101         bcopy(info.rqe, &rqip->info.rqe, sizeof(struct rqelement));
102         dev = info.rqe->b.b_bio1.bio_driver_info;
103         rqip->devmajor = major(dev);
104         rqip->devminor = minor(dev);
105         break;
106
107     case loginfo_lockwait:
108     case loginfo_lock:
109     case loginfo_unlock:
110         bcopy(info.lockinfo, &rqip->info.lockinfo, sizeof(struct rangelock));
111
112         break;
113
114     case loginfo_unused:
115         break;
116     }
117     rqip++;
118     if (rqip >= &rqinfo[RQINFO_SIZE])                       /* wrap around */
119         rqip = rqinfo;
120     crit_exit();
121 }
122
123 #endif
124
125 void
126 vinumstrategy(dev_t dev, struct bio *bio)
127 {
128     struct buf *bp = bio->bio_buf;
129     struct bio *nbio = bio;
130     struct volume *vol = NULL;
131     int volno;
132
133     switch (DEVTYPE(dev)) {
134     case VINUM_SD_TYPE:
135     case VINUM_RAWSD_TYPE:
136         bio->bio_driver_info = dev;
137         sdio(bio);
138         return;
139
140         /*
141          * In fact, vinum doesn't handle drives: they're
142          * handled directly by the disk drivers
143          */
144     case VINUM_DRIVE_TYPE:
145     default:
146         bp->b_error = EIO;                                  /* I/O error */
147         bp->b_flags |= B_ERROR;
148         biodone(bio);
149         return;
150
151     case VINUM_VOLUME_TYPE:                                 /* volume I/O */
152         volno = Volno(dev);
153         vol = &VOL[volno];
154         if (vol->state != volume_up) {                      /* can't access this volume */
155             bp->b_error = EIO;                              /* I/O error */
156             bp->b_flags |= B_ERROR;
157             biodone(bio);
158             return;
159         }
160         nbio = vinum_bounds_check(bio, vol);
161         if (nbio == NULL) {
162             biodone(bio);
163             return;
164         }
165         /* FALLTHROUGH */
166         /*
167          * Plex I/O is pretty much the same as volume I/O
168          * for a single plex.  Indicate this by passing a NULL
169          * pointer (set above) for the volume
170          */
171     case VINUM_PLEX_TYPE:
172     case VINUM_RAWPLEX_TYPE:
173         bp->b_resid = bp->b_bcount;                         /* transfer everything */
174         vinumstart(dev, nbio, 0);
175         return;
176     }
177 }
178
179 /*
180  * Start a transfer.  Return -1 on error,
181  * 0 if OK, 1 if we need to retry.
182  * Parameter reviveok is set when doing
183  * transfers for revives: it allows transfers to
184  * be started immediately when a revive is in
185  * progress.  During revive, normal transfers
186  * are queued if they share address space with
187  * a currently active revive operation.
188  */
189 int
190 vinumstart(dev_t dev, struct bio *bio, int reviveok)
191 {
192     struct buf *bp = bio->bio_buf;
193     int plexno;
194     int maxplex;                                            /* maximum number of plexes to handle */
195     struct volume *vol;
196     struct request *rq;                                     /* build up our request here */
197     enum requeststatus status;
198
199     bio->bio_driver_info = dev;
200
201 #if VINUMDEBUG
202     if (debug & DEBUG_LASTREQS)
203         logrq(loginfo_user_bp, (union rqinfou) bio, bio);
204 #endif
205
206     if ((bp->b_bcount % DEV_BSIZE) != 0) {                  /* bad length */
207         bp->b_error = EINVAL;                               /* invalid size */
208         bp->b_flags |= B_ERROR;
209         biodone(bio);
210         return -1;
211     }
212     rq = (struct request *) Malloc(sizeof(struct request)); /* allocate a request struct */
213     if (rq == NULL) {                                       /* can't do it */
214         bp->b_error = ENOMEM;                               /* can't get memory */
215         bp->b_flags |= B_ERROR;
216         biodone(bio);
217         return -1;
218     }
219     bzero(rq, sizeof(struct request));
220
221     /*
222      * Note the volume ID.  This can be NULL, which
223      * the request building functions use as an
224      * indication for single plex I/O
225      */
226     rq->bio = bio;                                          /* and the user buffer struct */
227
228     if (DEVTYPE(dev) == VINUM_VOLUME_TYPE) {        /* it's a volume, */
229         rq->volplex.volno = Volno(dev);             /* get the volume number */
230         vol = &VOL[rq->volplex.volno];                      /* and point to it */
231         vol->active++;                                      /* one more active request */
232         maxplex = vol->plexes;                              /* consider all its plexes */
233     } else {
234         vol = NULL;                                         /* no volume */
235         rq->volplex.plexno = Plexno(dev);                   /* point to the plex */
236         rq->isplex = 1;                                     /* note that it's a plex */
237         maxplex = 1;                                        /* just the one plex */
238     }
239
240     if (bp->b_cmd == BUF_CMD_READ) {
241         /*
242          * This is a read request.  Decide
243          * which plex to read from.
244          *
245          * There's a potential race condition here,
246          * since we're not locked, and we could end
247          * up multiply incrementing the round-robin
248          * counter.  This doesn't have any serious
249          * effects, however.
250          */
251         if (vol != NULL) {
252             plexno = vol->preferred_plex;                   /* get the plex to use */
253             if (plexno < 0) {                               /* round robin */
254                 plexno = vol->last_plex_read;
255                 vol->last_plex_read++;
256                 if (vol->last_plex_read >= vol->plexes)     /* got the the end? */
257                     vol->last_plex_read = 0;                /* wrap around */
258             }
259             status = build_read_request(rq, plexno);        /* build a request */
260         } else {
261             daddr_t diskaddr = (daddr_t)(bio->bio_offset >> DEV_BSHIFT);
262                                                             /* start offset of transfer */
263             status = bre(rq,                                /* build a request list */
264                 rq->volplex.plexno,
265                 &diskaddr,
266                 diskaddr + (bp->b_bcount / DEV_BSIZE));
267         }
268
269         if (status > REQUEST_RECOVERED) {                   /* can't satisfy it */
270             if (status == REQUEST_DOWN) {                   /* not enough subdisks */
271                 bp->b_error = EIO;                          /* I/O error */
272                 bp->b_flags |= B_ERROR;
273             }
274             biodone(bio);
275             freerq(rq);
276             return -1;
277         }
278         return launch_requests(rq, reviveok);               /* now start the requests if we can */
279     } else
280         /*
281          * This is a write operation.  We write to all plexes.  If this is
282          * a RAID-4 or RAID-5 plex, we must also update the parity stripe.
283          */
284     {
285         if (vol != NULL)
286             status = build_write_request(rq);               /* Not all the subdisks are up */
287         else {                                              /* plex I/O */
288             daddr_t diskstart;
289             daddr_t diskend;
290
291             diskstart = (daddr_t)(bio->bio_offset >> DEV_BSHIFT); /* start offset of transfer */
292             diskend = diskstart + bp->b_bcount / DEV_BSIZE;
293             status = bre(rq, Plexno(dev),
294                 &diskstart, diskend);  /* build requests for the plex */
295         }
296         if (status > REQUEST_RECOVERED) {                   /* can't satisfy it */
297             if (status == REQUEST_DOWN) {                   /* not enough subdisks */
298                 bp->b_error = EIO;                          /* I/O error */
299                 bp->b_flags |= B_ERROR;
300             }
301             biodone(bio);
302             freerq(rq);
303             return -1;
304         }
305         return launch_requests(rq, reviveok);               /* now start the requests if we can */
306     }
307 }
308
309 /*
310  * Call the low-level strategy routines to
311  * perform the requests in a struct request
312  */
313 int
314 launch_requests(struct request *rq, int reviveok)
315 {
316     struct rqgroup *rqg;
317     int rqno;                                               /* loop index */
318     struct rqelement *rqe;                                  /* current element */
319     struct drive *drive;
320     int rcount;                                             /* request count */
321
322     /*
323      * First find out whether we're reviving, and the
324      * request contains a conflict.  If so, we hang
325      * the request off plex->waitlist of the first
326      * plex we find which is reviving
327      */
328
329     if ((rq->flags & XFR_REVIVECONFLICT)                    /* possible revive conflict */
330     &&(!reviveok)) {                                        /* and we don't want to do it now, */
331         struct sd *sd;
332         struct request *waitlist;                           /* point to the waitlist */
333
334         sd = &SD[rq->sdno];
335         if (sd->waitlist != NULL) {                         /* something there already, */
336             waitlist = sd->waitlist;
337             while (waitlist->next != NULL)                  /* find the end */
338                 waitlist = waitlist->next;
339             waitlist->next = rq;                            /* hook our request there */
340         } else
341             sd->waitlist = rq;                              /* hook our request at the front */
342
343 #if VINUMDEBUG
344         if (debug & DEBUG_REVIVECONFLICT) {
345             log(LOG_DEBUG,
346                 "Revive conflict sd %d: %p\n%s dev %d.%d, offset 0x%llx, length %d\n",
347                 rq->sdno,
348                 rq,
349                 (rq->bio->bio_buf->b_cmd & BUF_CMD_READ) ? "Read" : "Write",
350                 major(((dev_t)rq->bio->bio_driver_info)),
351                 minor(((dev_t)rq->bio->bio_driver_info)),
352                 rq->bio->bio_offset,
353                 rq->bio->bio_buf->b_bcount);
354         }
355 #endif
356         return 0;                                           /* and get out of here */
357     }
358     rq->active = 0;                                         /* nothing yet */
359 #if VINUMDEBUG
360     if (debug & DEBUG_ADDRESSES)
361         log(LOG_DEBUG,
362             "Request: %p\n%s dev %d.%d, offset 0x%llx, length %d\n",
363             rq,
364             (rq->bio->bio_buf->b_cmd == BUF_CMD_READ) ? "Read" : "Write",
365             major(((dev_t)rq->bio->bio_driver_info)),
366             minor(((dev_t)rq->bio->bio_driver_info)),
367             rq->bio->bio_offset,
368             rq->bio->bio_buf->b_bcount);
369     vinum_conf.lastrq = rq;
370     vinum_conf.lastbio = rq->bio;
371     if (debug & DEBUG_LASTREQS)
372         logrq(loginfo_user_bpl, (union rqinfou) rq->bio, rq->bio);
373 #endif
374
375     /*
376      * This loop happens without any participation
377      * of the bottom half, so it requires no
378      * protection.
379      */
380     for (rqg = rq->rqg; rqg != NULL; rqg = rqg->next) {     /* through the whole request chain */
381         rqg->active = rqg->count;                           /* they're all active */
382         for (rqno = 0; rqno < rqg->count; rqno++) {
383             rqe = &rqg->rqe[rqno];
384             if (rqe->flags & XFR_BAD_SUBDISK)               /* this subdisk is bad, */
385                 rqg->active--;                              /* one less active request */
386         }
387         if (rqg->active)                                    /* we have at least one active request, */
388             rq->active++;                                   /* one more active request group */
389     }
390
391     /*
392      * Now fire off the requests.  In this loop the
393      * bottom half could be completing requests
394      * before we finish, so we need critical section protection.
395      */
396     crit_enter();
397     for (rqg = rq->rqg; rqg != NULL;) {                     /* through the whole request chain */
398         if (rqg->lockbase >= 0)                             /* this rqg needs a lock first */
399             rqg->lock = lockrange(rqg->lockbase, rqg->rq->bio->bio_buf, &PLEX[rqg->plexno]);
400         rcount = rqg->count;
401         for (rqno = 0; rqno < rcount;) {
402             dev_t dev;
403
404             rqe = &rqg->rqe[rqno];
405
406             /*
407              * Point to next rqg before the bottom end
408              * changes the structures.
409              */
410             if (++rqno >= rcount)
411                 rqg = rqg->next;
412             if ((rqe->flags & XFR_BAD_SUBDISK) == 0) {      /* this subdisk is good, */
413                 drive = &DRIVE[rqe->driveno];               /* look at drive */
414                 drive->active++;
415                 if (drive->active >= drive->maxactive)
416                     drive->maxactive = drive->active;
417                 vinum_conf.active++;
418                 if (vinum_conf.active >= vinum_conf.maxactive)
419                     vinum_conf.maxactive = vinum_conf.active;
420
421                 dev = rqe->b.b_bio1.bio_driver_info;
422 #ifdef VINUMDEBUG
423                 if (debug & DEBUG_ADDRESSES)
424                     log(LOG_DEBUG,
425                         "  %s dev %d.%d, sd %d, offset 0x%llx, devoffset 0x%llx, length %d\n",
426                         (rqe->b.b_cmd == BUF_CMD_READ) ? "Read" : "Write",
427                         major(dev),
428                         minor(dev),
429                         rqe->sdno,
430                         rqe->b.b_bio1.bio_offset - ((off_t)SD[rqe->sdno].driveoffset << DEV_BSHIFT),
431                         rqe->b.b_bio1.bio_offset,
432                         rqe->b.b_bcount);
433                 if (debug & DEBUG_LASTREQS)
434                     logrq(loginfo_rqe, (union rqinfou) rqe, rq->bio);
435 #endif
436                 /* fire off the request */
437                 dev_dstrategy(dev, &rqe->b.b_bio1);
438             }
439         }
440     }
441     crit_exit();
442     return 0;
443 }
444
445 /*
446  * define the low-level requests needed to perform a
447  * high-level I/O operation for a specific plex 'plexno'.
448  *
449  * Return REQUEST_OK if all subdisks involved in the request are up,
450  * REQUEST_DOWN if some subdisks are not up, and REQUEST_EOF if the
451  * request is at least partially outside the bounds of the subdisks.
452  *
453  * Modify the pointer *diskstart to point to the end address.  On
454  * read, return on the first bad subdisk, so that the caller
455  * (build_read_request) can try alternatives.
456  *
457  * On entry to this routine, the rqg structures are not assigned.  The
458  * assignment is performed by expandrq().  Strictly speaking, the
459  * elements rqe->sdno of all entries should be set to -1, since 0
460  * (from bzero) is a valid subdisk number.  We avoid this problem by
461  * initializing the ones we use, and not looking at the others (index
462  * >= rqg->requests).
463  */
464 enum requeststatus
465 bre(struct request *rq,
466     int plexno,
467     daddr_t * diskaddr,
468     daddr_t diskend)
469 {
470     int sdno;
471     struct sd *sd;
472     struct rqgroup *rqg;
473     struct bio *bio;
474     struct buf *bp;                                         /* user's bp */
475     struct plex *plex;
476     enum requeststatus status;                              /* return value */
477     daddr_t plexoffset;                                     /* offset of transfer in plex */
478     daddr_t stripebase;                                     /* base address of stripe (1st subdisk) */
479     daddr_t stripeoffset;                                   /* offset in stripe */
480     daddr_t blockoffset;                                    /* offset in stripe on subdisk */
481     struct rqelement *rqe;                                  /* point to this request information */
482     daddr_t diskstart = *diskaddr;                          /* remember where this transfer starts */
483     enum requeststatus s;                                   /* temp return value */
484
485     bio = rq->bio;                                          /* buffer pointer */
486     bp = bio->bio_buf;
487     status = REQUEST_OK;                                    /* return value: OK until proven otherwise */
488     plex = &PLEX[plexno];                                   /* point to the plex */
489
490     switch (plex->organization) {
491     case plex_concat:
492         sd = NULL;                                          /* (keep compiler quiet) */
493         for (sdno = 0; sdno < plex->subdisks; sdno++) {
494             sd = &SD[plex->sdnos[sdno]];
495             if (*diskaddr < sd->plexoffset)                 /* we must have a hole, */
496                 status = REQUEST_DEGRADED;                  /* note the fact */
497             if (*diskaddr < (sd->plexoffset + sd->sectors)) { /* the request starts in this subdisk */
498                 rqg = allocrqg(rq, 1);                      /* space for the request */
499                 if (rqg == NULL) {                          /* malloc failed */
500                     bp->b_error = ENOMEM;
501                     bp->b_flags |= B_ERROR;
502                     return REQUEST_ENOMEM;
503                 }
504                 rqg->plexno = plexno;
505
506                 rqe = &rqg->rqe[0];                         /* point to the element */
507                 rqe->rqg = rqg;                             /* group */
508                 rqe->sdno = sd->sdno;                       /* put in the subdisk number */
509                 plexoffset = *diskaddr;                     /* start offset in plex */
510                 rqe->sdoffset = plexoffset - sd->plexoffset; /* start offset in subdisk */
511                 rqe->useroffset = plexoffset - diskstart;   /* start offset in user buffer */
512                 rqe->dataoffset = 0;
513                 rqe->datalen = min(diskend - *diskaddr,     /* number of sectors to transfer in this sd */
514                     sd->sectors - rqe->sdoffset);
515                 rqe->groupoffset = 0;                       /* no groups for concatenated plexes */
516                 rqe->grouplen = 0;
517                 rqe->buflen = rqe->datalen;                 /* buffer length is data buffer length */
518                 rqe->flags = 0;
519                 rqe->driveno = sd->driveno;
520                 if (sd->state != sd_up) {                   /* *now* we find the sd is down */
521                     s = checksdstate(sd, rq, *diskaddr, diskend); /* do we need to change state? */
522                     if (s == REQUEST_DOWN) {                /* down? */
523                         rqe->flags = XFR_BAD_SUBDISK;       /* yup */
524                         if (rq->bio->bio_buf->b_cmd == BUF_CMD_READ)    /* read request, */
525                             return REQUEST_DEGRADED;        /* give up here */
526                         /*
527                          * If we're writing, don't give up
528                          * because of a bad subdisk.  Go
529                          * through to the bitter end, but note
530                          * which ones we can't access.
531                          */
532                         status = REQUEST_DEGRADED;          /* can't do it all */
533                     }
534                 }
535                 *diskaddr += rqe->datalen;                  /* bump the address */
536                 if (build_rq_buffer(rqe, plex)) {           /* build the buffer */
537                     deallocrqg(rqg);
538                     bp->b_error = ENOMEM;
539                     bp->b_flags |= B_ERROR;
540                     return REQUEST_ENOMEM;                  /* can't do it */
541                 }
542             }
543             if (*diskaddr == diskend)                       /* we're finished, */
544                 break;                                      /* get out of here */
545         }
546         /*
547          * We've got to the end of the plex.  Have we got to the end of
548          * the transfer?  It would seem that having an offset beyond the
549          * end of the subdisk is an error, but in fact it can happen if
550          * the volume has another plex of different size.  There's a valid
551          * question as to why you would want to do this, but currently
552          * it's allowed.
553          *
554          * In a previous version, I returned REQUEST_DOWN here.  I think
555          * REQUEST_EOF is more appropriate now.
556          */
557         if (diskend > sd->sectors + sd->plexoffset)         /* pointing beyond EOF? */
558             status = REQUEST_EOF;
559         break;
560
561     case plex_striped:
562         {
563             while (*diskaddr < diskend) {                   /* until we get it all sorted out */
564                 if (*diskaddr >= plex->length)              /* beyond the end of the plex */
565                     return REQUEST_EOF;                     /* can't continue */
566
567                 /* The offset of the start address from the start of the stripe. */
568                 stripeoffset = *diskaddr % (plex->stripesize * plex->subdisks);
569
570                 /* The plex-relative address of the start of the stripe. */
571                 stripebase = *diskaddr - stripeoffset;
572
573                 /* The number of the subdisk in which the start is located. */
574                 sdno = stripeoffset / plex->stripesize;
575
576                 /* The offset from the beginning of the stripe on this subdisk. */
577                 blockoffset = stripeoffset % plex->stripesize;
578
579                 sd = &SD[plex->sdnos[sdno]];                /* the subdisk in question */
580                 rqg = allocrqg(rq, 1);                      /* space for the request */
581                 if (rqg == NULL) {                          /* malloc failed */
582                     bp->b_error = ENOMEM;
583                     bp->b_flags |= B_ERROR;
584                     return REQUEST_ENOMEM;
585                 }
586                 rqg->plexno = plexno;
587
588                 rqe = &rqg->rqe[0];                         /* point to the element */
589                 rqe->rqg = rqg;
590                 rqe->sdoffset = stripebase / plex->subdisks + blockoffset; /* start offset in this subdisk */
591                 rqe->useroffset = *diskaddr - diskstart;    /* The offset of the start in the user buffer */
592                 rqe->dataoffset = 0;
593                 rqe->datalen = min(diskend - *diskaddr,     /* the amount remaining to transfer */
594                     plex->stripesize - blockoffset);        /* and the amount left in this stripe */
595                 rqe->groupoffset = 0;                       /* no groups for striped plexes */
596                 rqe->grouplen = 0;
597                 rqe->buflen = rqe->datalen;                 /* buffer length is data buffer length */
598                 rqe->flags = 0;
599                 rqe->sdno = sd->sdno;                       /* put in the subdisk number */
600                 rqe->driveno = sd->driveno;
601
602                 if (sd->state != sd_up) {                   /* *now* we find the sd is down */
603                     s = checksdstate(sd, rq, *diskaddr, diskend); /* do we need to change state? */
604                     if (s == REQUEST_DOWN) {                /* down? */
605                         rqe->flags = XFR_BAD_SUBDISK;       /* yup */
606                         if (rq->bio->bio_buf->b_cmd == BUF_CMD_READ)        /* read request, */
607                             return REQUEST_DEGRADED;        /* give up here */
608                         /*
609                          * If we're writing, don't give up
610                          * because of a bad subdisk.  Go through
611                          * to the bitter end, but note which
612                          * ones we can't access.
613                          */
614                         status = REQUEST_DEGRADED;          /* can't do it all */
615                     }
616                 }
617                 /*
618                  * It would seem that having an offset
619                  * beyond the end of the subdisk is an
620                  * error, but in fact it can happen if the
621                  * volume has another plex of different
622                  * size.  There's a valid question as to why
623                  * you would want to do this, but currently
624                  * it's allowed.
625                  */
626                 if (rqe->sdoffset + rqe->datalen > sd->sectors) { /* ends beyond the end of the subdisk? */
627                     rqe->datalen = sd->sectors - rqe->sdoffset; /* truncate */
628 #if VINUMDEBUG
629                     if (debug & DEBUG_EOFINFO) {            /* tell on the request */
630                         log(LOG_DEBUG,
631                             "vinum: EOF on plex %s, sd %s offset %llx (user offset %x)\n",
632                             plex->name,
633                             sd->name,
634                             (u_int) sd->sectors,
635                             bp->b_bio1.bio_offset);
636                         log(LOG_DEBUG,
637                             "vinum: stripebase %x, stripeoffset %x, blockoffset %x\n",
638                             stripebase,
639                             stripeoffset,
640                             blockoffset);
641                     }
642 #endif
643                 }
644                 if (build_rq_buffer(rqe, plex)) {           /* build the buffer */
645                     deallocrqg(rqg);
646                     bp->b_error = ENOMEM;
647                     bp->b_flags |= B_ERROR;
648                     return REQUEST_ENOMEM;                  /* can't do it */
649                 }
650                 *diskaddr += rqe->datalen;                  /* look at the remainder */
651                 if ((*diskaddr < diskend)                   /* didn't finish the request on this stripe */
652                 &&(*diskaddr < plex->length)) {             /* and there's more to come */
653                     plex->multiblock++;                     /* count another one */
654                     if (sdno == plex->subdisks - 1)         /* last subdisk, */
655                         plex->multistripe++;                /* another stripe as well */
656                 }
657             }
658         }
659         break;
660
661         /*
662          * RAID-4 and RAID-5 are complicated enough to have their own
663          * function.
664          */
665     case plex_raid4:
666     case plex_raid5:
667         status = bre5(rq, plexno, diskaddr, diskend);
668         break;
669
670     default:
671         log(LOG_ERR, "vinum: invalid plex type %d in bre\n", plex->organization);
672         status = REQUEST_DOWN;                              /* can't access it */
673     }
674
675     return status;
676 }
677
678 /*
679  * Build up a request structure for reading volumes.
680  * This function is not needed for plex reads, since there's
681  * no recovery if a plex read can't be satisified.
682  */
683 enum requeststatus
684 build_read_request(struct request *rq,                      /* request */
685     int plexindex)
686 {                                                           /* index in the volume's plex table */
687     struct bio *bio;
688     struct buf *bp;
689     daddr_t startaddr;                                      /* offset of previous part of transfer */
690     daddr_t diskaddr;                                       /* offset of current part of transfer */
691     daddr_t diskend;                                        /* and end offset of transfer */
692     int plexno;                                             /* plex index in vinum_conf */
693     struct rqgroup *rqg;                                    /* point to the request we're working on */
694     struct volume *vol;                                     /* volume in question */
695     int recovered = 0;                                      /* set if we recover a read */
696     enum requeststatus status = REQUEST_OK;
697     int plexmask;                                           /* bit mask of plexes, for recovery */
698
699     bio = rq->bio;                                          /* buffer pointer */
700     bp = bio->bio_buf;
701     diskaddr = bio->bio_offset >> DEV_BSHIFT;               /* start offset of transfer */
702     diskend = diskaddr + (bp->b_bcount / DEV_BSIZE);        /* and end offset of transfer */
703     rqg = &rq->rqg[plexindex];                              /* plex request */
704     vol = &VOL[rq->volplex.volno];                          /* point to volume */
705
706     while (diskaddr < diskend) {                            /* build up request components */
707         startaddr = diskaddr;
708         status = bre(rq, vol->plex[plexindex], &diskaddr, diskend); /* build up a request */
709         switch (status) {
710         case REQUEST_OK:
711             continue;
712
713         case REQUEST_RECOVERED:
714             /*
715              * XXX FIXME if we have more than one plex, and we can
716              * satisfy the request from another, don't use the
717              * recovered request, since it's more expensive.
718              */
719             recovered = 1;
720             break;
721
722         case REQUEST_ENOMEM:
723             return status;
724             /*
725              * If we get here, our request is not complete.  Try
726              * to fill in the missing parts from another plex.
727              * This can happen multiple times in this function,
728              * and we reinitialize the plex mask each time, since
729              * we could have a hole in our plexes.
730              */
731         case REQUEST_EOF:
732         case REQUEST_DOWN:                                  /* can't access the plex */
733         case REQUEST_DEGRADED:                              /* can't access the plex */
734             plexmask = ((1 << vol->plexes) - 1)             /* all plexes in the volume */
735             &~(1 << plexindex);                             /* except for the one we were looking at */
736             for (plexno = 0; plexno < vol->plexes; plexno++) {
737                 if (plexmask == 0)                          /* no plexes left to try */
738                     return REQUEST_DOWN;                    /* failed */
739                 diskaddr = startaddr;                       /* start at the beginning again */
740                 if (plexmask & (1 << plexno)) {             /* we haven't tried this plex yet */
741                     bre(rq, vol->plex[plexno], &diskaddr, diskend); /* try a request */
742                     if (diskaddr > startaddr) {             /* we satisfied another part */
743                         recovered = 1;                      /* we recovered from the problem */
744                         status = REQUEST_OK;                /* don't complain about it */
745                         break;
746                     }
747                 }
748             }
749             if (diskaddr == startaddr)                      /* didn't get any further, */
750                 return status;
751         }
752         if (recovered)
753             vol->recovered_reads += recovered;              /* adjust our recovery count */
754     }
755     return status;
756 }
757
758 /*
759  * Build up a request structure for writes.
760  * Return 0 if all subdisks involved in the request are up, 1 if some
761  * subdisks are not up, and -1 if the request is at least partially
762  * outside the bounds of the subdisks.
763  */
764 enum requeststatus
765 build_write_request(struct request *rq)
766 {                                                           /* request */
767     struct bio *bio;
768     struct buf *bp;
769     daddr_t diskstart;                                      /* offset of current part of transfer */
770     daddr_t diskend;                                        /* and end offset of transfer */
771     int plexno;                                             /* plex index in vinum_conf */
772     struct volume *vol;                                     /* volume in question */
773     enum requeststatus status;
774
775     bio = rq->bio;                                          /* buffer pointer */
776     bp = bio->bio_buf;
777     vol = &VOL[rq->volplex.volno];                          /* point to volume */
778     diskend = (daddr_t)(bio->bio_offset >> DEV_BSHIFT) + (bp->b_bcount / DEV_BSIZE);        /* end offset of transfer */
779     status = REQUEST_DOWN;                                  /* assume the worst */
780     for (plexno = 0; plexno < vol->plexes; plexno++) {
781         diskstart = (daddr_t)(bio->bio_offset >> DEV_BSHIFT);                       /* start offset of transfer */
782         /*
783          * Build requests for the plex.
784          * We take the best possible result here (min,
785          * not max): we're happy if we can write at all
786          */
787         status = min(status, bre(rq,
788                 vol->plex[plexno],
789                 &diskstart,
790                 diskend));
791     }
792     return status;
793 }
794
795 /* Fill in the struct buf part of a request element. */
796 enum requeststatus
797 build_rq_buffer(struct rqelement *rqe, struct plex *plex)
798 {
799     struct sd *sd;                                          /* point to subdisk */
800     struct volume *vol;
801     struct buf *bp;
802     struct buf *ubp;                                        /* user (high level) buffer header */
803     struct bio *ubio;
804
805     vol = &VOL[rqe->rqg->rq->volplex.volno];
806     sd = &SD[rqe->sdno];                                    /* point to subdisk */
807     bp = &rqe->b;
808     ubio = rqe->rqg->rq->bio;                               /* pointer to user buffer header */
809     ubp = ubio->bio_buf;
810
811     /* Initialize the buf struct */
812     /* copy these flags from user bp */
813     bp->b_flags = ubp->b_flags & (B_ORDERED | B_NOCACHE | B_ASYNC);
814     bp->b_cmd = ubp->b_cmd;
815 #ifdef VINUMDEBUG
816     if (rqe->flags & XFR_BUFLOCKED)                         /* paranoia */
817         panic("build_rq_buffer: rqe already locked");       /* XXX remove this when we're sure */
818 #endif
819     BUF_LOCKINIT(bp);                                       /* get a lock for the buffer */
820     BUF_LOCK(bp, LK_EXCLUSIVE);                             /* and lock it */
821     BUF_KERNPROC(bp);
822     initbufbio(bp);
823     rqe->flags |= XFR_BUFLOCKED;
824     bp->b_bio1.bio_done = complete_rqe;
825     /*
826      * You'd think that we wouldn't need to even
827      * build the request buffer for a dead subdisk,
828      * but in some cases we need information like
829      * the user buffer address.  Err on the side of
830      * generosity and supply what we can.  That
831      * obviously doesn't include drive information
832      * when the drive is dead.
833      */
834     if ((rqe->flags & XFR_BAD_SUBDISK) == 0)                /* subdisk is accessible, */
835         bp->b_bio1.bio_driver_info = DRIVE[rqe->driveno].dev; /* drive device */
836     bp->b_bio1.bio_offset = (off_t)(rqe->sdoffset + sd->driveoffset) << DEV_BSHIFT;     /* start address */
837     bp->b_bcount = rqe->buflen << DEV_BSHIFT;               /* number of bytes to transfer */
838     bp->b_resid = bp->b_bcount;                             /* and it's still all waiting */
839
840     if (rqe->flags & XFR_MALLOCED) {                        /* this operation requires a malloced buffer */
841         bp->b_data = Malloc(bp->b_bcount);                  /* get a buffer to put it in */
842         if (bp->b_data == NULL) {                           /* failed */
843             abortrequest(rqe->rqg->rq, ENOMEM);
844             return REQUEST_ENOMEM;                          /* no memory */
845         }
846     } else
847         /*
848          * Point directly to user buffer data.  This means
849          * that we don't need to do anything when we have
850          * finished the transfer
851          */
852         bp->b_data = ubp->b_data + rqe->useroffset * DEV_BSIZE;
853     /*
854      * On a recovery read, we perform an XOR of
855      * all blocks to the user buffer.  To make
856      * this work, we first clean out the buffer
857      */
858     if ((rqe->flags & (XFR_RECOVERY_READ | XFR_BAD_SUBDISK))
859         == (XFR_RECOVERY_READ | XFR_BAD_SUBDISK)) {         /* bad subdisk of a recovery read */
860         int length = rqe->grouplen << DEV_BSHIFT;           /* and count involved */
861         char *data = (char *) &rqe->b.b_data[rqe->groupoffset << DEV_BSHIFT]; /* destination */
862
863         bzero(data, length);                                /* clean it out */
864     }
865     return 0;
866 }
867
868 /*
869  * Abort a request: free resources and complete the
870  * user request with the specified error
871  */
872 int
873 abortrequest(struct request *rq, int error)
874 {
875     struct buf *bp = rq->bio->bio_buf;                      /* user buffer */
876
877     bp->b_error = error;
878     freerq(rq);                                             /* free everything we're doing */
879     bp->b_flags |= B_ERROR;
880     return error;                                           /* and give up */
881 }
882
883 /*
884  * Check that our transfer will cover the
885  * complete address space of the user request.
886  *
887  * Return 1 if it can, otherwise 0
888  */
889 int
890 check_range_covered(struct request *rq)
891 {
892     return 1;
893 }
894
895 /* Perform I/O on a subdisk */
896 void
897 sdio(struct bio *bio)
898 {
899     dev_t dev;
900     dev_t sddev;
901     struct sd *sd;
902     struct sdbuf *sbp;
903     daddr_t endoffset;
904     struct drive *drive;
905     struct buf *bp = bio->bio_buf;
906
907     dev = bio->bio_driver_info;
908
909 #if VINUMDEBUG
910     if (debug & DEBUG_LASTREQS)
911         logrq(loginfo_sdio, (union rqinfou) bio, bio);
912 #endif
913     sd = &SD[Sdno(dev)];                                    /* point to the subdisk */
914     drive = &DRIVE[sd->driveno];
915
916     if (drive->state != drive_up) {
917         if (sd->state >= sd_crashed) {
918             if (bp->b_cmd != BUF_CMD_READ)                  /* writing, */
919                 set_sd_state(sd->sdno, sd_stale, setstate_force);
920             else
921                 set_sd_state(sd->sdno, sd_crashed, setstate_force);
922         }
923         bp->b_error = EIO;
924         bp->b_flags |= B_ERROR;
925         biodone(bio);
926         return;
927     }
928     /*
929      * We allow access to any kind of subdisk as long as we can expect
930      * to get the I/O performed.
931      */
932     if (sd->state < sd_empty) {                             /* nothing to talk to, */
933         bp->b_error = EIO;
934         bp->b_flags |= B_ERROR;
935         biodone(bio);
936         return;
937     }
938     /* Get a buffer */
939     sbp = (struct sdbuf *) Malloc(sizeof(struct sdbuf));
940     if (sbp == NULL) {
941         bp->b_error = ENOMEM;
942         bp->b_flags |= B_ERROR;
943         biodone(bio);
944         return;
945     }
946     sddev = DRIVE[sd->driveno].dev;                 /* device */
947     bzero(sbp, sizeof(struct sdbuf));                       /* start with nothing */
948     sbp->b.b_cmd = bp->b_cmd;
949     sbp->b.b_bcount = bp->b_bcount;                         /* number of bytes to transfer */
950     sbp->b.b_resid = bp->b_resid;                           /* and amount waiting */
951     sbp->b.b_data = bp->b_data;                             /* data buffer */
952     BUF_LOCKINIT(&sbp->b);                                  /* get a lock for the buffer */
953     BUF_LOCK(&sbp->b, LK_EXCLUSIVE);                        /* and lock it */
954     BUF_KERNPROC(&sbp->b);
955     initbufbio(&sbp->b);
956     sbp->b.b_bio1.bio_offset = bio->bio_offset + ((off_t)sd->driveoffset << DEV_BSHIFT);
957     sbp->b.b_bio1.bio_done = sdio_done;                     /* come here on completion */
958     sbp->bio = bio;                                         /* note the address of the original header */
959     sbp->sdno = sd->sdno;                                   /* note for statistics */
960     sbp->driveno = sd->driveno;
961     endoffset = (daddr_t)(bio->bio_offset >> DEV_BSHIFT) + sbp->b.b_bcount / DEV_BSIZE;  /* final sector offset */
962     if (endoffset > sd->sectors) {                          /* beyond the end */
963         sbp->b.b_bcount -= (endoffset - sd->sectors) * DEV_BSIZE; /* trim */
964         if (sbp->b.b_bcount <= 0) {                         /* nothing to transfer */
965             bp->b_resid = bp->b_bcount;                     /* nothing transferred */
966             biodone(bio);
967             BUF_UNLOCK(&sbp->b);
968             BUF_LOCKFREE(&sbp->b);
969             Free(sbp);
970             return;
971         }
972     }
973 #if VINUMDEBUG
974     if (debug & DEBUG_ADDRESSES)
975         log(LOG_DEBUG,
976             "  %s dev %d.%d, sd %d, offset 0x%llx, devoffset 0x%llx, length %d\n",
977             (sbp->b.b_cmd == BUF_CMD_READ) ? "Read" : "Write",
978             major(sddev),
979             minor(sddev),
980             sbp->sdno,
981             sbp->b.b_bio1.bio_offset - ((off_t)SD[sbp->sdno].driveoffset << DEV_BSHIFT),
982             sbp->b.b_bio1.bio_offset,
983             sbp->b.b_bcount);
984 #endif
985     crit_enter();
986 #if VINUMDEBUG
987     if (debug & DEBUG_LASTREQS)
988         logrq(loginfo_sdiol, (union rqinfou) &sbp->b.b_bio1, &sbp->b.b_bio1);
989 #endif
990     dev_dstrategy(sddev, &sbp->b.b_bio1);
991     crit_exit();
992 }
993
994 /*
995  * Simplified version of bounds_check_with_label
996  * Determine the size of the transfer, and make sure it is
997  * within the boundaries of the partition. Adjust transfer
998  * if needed, and signal errors or early completion.
999  *
1000  * Volumes are simpler than disk slices: they only contain
1001  * one component (though we call them a, b and c to make
1002  * system utilities happy), and they always take up the
1003  * complete space of the "partition".
1004  *
1005  * I'm still not happy with this: why should the label be
1006  * protected?  If it weren't so damned difficult to write
1007  * one in the first pleace (because it's protected), it wouldn't
1008  * be a problem.
1009  */
1010 struct bio *
1011 vinum_bounds_check(struct bio *bio, struct volume *vol)
1012 {
1013     struct buf *bp = bio->bio_buf;
1014     struct bio *nbio;
1015     int maxsize = vol->size;                                /* size of the partition (sectors) */
1016     int size = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT; /* size of this request (sectors) */
1017     daddr_t blkno = (daddr_t)(bio->bio_offset >> DEV_BSHIFT);
1018
1019     /* Would this transfer overwrite the disk label? */
1020     if (blkno <= LABELSECTOR                        /* starts before or at the label */
1021 #if LABELSECTOR != 0
1022         && blkno + size > LABELSECTOR               /* and finishes after */
1023 #endif
1024         && (!(vol->flags & VF_RAW))                         /* and it's not raw */
1025         && (bp->b_cmd != BUF_CMD_READ)                      /* and it's a write */
1026         &&(!vol->flags & (VF_WLABEL | VF_LABELLING))) {     /* and we're not allowed to write the label */
1027         bp->b_error = EROFS;                                /* read-only */
1028         bp->b_flags |= B_ERROR;
1029         return (NULL);
1030     }
1031     if (size == 0)                                          /* no transfer specified, */
1032         return 0;                                           /* treat as EOF */
1033     /* beyond partition? */
1034     if (bio->bio_offset < 0                                 /* negative start */
1035         || blkno + size > maxsize) {                /* or goes beyond the end of the partition */
1036         /* if exactly at end of disk, return an EOF */
1037         if (blkno == maxsize) {
1038             bp->b_resid = bp->b_bcount;
1039             return (NULL);
1040         }
1041         /* or truncate if part of it fits */
1042         size = maxsize - blkno;
1043         if (size <= 0) {                                    /* nothing to transfer */
1044             bp->b_error = EINVAL;
1045             bp->b_flags |= B_ERROR;
1046             return (NULL);
1047         }
1048         bp->b_bcount = size << DEV_BSHIFT;
1049     }
1050     nbio = push_bio(bio);
1051     nbio->bio_offset = bio->bio_offset;
1052     return (nbio);
1053 }
1054
1055 /*
1056  * Allocate a request group and hook
1057  * it in in the list for rq
1058  */
1059 struct rqgroup *
1060 allocrqg(struct request *rq, int elements)
1061 {
1062     struct rqgroup *rqg;                                    /* the one we're going to allocate */
1063     int size = sizeof(struct rqgroup) + elements * sizeof(struct rqelement);
1064
1065     rqg = (struct rqgroup *) Malloc(size);
1066     if (rqg != NULL) {                                      /* malloc OK, */
1067         if (rq->rqg)                                        /* we already have requests */
1068             rq->lrqg->next = rqg;                           /* hang it off the end */
1069         else                                                /* first request */
1070             rq->rqg = rqg;                                  /* at the start */
1071         rq->lrqg = rqg;                                     /* this one is the last in the list */
1072
1073         bzero(rqg, size);                                   /* no old junk */
1074         rqg->rq = rq;                                       /* point back to the parent request */
1075         rqg->count = elements;                              /* number of requests in the group */
1076         rqg->lockbase = -1;                                 /* no lock required yet */
1077     }
1078     return rqg;
1079 }
1080
1081 /*
1082  * Deallocate a request group out of a chain.  We do
1083  * this by linear search: the chain is short, this
1084  * almost never happens, and currently it can only
1085  * happen to the first member of the chain.
1086  */
1087 void
1088 deallocrqg(struct rqgroup *rqg)
1089 {
1090     struct rqgroup *rqgc = rqg->rq->rqg;                    /* point to the request chain */
1091
1092     if (rqg->lock)                                          /* got a lock? */
1093         unlockrange(rqg->plexno, rqg->lock);                /* yes, free it */
1094     if (rqgc == rqg)                                        /* we're first in line */
1095         rqg->rq->rqg = rqg->next;                           /* unhook ourselves */
1096     else {
1097         while ((rqgc->next != NULL)                         /* find the group */
1098         &&(rqgc->next != rqg))
1099             rqgc = rqgc->next;
1100         if (rqgc->next == NULL)
1101             log(LOG_ERR,
1102                 "vinum deallocrqg: rqg %p not found in request %p\n",
1103                 rqg->rq,
1104                 rqg);
1105         else
1106             rqgc->next = rqg->next;                         /* make the chain jump over us */
1107     }
1108     Free(rqg);
1109 }
1110
1111 /* Local Variables: */
1112 /* fill-column: 50 */
1113 /* End: */