Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / usr.sbin / mptutil / mpt_config.c
1 /*-
2  * Copyright (c) 2008 Yahoo!, Inc.
3  * All rights reserved.
4  * Written by: John Baldwin <jhb@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the author nor the names of any co-contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $FreeBSD: src/usr.sbin/mptutil/mpt_config.c,v 1.3 2010/11/22 14:36:04 jhb Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/errno.h>
35 #include <err.h>
36 #include <fcntl.h>
37 #include <libutil.h>
38 #include <paths.h>
39 #ifdef DEBUG
40 #include <stdint.h>
41 #endif
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include "mptutil.h"
47
48 #ifdef DEBUG
49 static void     dump_config(CONFIG_PAGE_RAID_VOL_0 *vol);
50 #endif
51
52 static long
53 dehumanize(const char *value)
54 {
55         char    *vtp;
56         long    iv;
57  
58         if (value == NULL)
59                 return (0);
60         iv = strtoq(value, &vtp, 0);
61         if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
62                 return (0);
63         }
64         switch (vtp[0]) {
65         case 't': case 'T':
66                 iv *= 1024;
67         case 'g': case 'G':
68                 iv *= 1024;
69         case 'm': case 'M':
70                 iv *= 1024;
71         case 'k': case 'K':
72                 iv *= 1024;
73         case '\0':
74                 break;
75         default:
76                 return (0);
77         }
78         return (iv);
79 }
80
81 /*
82  * Lock the volume by opening its /dev device read/write.  This will
83  * only work if nothing else has it opened (including mounts).  We
84  * leak the fd on purpose since this application is not long-running.
85  */
86 int
87 mpt_lock_volume(U8 VolumeBus, U8 VolumeID)
88 {
89         char path[MAXPATHLEN];
90         struct mpt_query_disk qd;
91         int error, vfd;
92
93         error = mpt_query_disk(VolumeBus, VolumeID, &qd);
94         if (error == ENOENT)
95                 /*
96                  * This means there isn't a CAM device associated with
97                  * the volume, and thus it is already implicitly
98                  * locked, so just return.
99                  */
100                 return (0);
101         if (error) {
102                 warnc(error, "Unable to lookup volume device name");
103                 return (error);
104         }
105         snprintf(path, sizeof(path), "%s%s", _PATH_DEV, qd.devname);
106         vfd = open(path, O_RDWR);
107         if (vfd < 0) {
108                 error = errno;
109                 warn("Unable to lock volume %s", qd.devname);
110                 return (error);
111         }
112         return (0);
113 }
114
115 static int
116 mpt_lock_physdisk(struct mpt_standalone_disk *disk)
117 {
118         char path[MAXPATHLEN];
119         int dfd, error;
120
121         snprintf(path, sizeof(path), "%s%s", _PATH_DEV, disk->devname);
122         dfd = open(path, O_RDWR);
123         if (dfd < 0) {
124                 error = errno;
125                 warn("Unable to lock disk %s", disk->devname);
126                 return (error);
127         }
128         return (0);
129 }
130
131 static int
132 mpt_lookup_standalone_disk(const char *name, struct mpt_standalone_disk *disks,
133     int ndisks, int *idx)
134 {
135         char *cp;
136         long bus, id;
137         int i;
138
139         /* Check for a raw <bus>:<id> string. */
140         bus = strtol(name, &cp, 0);
141         if (*cp == ':') {
142                 id = strtol(cp + 1, &cp, 0);
143                 if (*cp == '\0') {
144                         if (bus < 0 || bus > 0xff || id < 0 || id > 0xff) {
145                                 return (EINVAL);
146                         }
147                         for (i = 0; i < ndisks; i++) {
148                                 if (disks[i].bus == (U8)bus &&
149                                     disks[i].target == (U8)id) {
150                                         *idx = i;
151                                         return (0);
152                                 }
153                         }
154                         return (ENOENT);
155                 }
156         }
157
158         if (name[0] == 'd' && name[1] == 'a') {
159                 for (i = 0; i < ndisks; i++) {
160                         if (strcmp(name, disks[i].devname) == 0) {
161                                 *idx = i;
162                                 return (0);
163                         }
164                 }
165                 return (ENOENT);
166         }
167
168         return (EINVAL);
169 }
170
171 /*
172  * Mark a standalone disk as being a physical disk.
173  */
174 static int
175 mpt_create_physdisk(int fd, struct mpt_standalone_disk *disk, U8 *PhysDiskNum)
176 {
177         CONFIG_PAGE_HEADER header;
178         CONFIG_PAGE_RAID_PHYS_DISK_0 *config_page;
179         int error;
180         U32 ActionData;
181
182         error = mpt_read_config_page_header(fd, MPI_CONFIG_PAGETYPE_RAID_PHYSDISK,
183             0, 0, &header, NULL);
184         if (error)
185                 return (error);
186         if (header.PageVersion > MPI_RAIDPHYSDISKPAGE0_PAGEVERSION) {
187                 warnx("Unsupported RAID physdisk page 0 version %d",
188                     header.PageVersion);
189                 return (EOPNOTSUPP);
190         }               
191         config_page = calloc(1, sizeof(CONFIG_PAGE_RAID_PHYS_DISK_0));
192         config_page->Header.PageType = MPI_CONFIG_PAGETYPE_RAID_PHYSDISK;
193         config_page->Header.PageNumber = 0;
194         config_page->Header.PageLength = sizeof(CONFIG_PAGE_RAID_PHYS_DISK_0) /
195             4;
196         config_page->PhysDiskIOC = 0;   /* XXX */
197         config_page->PhysDiskBus = disk->bus;
198         config_page->PhysDiskID = disk->target;
199
200         /* XXX: Enclosure info for PhysDiskSettings? */
201         error = mpt_raid_action(fd, MPI_RAID_ACTION_CREATE_PHYSDISK, 0, 0, 0, 0,
202             config_page, sizeof(CONFIG_PAGE_RAID_PHYS_DISK_0), NULL,
203             &ActionData, sizeof(ActionData), NULL, NULL, 1);
204         if (error)
205                 return (error);
206         *PhysDiskNum = ActionData & 0xff;
207         return (0);
208 }
209
210 static int
211 mpt_delete_physdisk(int fd, U8 PhysDiskNum)
212 {
213
214         return (mpt_raid_action(fd, MPI_RAID_ACTION_DELETE_PHYSDISK, 0, 0,
215             PhysDiskNum, 0, NULL, 0, NULL, NULL, 0, NULL, NULL, 0));
216 }
217
218 /*
219  * MPT's firmware does not have a clear command.  Instead, we
220  * implement it by deleting each array and disk by hand.
221  */
222 static int
223 clear_config(int ac __unused, char **av __unused)
224 {
225         CONFIG_PAGE_IOC_2 *ioc2;
226         CONFIG_PAGE_IOC_2_RAID_VOL *vol;
227         CONFIG_PAGE_IOC_3 *ioc3;
228         IOC_3_PHYS_DISK *disk;
229         CONFIG_PAGE_IOC_5 *ioc5;
230         IOC_5_HOT_SPARE *spare;
231         int ch, error, fd, i;
232
233         fd = mpt_open(mpt_unit);
234         if (fd < 0) {
235                 error = errno;
236                 warn("mpt_open");
237                 return (error);
238         }
239
240         ioc2 = mpt_read_ioc_page(fd, 2, NULL);
241         if (ioc2 == NULL) {
242                 error = errno;
243                 warn("Failed to fetch volume list");
244                 return (error);
245         }
246
247         /* Lock all the volumes first. */
248         vol = ioc2->RaidVolume;
249         for (i = 0; i < ioc2->NumActiveVolumes; vol++, i++) {
250                 if (mpt_lock_volume(vol->VolumeBus, vol->VolumeID) < 0) {
251                         warnx("Volume %s is busy and cannot be deleted",
252                             mpt_volume_name(vol->VolumeBus, vol->VolumeID));
253                         return (EBUSY);
254                 }
255         }
256
257         printf(
258             "Are you sure you wish to clear the configuration on mpt%u? [y/N] ",
259             mpt_unit);
260         ch = getchar();
261         if (ch != 'y' && ch != 'Y') {
262                 printf("\nAborting\n");
263                 return (0);
264         }
265
266         /* Delete all the volumes. */
267         vol = ioc2->RaidVolume;
268         for (i = 0; i < ioc2->NumActiveVolumes; vol++, i++) {
269                 error = mpt_raid_action(fd, MPI_RAID_ACTION_DELETE_VOLUME,
270                     vol->VolumeBus, vol->VolumeID, 0,
271                     MPI_RAID_ACTION_ADATA_DEL_PHYS_DISKS |
272                     MPI_RAID_ACTION_ADATA_ZERO_LBA0, NULL, 0, NULL, NULL, 0,
273                     NULL, NULL, 0);
274                 if (error)
275                         warnc(error, "Failed to delete volume %s",
276                             mpt_volume_name(vol->VolumeBus, vol->VolumeID));
277         }
278         free(ioc2);
279
280         /* Delete all the spares. */
281         ioc5 = mpt_read_ioc_page(fd, 5, NULL);
282         if (ioc5 == NULL)
283                 warn("Failed to fetch spare list");
284         else {
285                 spare = ioc5->HotSpare;
286                 for (i = 0; i < ioc5->NumHotSpares; spare++, i++)
287                         if (mpt_delete_physdisk(fd, spare->PhysDiskNum) < 0)
288                                 warn("Failed to delete physical disk %d",
289                                     spare->PhysDiskNum);
290                 free(ioc5);
291         }
292
293         /* Delete any RAID physdisks that may be left. */
294         ioc3 = mpt_read_ioc_page(fd, 3, NULL);
295         if (ioc3 == NULL)
296                 warn("Failed to fetch drive list");
297         else {
298                 disk = ioc3->PhysDisk;
299                 for (i = 0; i < ioc3->NumPhysDisks; disk++, i++)
300                         if (mpt_delete_physdisk(fd, disk->PhysDiskNum) < 0)
301                                 warn("Failed to delete physical disk %d",
302                                     disk->PhysDiskNum);
303                 free(ioc3);
304         }
305
306         printf("mpt%d: Configuration cleared\n", mpt_unit);
307         mpt_rescan_bus(-1, -1);
308         close(fd);
309
310         return (0);
311 }
312 MPT_COMMAND(top, clear, clear_config);
313
314 #define RT_RAID0        0
315 #define RT_RAID1        1
316 #define RT_RAID1E       2
317
318 static struct raid_type_entry {
319         const char *name;
320         int     raid_type;
321 } raid_type_table[] = {
322         { "raid0",      RT_RAID0 },
323         { "raid-0",     RT_RAID0 },
324         { "raid1",      RT_RAID1 },
325         { "raid-1",     RT_RAID1 },
326         { "mirror",     RT_RAID1 },
327         { "raid1e",     RT_RAID1E },
328         { "raid-1e",    RT_RAID1E },
329         { NULL,         0 },
330 };
331
332 struct config_id_state {
333         struct mpt_standalone_disk *sdisks;
334         struct mpt_drive_list *list;
335         CONFIG_PAGE_IOC_2 *ioc2;
336         U8      target_id;
337         int     nsdisks;
338 };
339
340 struct drive_info {
341         CONFIG_PAGE_RAID_PHYS_DISK_0 *info;
342         struct mpt_standalone_disk *sdisk;
343 };
344
345 struct volume_info {
346         int     drive_count;
347         struct drive_info *drives;
348 };
349
350 /* Parse a comma-separated list of drives for a volume. */
351 static int
352 parse_volume(int fd, int raid_type, struct config_id_state *state,
353     char *volume_str, struct volume_info *info)
354 {
355         struct drive_info *dinfo;
356         U8 PhysDiskNum;
357         char *cp;
358         int count, error, i;
359
360         cp = volume_str;
361         for (count = 0; cp != NULL; count++) {
362                 cp = strchr(cp, ',');
363                 if (cp != NULL) {
364                         cp++;
365                         if (*cp == ',') {
366                                 warnx("Invalid drive list '%s'", volume_str);
367                                 return (EINVAL);
368                         }
369                 }
370         }
371
372         /* Validate the number of drives for this volume. */
373         switch (raid_type) {
374         case RT_RAID0:
375                 if (count < 2) {
376                         warnx("RAID0 requires at least 2 drives in each "
377                             "array");
378                         return (EINVAL);
379                 }
380                 break;
381         case RT_RAID1:
382                 if (count != 2) {
383                         warnx("RAID1 requires exactly 2 drives in each "
384                             "array");
385                         return (EINVAL);
386                 }
387                 break;
388         case RT_RAID1E:
389                 if (count < 3) {
390                         warnx("RAID1E requires at least 3 drives in each "
391                             "array");
392                         return (EINVAL);
393                 }
394                 break;
395         }
396
397         /* Validate each drive. */
398         info->drives = calloc(count, sizeof(struct drive_info));
399         info->drive_count = count;
400         for (dinfo = info->drives; (cp = strsep(&volume_str, ",")) != NULL;
401              dinfo++) {
402                 /* If this drive is already a RAID phys just fetch the info. */
403                 error = mpt_lookup_drive(state->list, cp, &PhysDiskNum);
404                 if (error == 0) {
405                         dinfo->info = mpt_pd_info(fd, PhysDiskNum, NULL);
406                         if (dinfo->info == NULL)
407                                 return (errno);
408                         continue;
409                 }
410
411                 /* See if it is a standalone disk. */
412                 if (mpt_lookup_standalone_disk(cp, state->sdisks,
413                     state->nsdisks, &i) < 0) {
414                         error = errno;
415                         warn("Unable to lookup drive %s", cp);
416                         return (error);
417                 }
418                 dinfo->sdisk = &state->sdisks[i];
419
420                 /* Lock the disk, we will create phys disk pages later. */
421                 if (mpt_lock_physdisk(dinfo->sdisk) < 0)
422                         return (errno);
423         }
424
425         return (0);
426 }
427
428 /*
429  * Add RAID physdisk pages for any standalone disks that a volume is
430  * going to use.
431  */
432 static int
433 add_drives(int fd, struct volume_info *info, int verbose)
434 {
435         struct drive_info *dinfo;
436         U8 PhysDiskNum;
437         int error, i;
438
439         for (i = 0, dinfo = info->drives; i < info->drive_count;
440              i++, dinfo++) {
441                 if (dinfo->info == NULL) {
442                         if (mpt_create_physdisk(fd, dinfo->sdisk,
443                             &PhysDiskNum) < 0) {
444                                 error = errno;
445                                 warn(
446                             "Failed to create physical disk page for %s",
447                                     dinfo->sdisk->devname);
448                                 return (error);
449                         }
450                         if (verbose)
451                                 printf("Added drive %s with PhysDiskNum %u\n",
452                                     dinfo->sdisk->devname, PhysDiskNum);
453
454                         dinfo->info = mpt_pd_info(fd, PhysDiskNum, NULL);
455                         if (dinfo->info == NULL)
456                                 return (errno);
457                 }
458         }
459         return (0);
460 }
461
462 /*
463  * Find the next free target ID assuming that 'target_id' is the last
464  * one used.  'target_id' should be 0xff for the initial test.
465  */
466 static U8
467 find_next_volume(struct config_id_state *state)
468 {
469         CONFIG_PAGE_IOC_2_RAID_VOL *vol;
470         int i;
471
472 restart:
473         /* Assume the current one is used. */
474         state->target_id++;
475
476         /* Search drives first. */
477         for (i = 0; i < state->nsdisks; i++)
478                 if (state->sdisks[i].target == state->target_id)
479                         goto restart;
480         for (i = 0; i < state->list->ndrives; i++)
481                 if (state->list->drives[i]->PhysDiskID == state->target_id)
482                         goto restart;
483
484         /* Seach volumes second. */
485         vol = state->ioc2->RaidVolume;
486         for (i = 0; i < state->ioc2->NumActiveVolumes; vol++, i++)
487                 if (vol->VolumeID == state->target_id)
488                         goto restart;
489
490         return (state->target_id);
491 }
492
493 /* Create a volume and populate it with drives. */
494 static CONFIG_PAGE_RAID_VOL_0 *
495 build_volume(int fd, struct volume_info *info, int raid_type, long stripe_size,
496     struct config_id_state *state, int verbose)
497 {
498         CONFIG_PAGE_HEADER header;
499         CONFIG_PAGE_RAID_VOL_0 *vol;
500         RAID_VOL0_PHYS_DISK *rdisk;
501         struct drive_info *dinfo;
502         U32 MinLBA;
503         uint64_t MaxLBA;
504         size_t page_size;
505         int error, i;
506
507         error = mpt_read_config_page_header(fd, MPI_CONFIG_PAGETYPE_RAID_VOLUME,
508             0, 0, &header, NULL);
509         if (error) {
510                 errno = error;
511                 return (NULL);
512         }
513         if (header.PageVersion > MPI_RAIDVOLPAGE0_PAGEVERSION) {
514                 warnx("Unsupported RAID volume page 0 version %d",
515                     header.PageVersion);
516                 errno = EOPNOTSUPP;
517                 return (NULL);
518         }
519         page_size = sizeof(CONFIG_PAGE_RAID_VOL_0) +
520             sizeof(RAID_VOL0_PHYS_DISK) * (info->drive_count - 1);
521         vol = calloc(1, page_size);
522         if (vol == NULL)
523                 return (NULL);
524
525         /* Header */
526         vol->Header.PageType = MPI_CONFIG_PAGETYPE_RAID_VOLUME;
527         vol->Header.PageNumber = 0;
528         vol->Header.PageLength = page_size / 4;
529
530         /* Properties */
531         vol->VolumeID = find_next_volume(state);
532         vol->VolumeBus = 0;
533         vol->VolumeIOC = 0;     /* XXX */
534         vol->VolumeStatus.Flags = MPI_RAIDVOL0_STATUS_FLAG_ENABLED;
535         vol->VolumeStatus.State = MPI_RAIDVOL0_STATUS_STATE_OPTIMAL;
536         vol->VolumeSettings.Settings = MPI_RAIDVOL0_SETTING_USE_DEFAULTS;
537         vol->VolumeSettings.HotSparePool = MPI_RAID_HOT_SPARE_POOL_0;
538         vol->NumPhysDisks = info->drive_count;
539
540         /* Find the smallest drive. */
541         MinLBA = info->drives[0].info->MaxLBA;
542         for (i = 1; i < info->drive_count; i++)
543                 if (info->drives[i].info->MaxLBA < MinLBA)
544                         MinLBA = info->drives[i].info->MaxLBA;
545
546         /*
547          * Now chop off 512MB at the end to leave room for the
548          * metadata.  The controller might only use 64MB, but we just
549          * chop off the max to be simple.
550          */
551         MinLBA -= (512 * 1024 * 1024) / 512;
552
553         switch (raid_type) {
554         case RT_RAID0:
555                 vol->VolumeType = MPI_RAID_VOL_TYPE_IS;
556                 vol->StripeSize = stripe_size / 512;
557                 MaxLBA = MinLBA * info->drive_count;
558                 break;
559         case RT_RAID1:
560                 vol->VolumeType = MPI_RAID_VOL_TYPE_IM;
561                 MaxLBA = MinLBA * (info->drive_count / 2);
562                 break;
563         case RT_RAID1E:
564                 vol->VolumeType = MPI_RAID_VOL_TYPE_IME;
565                 vol->StripeSize = stripe_size / 512;
566                 MaxLBA = MinLBA * info->drive_count / 2;
567                 break;
568         default:
569                 /* Pacify gcc. */
570                 abort();                
571         }
572
573         /*
574          * If the controller doesn't support 64-bit addressing and the
575          * new volume is larger than 2^32 blocks, warn the user and
576          * truncate the volume.
577          */
578         if (MaxLBA >> 32 != 0 &&
579             !(state->ioc2->CapabilitiesFlags &
580             MPI_IOCPAGE2_CAP_FLAGS_RAID_64_BIT_ADDRESSING)) {
581                 warnx(
582             "Controller does not support volumes > 2TB, truncating volume.");
583                 MaxLBA = 0xffffffff;
584         }
585         vol->MaxLBA = MaxLBA;
586         vol->MaxLBAHigh = MaxLBA >> 32;
587
588         /* Populate drives. */
589         for (i = 0, dinfo = info->drives, rdisk = vol->PhysDisk;
590              i < info->drive_count; i++, dinfo++, rdisk++) {
591                 if (verbose)
592                         printf("Adding drive %u (%u:%u) to volume %u:%u\n",
593                             dinfo->info->PhysDiskNum, dinfo->info->PhysDiskBus,
594                             dinfo->info->PhysDiskID, vol->VolumeBus,
595                             vol->VolumeID);
596                 if (raid_type == RT_RAID1) {
597                         if (i == 0)
598                                 rdisk->PhysDiskMap =
599                                     MPI_RAIDVOL0_PHYSDISK_PRIMARY;
600                         else
601                                 rdisk->PhysDiskMap =
602                                     MPI_RAIDVOL0_PHYSDISK_SECONDARY;
603                 } else
604                         rdisk->PhysDiskMap = i;
605                 rdisk->PhysDiskNum = dinfo->info->PhysDiskNum;
606         }
607
608         return (vol);
609 }
610
611 static int
612 create_volume(int ac, char **av)
613 {
614         CONFIG_PAGE_RAID_VOL_0 *vol;
615         struct config_id_state state;
616         struct volume_info *info;
617         long stripe_size;
618         int ch, error, fd, i, quick, raid_type, verbose;
619 #ifdef DEBUG
620         int dump;
621 #endif
622
623         if (ac < 2) {
624                 warnx("create: volume type required");
625                 return (EINVAL);
626         }
627         
628         fd = mpt_open(mpt_unit);
629         if (fd < 0) {
630                 error = errno;
631                 warn("mpt_open");
632                 return (error);
633         }
634
635         /* Lookup the RAID type first. */
636         raid_type = -1;
637         for (i = 0; raid_type_table[i].name != NULL; i++)
638                 if (strcasecmp(raid_type_table[i].name, av[1]) == 0) {
639                         raid_type = raid_type_table[i].raid_type;
640                         break;
641                 }
642
643         if (raid_type == -1) {
644                 warnx("Unknown or unsupported volume type %s", av[1]);
645                 return (EINVAL);
646         }
647
648         /* Parse any options. */
649         optind = 2;
650 #ifdef DEBUG
651         dump = 0;
652 #endif
653         quick = 0;
654         verbose = 0;
655         stripe_size = 64 * 1024;
656
657         while ((ch = getopt(ac, av, "dqs:v")) != -1) {
658                 switch (ch) {
659 #ifdef DEBUG
660                 case 'd':
661                         dump = 1;
662                         break;
663 #endif
664                 case 'q':
665                         quick = 1;
666                         break;
667                 case 's':
668                         stripe_size = dehumanize(optarg);
669                         if ((stripe_size < 512) || (!powerof2(stripe_size))) {
670                                 warnx("Invalid stripe size %s", optarg);
671                                 return (EINVAL);
672                         }
673                         break;
674                 case 'v':
675                         verbose = 1;
676                         break;
677                 case '?':
678                 default:
679                         return (EINVAL);
680                 }
681         }
682         ac -= optind;
683         av += optind;
684
685         /* Fetch existing config data. */
686         state.ioc2 = mpt_read_ioc_page(fd, 2, NULL);
687         if (state.ioc2 == NULL) {
688                 error = errno;
689                 warn("Failed to read volume list");
690                 return (error);
691         }
692         state.list = mpt_pd_list(fd);
693         if (state.list == NULL)
694                 return (errno);
695         error = mpt_fetch_disks(fd, &state.nsdisks, &state.sdisks);
696         if (error) {
697                 warn("Failed to fetch standalone disk list");
698                 return (error);
699         }       
700         state.target_id = 0xff;
701         
702         /* Parse the drive list. */
703         if (ac != 1) {
704                 warnx("Exactly one drive list is required");
705                 return (EINVAL);
706         }
707         info = calloc(1, sizeof(*info));
708         if (info == NULL)
709                 return (ENOMEM);
710         error = parse_volume(fd, raid_type, &state, av[0], info);
711         if (error)
712                 return (error);
713
714         /* Create RAID physdisk pages for standalone disks. */
715         error = add_drives(fd, info, verbose);
716         if (error)
717                 return (error);
718
719         /* Build the volume. */
720         vol = build_volume(fd, info, raid_type, stripe_size, &state, verbose);
721         if (vol == NULL)
722                 return (errno);
723
724 #ifdef DEBUG
725         if (dump) {
726                 dump_config(vol);
727                 goto skip;
728         }
729 #endif
730
731         /* Send the new volume to the controller. */
732         error = mpt_raid_action(fd, MPI_RAID_ACTION_CREATE_VOLUME, vol->VolumeBus,
733             vol->VolumeID, 0, quick ? MPI_RAID_ACTION_ADATA_DO_NOT_SYNC : 0,
734             vol, vol->Header.PageLength * 4, NULL, NULL, 0, NULL, NULL, 1);
735         if (error) {
736                 errno = error;
737                 warn("Failed to add volume");
738                 return (error);
739         }
740
741 #ifdef DEBUG
742 skip:
743 #endif
744         mpt_rescan_bus(vol->VolumeBus, vol->VolumeID);
745
746         /* Clean up. */
747         free(vol);
748         free(info);
749         free(state.sdisks);
750         mpt_free_pd_list(state.list);
751         free(state.ioc2);
752         close(fd);
753
754         return (0);
755 }
756 MPT_COMMAND(top, create, create_volume);
757
758 static int
759 delete_volume(int ac, char **av)
760 {
761         U8 VolumeBus, VolumeID;
762         int error, fd;
763
764         if (ac != 2) {
765                 warnx("delete: volume required");
766                 return (EINVAL);
767         }
768
769         fd = mpt_open(mpt_unit);
770         if (fd < 0) {
771                 error = errno;
772                 warn("mpt_open");
773                 return (error);
774         }
775
776         error = mpt_lookup_volume(fd, av[1], &VolumeBus, &VolumeID);
777         if (error) {
778                 warnc(error, "Invalid volume %s", av[1]);
779                 return (error);
780         }
781
782         if (mpt_lock_volume(VolumeBus, VolumeID) < 0)
783                 return (errno);
784
785         error = mpt_raid_action(fd, MPI_RAID_ACTION_DELETE_VOLUME, VolumeBus,
786             VolumeID, 0, MPI_RAID_ACTION_ADATA_DEL_PHYS_DISKS |
787             MPI_RAID_ACTION_ADATA_ZERO_LBA0, NULL, 0, NULL, NULL, 0, NULL,
788             NULL, 0);
789         if (error) {
790                 warnc(error, "Failed to delete volume");
791                 return (error);
792         }
793
794         mpt_rescan_bus(-1, -1);
795         close(fd);
796
797         return (0);
798 }
799 MPT_COMMAND(top, delete, delete_volume);
800
801 static int
802 find_volume_spare_pool(int fd, const char *name, int *pool)
803 {
804         CONFIG_PAGE_RAID_VOL_0 *info;
805         CONFIG_PAGE_IOC_2 *ioc2;
806         CONFIG_PAGE_IOC_2_RAID_VOL *vol;
807         U8 VolumeBus, VolumeID;
808         int error, i, j, new_pool, pool_count[7];
809
810         error = mpt_lookup_volume(fd, name, &VolumeBus, &VolumeID);
811         if (error) {
812                 warnc(error, "Invalid volume %s", name);
813                 return (error);
814         }
815
816         info = mpt_vol_info(fd, VolumeBus, VolumeID, NULL);
817         if (info == NULL)
818                 return (errno);
819
820         /*
821          * Check for an existing pool other than pool 0 (used for
822          * global spares).
823          */
824         if ((info->VolumeSettings.HotSparePool & ~MPI_RAID_HOT_SPARE_POOL_0) !=
825             0) {
826                 *pool = 1 << (ffs(info->VolumeSettings.HotSparePool &
827                     ~MPI_RAID_HOT_SPARE_POOL_0) - 1);
828                 return (0);
829         }
830         free(info);
831
832         /*
833          * Try to find a free pool.  First, figure out which pools are
834          * in use.
835          */
836         ioc2 = mpt_read_ioc_page(fd, 2, NULL);
837         if (ioc2 == NULL) {
838                 error = errno;
839                 warn("Failed to fetch volume list");
840                 return (error);
841         }
842         bzero(pool_count, sizeof(pool_count));  
843         vol = ioc2->RaidVolume;
844         for (i = 0; i < ioc2->NumActiveVolumes; vol++, i++) {
845                 info = mpt_vol_info(fd, vol->VolumeBus, vol->VolumeID, NULL);
846                 if (info == NULL)
847                         return (errno);
848                 for (j = 0; j < 7; j++)
849                         if (info->VolumeSettings.HotSparePool & (1 << (j + 1)))
850                                 pool_count[j]++;
851                 free(info);
852         }
853         free(ioc2);
854
855         /* Find the pool with the lowest use count. */
856         new_pool = 0;
857         for (i = 1; i < 7; i++)
858                 if (pool_count[i] < pool_count[new_pool])
859                         new_pool = i;
860         new_pool++;
861
862         /* Add this pool to the volume. */
863         info = mpt_vol_info(fd, VolumeBus, VolumeID, NULL);
864         if (info == NULL)
865                 return (error);
866         info->VolumeSettings.HotSparePool |= (1 << new_pool);
867         error = mpt_raid_action(fd, MPI_RAID_ACTION_CHANGE_VOLUME_SETTINGS,
868             VolumeBus, VolumeID, 0, *(U32 *)&info->VolumeSettings, NULL, 0,
869             NULL, NULL, 0, NULL, NULL, 0);
870         if (error) {
871                 warnx("Failed to add spare pool %d to %s", new_pool,
872                     mpt_volume_name(VolumeBus, VolumeID));
873                 return (error);
874         }
875         free(info);
876
877         *pool = (1 << new_pool);
878         return (0);
879 }
880
881 static int
882 add_spare(int ac, char **av)
883 {
884         CONFIG_PAGE_RAID_PHYS_DISK_0 *info;
885         struct mpt_standalone_disk *sdisks;
886         struct mpt_drive_list *list;
887         U8 PhysDiskNum;
888         int error, fd, i, nsdisks, pool = 0;
889
890         if (ac < 2) {
891                 warnx("add spare: drive required");
892                 return (EINVAL);
893         }
894         if (ac > 3) {
895                 warnx("add spare: extra arguments");
896                 return (EINVAL);
897         }
898
899         fd = mpt_open(mpt_unit);
900         if (fd < 0) {
901                 error = errno;
902                 warn("mpt_open");
903                 return (error);
904         }
905
906         if (ac == 3) {
907                 error = find_volume_spare_pool(fd, av[2], &pool);
908                 if (error)
909                         return (error);
910         } else
911                 pool = MPI_RAID_HOT_SPARE_POOL_0;
912
913         list = mpt_pd_list(fd);
914         if (list == NULL)
915                 return (errno);
916
917         error = mpt_lookup_drive(list, av[1], &PhysDiskNum);
918         if (error) {
919                 error = mpt_fetch_disks(fd, &nsdisks, &sdisks);
920                 if (error != 0) {
921                         warn("Failed to fetch standalone disk list");
922                         return (error);
923                 }
924
925                 if (mpt_lookup_standalone_disk(av[1], sdisks, nsdisks, &i) <
926                     0) {
927                         error = errno;
928                         warn("Unable to lookup drive %s", av[1]);
929                         return (error);
930                 }
931
932                 if (mpt_lock_physdisk(&sdisks[i]) < 0)
933                         return (errno);
934
935                 if (mpt_create_physdisk(fd, &sdisks[i], &PhysDiskNum) < 0) {
936                         error = errno;
937                         warn("Failed to create physical disk page");
938                         return (error);
939                 }
940                 free(sdisks);
941         }
942         mpt_free_pd_list(list);
943
944         info = mpt_pd_info(fd, PhysDiskNum, NULL);
945         if (info == NULL) {
946                 error = errno;
947                 warn("Failed to fetch drive info");
948                 return (error);
949         }
950
951         info->PhysDiskSettings.HotSparePool = pool;
952         error = mpt_raid_action(fd, MPI_RAID_ACTION_CHANGE_PHYSDISK_SETTINGS, 0,
953             0, PhysDiskNum, *(U32 *)&info->PhysDiskSettings, NULL, 0, NULL,
954             NULL, 0, NULL, NULL, 0);
955         if (error) {
956                 warnc(error, "Failed to assign spare");
957                 return (error);
958         }
959
960         free(info);
961         close(fd);
962
963         return (0);
964 }
965 MPT_COMMAND(top, add, add_spare);
966
967 static int
968 remove_spare(int ac, char **av)
969 {
970         CONFIG_PAGE_RAID_PHYS_DISK_0 *info;
971         struct mpt_drive_list *list;
972         U8 PhysDiskNum;
973         int error, fd;
974
975         if (ac != 2) {
976                 warnx("remove spare: drive required");
977                 return (EINVAL);
978         }
979
980         fd = mpt_open(mpt_unit);
981         if (fd < 0) {
982                 error = errno;
983                 warn("mpt_open");
984                 return (error);
985         }
986
987         list = mpt_pd_list(fd);
988         if (list == NULL)
989                 return (errno);
990
991         error = mpt_lookup_drive(list, av[1], &PhysDiskNum);
992         if (error) {
993                 warn("Failed to find drive %s", av[1]);
994                 return (error);
995         }
996         mpt_free_pd_list(list);
997
998         
999         info = mpt_pd_info(fd, PhysDiskNum, NULL);
1000         if (info == NULL) {
1001                 error = errno;
1002                 warn("Failed to fetch drive info");
1003                 return (error);
1004         }
1005
1006         if (info->PhysDiskSettings.HotSparePool == 0) {
1007                 warnx("Drive %u is not a hot spare", PhysDiskNum);
1008                 return (EINVAL);
1009         }
1010
1011         if (mpt_delete_physdisk(fd, PhysDiskNum) < 0) {
1012                 error = errno;
1013                 warn("Failed to delete physical disk page");
1014                 return (error);
1015         }
1016
1017         mpt_rescan_bus(info->PhysDiskBus, info->PhysDiskID);
1018         free(info);
1019         close(fd);
1020
1021         return (0);
1022 }
1023 MPT_COMMAND(top, remove, remove_spare);
1024
1025 #ifdef DEBUG
1026 MPT_TABLE(top, pd);
1027
1028 static int
1029 pd_create(int ac, char **av)
1030 {
1031         struct mpt_standalone_disk *disks;
1032         int error, fd, i, ndisks;
1033         U8 PhysDiskNum;
1034
1035         if (ac != 2) {
1036                 warnx("pd create: drive required");
1037                 return (EINVAL);
1038         }
1039
1040         fd = mpt_open(mpt_unit);
1041         if (fd < 0) {
1042                 error = errno;
1043                 warn("mpt_open");
1044                 return (error);
1045         }
1046
1047         error = mpt_fetch_disks(fd, &ndisks, &disks);
1048         if (error != 0) {
1049                 warn("Failed to fetch standalone disk list");
1050                 return (error);
1051         }
1052
1053         if (mpt_lookup_standalone_disk(av[1], disks, ndisks, &i) < 0) {
1054                 error = errno;
1055                 warn("Unable to lookup drive");
1056                 return (error);
1057         }
1058
1059         if (mpt_lock_physdisk(&disks[i]) < 0)
1060                 return (errno);
1061
1062         if (mpt_create_physdisk(fd, &disks[i], &PhysDiskNum) < 0) {
1063                 error = errno;
1064                 warn("Failed to create physical disk page");
1065                 return (error);
1066         }
1067         free(disks);
1068
1069         printf("Added drive %s with PhysDiskNum %u\n", av[1], PhysDiskNum);
1070
1071         close(fd);
1072
1073         return (0);
1074 }
1075 MPT_COMMAND(pd, create, pd_create);
1076
1077 static int
1078 pd_delete(int ac, char **av)
1079 {
1080         CONFIG_PAGE_RAID_PHYS_DISK_0 *info;
1081         struct mpt_drive_list *list;
1082         int error, fd;
1083         U8 PhysDiskNum;
1084
1085         if (ac != 2) {
1086                 warnx("pd delete: drive required");
1087                 return (EINVAL);
1088         }
1089
1090         fd = mpt_open(mpt_unit);
1091         if (fd < 0) {
1092                 error = errno;
1093                 warn("mpt_open");
1094                 return (error);
1095         }
1096
1097         list = mpt_pd_list(fd);
1098         if (list == NULL)
1099                 return (errno);
1100
1101         if (mpt_lookup_drive(list, av[1], &PhysDiskNum) < 0) {
1102                 error = errno;
1103                 warn("Failed to find drive %s", av[1]);
1104                 return (error);
1105         }
1106         mpt_free_pd_list(list);
1107
1108         info = mpt_pd_info(fd, PhysDiskNum, NULL);
1109         if (info == NULL) {
1110                 error = errno;
1111                 warn("Failed to fetch drive info");
1112                 return (error);
1113         }
1114
1115         if (mpt_delete_physdisk(fd, PhysDiskNum) < 0) {
1116                 error = errno;
1117                 warn("Failed to delete physical disk page");
1118                 return (error);
1119         }
1120
1121         mpt_rescan_bus(info->PhysDiskBus, info->PhysDiskID);
1122         free(info);
1123         close(fd);
1124
1125         return (0);
1126 }
1127 MPT_COMMAND(pd, delete, pd_delete);
1128
1129 /* Display raw data about a volume config. */
1130 static void
1131 dump_config(CONFIG_PAGE_RAID_VOL_0 *vol)
1132 {
1133         int i;
1134
1135         printf("Volume Configuration (Debug):\n");
1136         printf(
1137    " Page Header: Type 0x%02x Number 0x%02x Length 0x%02x(%u) Version 0x%02x\n",
1138             vol->Header.PageType, vol->Header.PageNumber,
1139             vol->Header.PageLength, vol->Header.PageLength * 4,
1140             vol->Header.PageVersion);
1141         printf("     Address: %d:%d IOC %d\n", vol->VolumeBus, vol->VolumeID,
1142             vol->VolumeIOC);
1143         printf("        Type: %d (%s)\n", vol->VolumeType,
1144             mpt_raid_level(vol->VolumeType));
1145         printf("      Status: %s (Flags 0x%02x)\n",
1146             mpt_volstate(vol->VolumeStatus.State), vol->VolumeStatus.Flags);
1147         printf("    Settings: 0x%04x (Spare Pools 0x%02x)\n",
1148             vol->VolumeSettings.Settings, vol->VolumeSettings.HotSparePool);
1149         printf("      MaxLBA: %ju\n", (uintmax_t)vol->MaxLBAHigh << 32 |
1150             vol->MaxLBA);
1151         printf(" Stripe Size: %ld\n", (long)vol->StripeSize * 512);
1152         printf(" %d Disks:\n", vol->NumPhysDisks);
1153
1154         for (i = 0; i < vol->NumPhysDisks; i++)
1155                 printf("    Disk %d: Num 0x%02x Map 0x%02x\n", i,
1156                     vol->PhysDisk[i].PhysDiskNum, vol->PhysDisk[i].PhysDiskMap);
1157 }
1158
1159 static int
1160 debug_config(int ac, char **av)
1161 {
1162         CONFIG_PAGE_RAID_VOL_0 *vol;
1163         U8 VolumeBus, VolumeID;
1164         int error, fd;
1165
1166         if (ac != 2) {
1167                 warnx("debug: volume required");
1168                 return (EINVAL);
1169         }
1170
1171         fd = mpt_open(mpt_unit);
1172         if (fd < 0) {
1173                 error = errno;
1174                 warn("mpt_open");
1175                 return (error);
1176         }
1177
1178         error = mpt_lookup_volume(fd, av[1], &VolumeBus, &VolumeID);
1179         if (error) {
1180                 warnc(error, "Invalid volume: %s", av[1]);
1181                 return (error);
1182         }
1183
1184         vol = mpt_vol_info(fd, VolumeBus, VolumeID, NULL);
1185         if (vol == NULL) {
1186                 error = errno;
1187                 warn("Failed to get volume info");
1188                 return (error);
1189         }
1190
1191         dump_config(vol);
1192         free(vol);
1193         close(fd);
1194
1195         return (0);
1196 }
1197 MPT_COMMAND(top, debug, debug_config);
1198 #endif