]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c
MFV r316933: 5142 libzfs support raidz root pool (loader project)
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / vdev_geom.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2006 Pawel Jakub Dawidek <pjd@FreeBSD.org>
23  * All rights reserved.
24  *
25  * Portions Copyright (c) 2012 Martin Matuska <mm@FreeBSD.org>
26  */
27
28 #include <sys/zfs_context.h>
29 #include <sys/param.h>
30 #include <sys/kernel.h>
31 #include <sys/bio.h>
32 #include <sys/disk.h>
33 #include <sys/spa.h>
34 #include <sys/spa_impl.h>
35 #include <sys/vdev_impl.h>
36 #include <sys/fs/zfs.h>
37 #include <sys/zio.h>
38 #include <geom/geom.h>
39 #include <geom/geom_int.h>
40
41 /*
42  * Virtual device vector for GEOM.
43  */
44
45 static g_attrchanged_t vdev_geom_attrchanged;
46 struct g_class zfs_vdev_class = {
47         .name = "ZFS::VDEV",
48         .version = G_VERSION,
49         .attrchanged = vdev_geom_attrchanged,
50 };
51
52 struct consumer_vdev_elem {
53         SLIST_ENTRY(consumer_vdev_elem) elems;
54         vdev_t                          *vd;
55 };
56
57 SLIST_HEAD(consumer_priv_t, consumer_vdev_elem);
58 _Static_assert(sizeof(((struct g_consumer*)NULL)->private)
59     == sizeof(struct consumer_priv_t*),
60     "consumer_priv_t* can't be stored in g_consumer.private");
61
62 DECLARE_GEOM_CLASS(zfs_vdev_class, zfs_vdev);
63
64 SYSCTL_DECL(_vfs_zfs_vdev);
65 /* Don't send BIO_FLUSH. */
66 static int vdev_geom_bio_flush_disable;
67 SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, bio_flush_disable, CTLFLAG_RWTUN,
68     &vdev_geom_bio_flush_disable, 0, "Disable BIO_FLUSH");
69 /* Don't send BIO_DELETE. */
70 static int vdev_geom_bio_delete_disable;
71 SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, bio_delete_disable, CTLFLAG_RWTUN,
72     &vdev_geom_bio_delete_disable, 0, "Disable BIO_DELETE");
73
74 /* Declare local functions */
75 static void vdev_geom_detach(struct g_consumer *cp, boolean_t open_for_read);
76
77 /*
78  * Thread local storage used to indicate when a thread is probing geoms
79  * for their guids.  If NULL, this thread is not tasting geoms.  If non NULL,
80  * it is looking for a replacement for the vdev_t* that is its value.
81  */
82 uint_t zfs_geom_probe_vdev_key;
83
84 static void
85 vdev_geom_set_rotation_rate(vdev_t *vd, struct g_consumer *cp)
86
87         int error;
88         uint16_t rate;
89
90         error = g_getattr("GEOM::rotation_rate", cp, &rate);
91         if (error == 0)
92                 vd->vdev_rotation_rate = rate;
93         else
94                 vd->vdev_rotation_rate = VDEV_RATE_UNKNOWN;
95 }
96
97 static void
98 vdev_geom_set_physpath(vdev_t *vd, struct g_consumer *cp,
99                        boolean_t do_null_update)
100 {
101         boolean_t needs_update = B_FALSE;
102         char *physpath;
103         int error, physpath_len;
104
105         physpath_len = MAXPATHLEN;
106         physpath = g_malloc(physpath_len, M_WAITOK|M_ZERO);
107         error = g_io_getattr("GEOM::physpath", cp, &physpath_len, physpath);
108         if (error == 0) {
109                 char *old_physpath;
110
111                 /* g_topology lock ensures that vdev has not been closed */
112                 g_topology_assert();
113                 old_physpath = vd->vdev_physpath;
114                 vd->vdev_physpath = spa_strdup(physpath);
115
116                 if (old_physpath != NULL) {
117                         needs_update = (strcmp(old_physpath,
118                                                 vd->vdev_physpath) != 0);
119                         spa_strfree(old_physpath);
120                 } else
121                         needs_update = do_null_update;
122         }
123         g_free(physpath);
124
125         /*
126          * If the physical path changed, update the config.
127          * Only request an update for previously unset physpaths if
128          * requested by the caller.
129          */
130         if (needs_update)
131                 spa_async_request(vd->vdev_spa, SPA_ASYNC_CONFIG_UPDATE);
132
133 }
134
135 static void
136 vdev_geom_attrchanged(struct g_consumer *cp, const char *attr)
137 {
138         char *old_physpath;
139         struct consumer_priv_t *priv;
140         struct consumer_vdev_elem *elem;
141         int error;
142
143         priv = (struct consumer_priv_t*)&cp->private;
144         if (SLIST_EMPTY(priv))
145                 return;
146
147         SLIST_FOREACH(elem, priv, elems) {
148                 vdev_t *vd = elem->vd;
149                 if (strcmp(attr, "GEOM::rotation_rate") == 0) {
150                         vdev_geom_set_rotation_rate(vd, cp);
151                         return;
152                 }
153                 if (strcmp(attr, "GEOM::physpath") == 0) {
154                         vdev_geom_set_physpath(vd, cp, /*null_update*/B_TRUE);
155                         return;
156                 }
157         }
158 }
159
160 static void
161 vdev_geom_orphan(struct g_consumer *cp)
162 {
163         struct consumer_priv_t *priv;
164         struct consumer_vdev_elem *elem;
165
166         g_topology_assert();
167
168         priv = (struct consumer_priv_t*)&cp->private;
169         if (SLIST_EMPTY(priv))
170                 /* Vdev close in progress.  Ignore the event. */
171                 return;
172
173         /*
174          * Orphan callbacks occur from the GEOM event thread.
175          * Concurrent with this call, new I/O requests may be
176          * working their way through GEOM about to find out
177          * (only once executed by the g_down thread) that we've
178          * been orphaned from our disk provider.  These I/Os
179          * must be retired before we can detach our consumer.
180          * This is most easily achieved by acquiring the
181          * SPA ZIO configuration lock as a writer, but doing
182          * so with the GEOM topology lock held would cause
183          * a lock order reversal.  Instead, rely on the SPA's
184          * async removal support to invoke a close on this
185          * vdev once it is safe to do so.
186          */
187         SLIST_FOREACH(elem, priv, elems) {
188                 vdev_t *vd = elem->vd;
189
190                 vd->vdev_remove_wanted = B_TRUE;
191                 spa_async_request(vd->vdev_spa, SPA_ASYNC_REMOVE);
192         }
193 }
194
195 static struct g_consumer *
196 vdev_geom_attach(struct g_provider *pp, vdev_t *vd)
197 {
198         struct g_geom *gp;
199         struct g_consumer *cp;
200         int error;
201
202         g_topology_assert();
203
204         ZFS_LOG(1, "Attaching to %s.", pp->name);
205
206         if (pp->sectorsize > VDEV_PAD_SIZE || !ISP2(pp->sectorsize)) {
207                 ZFS_LOG(1, "Failing attach of %s. Incompatible sectorsize %d\n",
208                     pp->name, pp->sectorsize);
209                 return (NULL);
210         } else if (pp->mediasize < SPA_MINDEVSIZE) {
211                 ZFS_LOG(1, "Failing attach of %s. Incompatible mediasize %ju\n",
212                     pp->name, pp->mediasize);
213                 return (NULL);
214         }
215
216         /* Do we have geom already? No? Create one. */
217         LIST_FOREACH(gp, &zfs_vdev_class.geom, geom) {
218                 if (gp->flags & G_GEOM_WITHER)
219                         continue;
220                 if (strcmp(gp->name, "zfs::vdev") != 0)
221                         continue;
222                 break;
223         }
224         if (gp == NULL) {
225                 gp = g_new_geomf(&zfs_vdev_class, "zfs::vdev");
226                 gp->orphan = vdev_geom_orphan;
227                 gp->attrchanged = vdev_geom_attrchanged;
228                 cp = g_new_consumer(gp);
229                 error = g_attach(cp, pp);
230                 if (error != 0) {
231                         ZFS_LOG(1, "%s(%d): g_attach failed: %d\n", __func__,
232                             __LINE__, error);
233                         vdev_geom_detach(cp, B_FALSE);
234                         return (NULL);
235                 }
236                 error = g_access(cp, 1, 0, 1);
237                 if (error != 0) {
238                         ZFS_LOG(1, "%s(%d): g_access failed: %d", __func__,
239                                __LINE__, error);
240                         vdev_geom_detach(cp, B_FALSE);
241                         return (NULL);
242                 }
243                 ZFS_LOG(1, "Created geom and consumer for %s.", pp->name);
244         } else {
245                 /* Check if we are already connected to this provider. */
246                 LIST_FOREACH(cp, &gp->consumer, consumer) {
247                         if (cp->provider == pp) {
248                                 ZFS_LOG(1, "Found consumer for %s.", pp->name);
249                                 break;
250                         }
251                 }
252                 if (cp == NULL) {
253                         cp = g_new_consumer(gp);
254                         error = g_attach(cp, pp);
255                         if (error != 0) {
256                                 ZFS_LOG(1, "%s(%d): g_attach failed: %d\n",
257                                     __func__, __LINE__, error);
258                                 vdev_geom_detach(cp, B_FALSE);
259                                 return (NULL);
260                         }
261                         error = g_access(cp, 1, 0, 1);
262                         if (error != 0) {
263                                 ZFS_LOG(1, "%s(%d): g_access failed: %d\n",
264                                     __func__, __LINE__, error);
265                                 vdev_geom_detach(cp, B_FALSE);
266                                 return (NULL);
267                         }
268                         ZFS_LOG(1, "Created consumer for %s.", pp->name);
269                 } else {
270                         error = g_access(cp, 1, 0, 1);
271                         if (error != 0) {
272                                 ZFS_LOG(1, "%s(%d): g_access failed: %d\n",
273                                     __func__, __LINE__, error);
274                                 return (NULL);
275                         }
276                         ZFS_LOG(1, "Used existing consumer for %s.", pp->name);
277                 }
278         }
279
280         if (vd != NULL)
281                 vd->vdev_tsd = cp;
282
283         cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
284         return (cp);
285 }
286
287 static void
288 vdev_geom_detach(struct g_consumer *cp, boolean_t open_for_read)
289 {
290         struct g_geom *gp;
291
292         g_topology_assert();
293
294         ZFS_LOG(1, "Detaching from %s.",
295             cp->provider && cp->provider->name ? cp->provider->name : "NULL");
296
297         gp = cp->geom;
298         if (open_for_read)
299                 g_access(cp, -1, 0, -1);
300         /* Destroy consumer on last close. */
301         if (cp->acr == 0 && cp->ace == 0) {
302                 if (cp->acw > 0)
303                         g_access(cp, 0, -cp->acw, 0);
304                 if (cp->provider != NULL) {
305                         ZFS_LOG(1, "Destroying consumer for %s.",
306                             cp->provider->name ? cp->provider->name : "NULL");
307                         g_detach(cp);
308                 }
309                 g_destroy_consumer(cp);
310         }
311         /* Destroy geom if there are no consumers left. */
312         if (LIST_EMPTY(&gp->consumer)) {
313                 ZFS_LOG(1, "Destroyed geom %s.", gp->name);
314                 g_wither_geom(gp, ENXIO);
315         }
316 }
317
318 static void
319 vdev_geom_close_locked(vdev_t *vd)
320 {
321         struct g_consumer *cp;
322         struct consumer_priv_t *priv;
323         struct consumer_vdev_elem *elem, *elem_temp;
324
325         g_topology_assert();
326
327         cp = vd->vdev_tsd;
328         vd->vdev_delayed_close = B_FALSE;
329         if (cp == NULL)
330                 return;
331
332         ZFS_LOG(1, "Closing access to %s.", cp->provider->name);
333         KASSERT(cp->private != NULL, ("%s: cp->private is NULL", __func__));
334         priv = (struct consumer_priv_t*)&cp->private;
335         vd->vdev_tsd = NULL;
336         SLIST_FOREACH_SAFE(elem, priv, elems, elem_temp) {
337                 if (elem->vd == vd) {
338                         SLIST_REMOVE(priv, elem, consumer_vdev_elem, elems);
339                         g_free(elem);
340                 }
341         }
342
343         vdev_geom_detach(cp, B_TRUE);
344 }
345
346 /*
347  * Issue one or more bios to the vdev in parallel
348  * cmds, datas, offsets, errors, and sizes are arrays of length ncmds.  Each IO
349  * operation is described by parallel entries from each array.  There may be
350  * more bios actually issued than entries in the array
351  */
352 static void
353 vdev_geom_io(struct g_consumer *cp, int *cmds, void **datas, off_t *offsets,
354     off_t *sizes, int *errors, int ncmds)
355 {
356         struct bio **bios;
357         u_char *p;
358         off_t off, maxio, s, end;
359         int i, n_bios, j;
360         size_t bios_size;
361
362         maxio = MAXPHYS - (MAXPHYS % cp->provider->sectorsize);
363         n_bios = 0;
364
365         /* How many bios are required for all commands ? */
366         for (i = 0; i < ncmds; i++)
367                 n_bios += (sizes[i] + maxio - 1) / maxio;
368
369         /* Allocate memory for the bios */
370         bios_size = n_bios * sizeof(struct bio*);
371         bios = kmem_zalloc(bios_size, KM_SLEEP);
372
373         /* Prepare and issue all of the bios */
374         for (i = j = 0; i < ncmds; i++) {
375                 off = offsets[i];
376                 p = datas[i];
377                 s = sizes[i];
378                 end = off + s;
379                 ASSERT((off % cp->provider->sectorsize) == 0);
380                 ASSERT((s % cp->provider->sectorsize) == 0);
381
382                 for (; off < end; off += maxio, p += maxio, s -= maxio, j++) {
383                         bios[j] = g_alloc_bio();
384                         bios[j]->bio_cmd = cmds[i];
385                         bios[j]->bio_done = NULL;
386                         bios[j]->bio_offset = off;
387                         bios[j]->bio_length = MIN(s, maxio);
388                         bios[j]->bio_data = p;
389                         g_io_request(bios[j], cp);
390                 }
391         }
392         ASSERT(j == n_bios);
393
394         /* Wait for all of the bios to complete, and clean them up */
395         for (i = j = 0; i < ncmds; i++) {
396                 off = offsets[i];
397                 s = sizes[i];
398                 end = off + s;
399
400                 for (; off < end; off += maxio, s -= maxio, j++) {
401                         errors[i] = biowait(bios[j], "vdev_geom_io") || errors[i];
402                         g_destroy_bio(bios[j]);
403                 }
404         }
405         kmem_free(bios, bios_size);
406 }
407
408 /* 
409  * Read the vdev config from a device.  Return the number of valid labels that
410  * were found.  The vdev config will be returned in config if and only if at
411  * least one valid label was found.
412  */
413 static int
414 vdev_geom_read_config(struct g_consumer *cp, nvlist_t **config)
415 {
416         struct g_provider *pp;
417         vdev_phys_t *vdev_lists[VDEV_LABELS];
418         char *buf;
419         size_t buflen;
420         uint64_t psize, state, txg;
421         off_t offsets[VDEV_LABELS];
422         off_t size;
423         off_t sizes[VDEV_LABELS];
424         int cmds[VDEV_LABELS];
425         int errors[VDEV_LABELS];
426         int l, nlabels;
427
428         g_topology_assert_not();
429
430         pp = cp->provider;
431         ZFS_LOG(1, "Reading config from %s...", pp->name);
432
433         psize = pp->mediasize;
434         psize = P2ALIGN(psize, (uint64_t)sizeof(vdev_label_t));
435
436         size = sizeof(*vdev_lists[0]) + pp->sectorsize -
437             ((sizeof(*vdev_lists[0]) - 1) % pp->sectorsize) - 1;
438
439         buflen = sizeof(vdev_lists[0]->vp_nvlist);
440
441         *config = NULL;
442         /* Create all of the IO requests */
443         for (l = 0; l < VDEV_LABELS; l++) {
444                 cmds[l] = BIO_READ;
445                 vdev_lists[l] = kmem_alloc(size, KM_SLEEP);
446                 offsets[l] = vdev_label_offset(psize, l, 0) + VDEV_SKIP_SIZE;
447                 sizes[l] = size;
448                 errors[l] = 0;
449                 ASSERT(offsets[l] % pp->sectorsize == 0);
450         }
451
452         /* Issue the IO requests */
453         vdev_geom_io(cp, cmds, (void**)vdev_lists, offsets, sizes, errors,
454             VDEV_LABELS);
455
456         /* Parse the labels */
457         nlabels = 0;
458         for (l = 0; l < VDEV_LABELS; l++) {
459                 if (errors[l] != 0)
460                         continue;
461
462                 buf = vdev_lists[l]->vp_nvlist;
463
464                 if (nvlist_unpack(buf, buflen, config, 0) != 0)
465                         continue;
466
467                 if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
468                     &state) != 0 || state > POOL_STATE_L2CACHE) {
469                         nvlist_free(*config);
470                         *config = NULL;
471                         continue;
472                 }
473
474                 if (state != POOL_STATE_SPARE &&
475                     state != POOL_STATE_L2CACHE &&
476                     (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
477                     &txg) != 0 || txg == 0)) {
478                         nvlist_free(*config);
479                         *config = NULL;
480                         continue;
481                 }
482
483                 nlabels++;
484         }
485
486         /* Free the label storage */
487         for (l = 0; l < VDEV_LABELS; l++)
488                 kmem_free(vdev_lists[l], size);
489
490         return (nlabels);
491 }
492
493 static void
494 resize_configs(nvlist_t ***configs, uint64_t *count, uint64_t id)
495 {
496         nvlist_t **new_configs;
497         uint64_t i;
498
499         if (id < *count)
500                 return;
501         new_configs = kmem_zalloc((id + 1) * sizeof(nvlist_t *),
502             KM_SLEEP);
503         for (i = 0; i < *count; i++)
504                 new_configs[i] = (*configs)[i];
505         if (*configs != NULL)
506                 kmem_free(*configs, *count * sizeof(void *));
507         *configs = new_configs;
508         *count = id + 1;
509 }
510
511 static void
512 process_vdev_config(nvlist_t ***configs, uint64_t *count, nvlist_t *cfg,
513     const char *name, uint64_t* known_pool_guid)
514 {
515         nvlist_t *vdev_tree;
516         uint64_t pool_guid;
517         uint64_t vdev_guid, known_guid;
518         uint64_t id, txg, known_txg;
519         char *pname;
520         int i;
521
522         if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &pname) != 0 ||
523             strcmp(pname, name) != 0)
524                 goto ignore;
525
526         if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &pool_guid) != 0)
527                 goto ignore;
528
529         if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_TOP_GUID, &vdev_guid) != 0)
530                 goto ignore;
531
532         if (nvlist_lookup_nvlist(cfg, ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0)
533                 goto ignore;
534
535         if (nvlist_lookup_uint64(vdev_tree, ZPOOL_CONFIG_ID, &id) != 0)
536                 goto ignore;
537
538         VERIFY(nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
539
540         if (*known_pool_guid != 0) {
541                 if (pool_guid != *known_pool_guid)
542                         goto ignore;
543         } else
544                 *known_pool_guid = pool_guid;
545
546         resize_configs(configs, count, id);
547
548         if ((*configs)[id] != NULL) {
549                 VERIFY(nvlist_lookup_uint64((*configs)[id],
550                     ZPOOL_CONFIG_POOL_TXG, &known_txg) == 0);
551                 if (txg <= known_txg)
552                         goto ignore;
553                 nvlist_free((*configs)[id]);
554         }
555
556         (*configs)[id] = cfg;
557         return;
558
559 ignore:
560         nvlist_free(cfg);
561 }
562
563 int
564 vdev_geom_read_pool_label(const char *name,
565     nvlist_t ***configs, uint64_t *count)
566 {
567         struct g_class *mp;
568         struct g_geom *gp;
569         struct g_provider *pp;
570         struct g_consumer *zcp;
571         nvlist_t *vdev_cfg;
572         uint64_t pool_guid;
573         int error, nlabels;
574
575         DROP_GIANT();
576         g_topology_lock();
577
578         *configs = NULL;
579         *count = 0;
580         pool_guid = 0;
581         LIST_FOREACH(mp, &g_classes, class) {
582                 if (mp == &zfs_vdev_class)
583                         continue;
584                 LIST_FOREACH(gp, &mp->geom, geom) {
585                         if (gp->flags & G_GEOM_WITHER)
586                                 continue;
587                         LIST_FOREACH(pp, &gp->provider, provider) {
588                                 if (pp->flags & G_PF_WITHER)
589                                         continue;
590                                 zcp = vdev_geom_attach(pp, NULL);
591                                 if (zcp == NULL)
592                                         continue;
593                                 g_topology_unlock();
594                                 nlabels = vdev_geom_read_config(zcp, &vdev_cfg);
595                                 g_topology_lock();
596                                 vdev_geom_detach(zcp, B_TRUE);
597                                 if (nlabels == 0)
598                                         continue;
599                                 ZFS_LOG(1, "successfully read vdev config");
600
601                                 process_vdev_config(configs, count,
602                                     vdev_cfg, name, &pool_guid);
603                         }
604                 }
605         }
606         g_topology_unlock();
607         PICKUP_GIANT();
608
609         return (*count > 0 ? 0 : ENOENT);
610 }
611
612 enum match {
613         NO_MATCH = 0,           /* No matching labels found */
614         TOPGUID_MATCH = 1,      /* Labels match top guid, not vdev guid*/
615         ZERO_MATCH = 1,         /* Should never be returned */
616         ONE_MATCH = 2,          /* 1 label matching the vdev_guid */
617         TWO_MATCH = 3,          /* 2 label matching the vdev_guid */
618         THREE_MATCH = 4,        /* 3 label matching the vdev_guid */
619         FULL_MATCH = 5          /* all labels match the vdev_guid */
620 };
621
622 static enum match
623 vdev_attach_ok(vdev_t *vd, struct g_provider *pp)
624 {
625         nvlist_t *config;
626         uint64_t pool_guid, top_guid, vdev_guid;
627         struct g_consumer *cp;
628         int nlabels;
629
630         cp = vdev_geom_attach(pp, NULL);
631         if (cp == NULL) {
632                 ZFS_LOG(1, "Unable to attach tasting instance to %s.",
633                     pp->name);
634                 return (NO_MATCH);
635         }
636         g_topology_unlock();
637         nlabels = vdev_geom_read_config(cp, &config);
638         if (nlabels == 0) {
639                 g_topology_lock();
640                 vdev_geom_detach(cp, B_TRUE);
641                 ZFS_LOG(1, "Unable to read config from %s.", pp->name);
642                 return (NO_MATCH);
643         }
644         g_topology_lock();
645         vdev_geom_detach(cp, B_TRUE);
646
647         pool_guid = 0;
648         (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid);
649         top_guid = 0;
650         (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID, &top_guid);
651         vdev_guid = 0;
652         (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid);
653         nvlist_free(config);
654
655         /*
656          * Check that the label's pool guid matches the desired guid.
657          * Inactive spares and L2ARCs do not have any pool guid in the label.
658          */
659         if (pool_guid != 0 && pool_guid != spa_guid(vd->vdev_spa)) {
660                 ZFS_LOG(1, "pool guid mismatch for provider %s: %ju != %ju.",
661                     pp->name,
662                     (uintmax_t)spa_guid(vd->vdev_spa), (uintmax_t)pool_guid);
663                 return (NO_MATCH);
664         }
665
666         /*
667          * Check that the label's vdev guid matches the desired guid.
668          * The second condition handles possible race on vdev detach, when
669          * remaining vdev receives GUID of destroyed top level mirror vdev.
670          */
671         if (vdev_guid == vd->vdev_guid) {
672                 ZFS_LOG(1, "guids match for provider %s.", pp->name);
673                 return (ZERO_MATCH + nlabels);
674         } else if (top_guid == vd->vdev_guid && vd == vd->vdev_top) {
675                 ZFS_LOG(1, "top vdev guid match for provider %s.", pp->name);
676                 return (TOPGUID_MATCH);
677         }
678         ZFS_LOG(1, "vdev guid mismatch for provider %s: %ju != %ju.",
679             pp->name, (uintmax_t)vd->vdev_guid, (uintmax_t)vdev_guid);
680         return (NO_MATCH);
681 }
682
683 static struct g_consumer *
684 vdev_geom_attach_by_guids(vdev_t *vd)
685 {
686         struct g_class *mp;
687         struct g_geom *gp;
688         struct g_provider *pp, *best_pp;
689         struct g_consumer *cp;
690         enum match match, best_match;
691
692         g_topology_assert();
693
694         cp = NULL;
695         best_pp = NULL;
696         best_match = NO_MATCH;
697         LIST_FOREACH(mp, &g_classes, class) {
698                 if (mp == &zfs_vdev_class)
699                         continue;
700                 LIST_FOREACH(gp, &mp->geom, geom) {
701                         if (gp->flags & G_GEOM_WITHER)
702                                 continue;
703                         LIST_FOREACH(pp, &gp->provider, provider) {
704                                 match = vdev_attach_ok(vd, pp);
705                                 if (match > best_match) {
706                                         best_match = match;
707                                         best_pp = pp;
708                                 }
709                                 if (match == FULL_MATCH)
710                                         goto out;
711                         }
712                 }
713         }
714
715 out:
716         if (best_pp) {
717                 cp = vdev_geom_attach(best_pp, vd);
718                 if (cp == NULL) {
719                         printf("ZFS WARNING: Unable to attach to %s.\n",
720                             best_pp->name);
721                 }
722         }
723         return (cp);
724 }
725
726 static struct g_consumer *
727 vdev_geom_open_by_guids(vdev_t *vd)
728 {
729         struct g_consumer *cp;
730         char *buf;
731         size_t len;
732
733         g_topology_assert();
734
735         ZFS_LOG(1, "Searching by guids [%ju:%ju].",
736                 (uintmax_t)spa_guid(vd->vdev_spa), (uintmax_t)vd->vdev_guid);
737         cp = vdev_geom_attach_by_guids(vd);
738         if (cp != NULL) {
739                 len = strlen(cp->provider->name) + strlen("/dev/") + 1;
740                 buf = kmem_alloc(len, KM_SLEEP);
741
742                 snprintf(buf, len, "/dev/%s", cp->provider->name);
743                 spa_strfree(vd->vdev_path);
744                 vd->vdev_path = buf;
745
746                 ZFS_LOG(1, "Attach by guid [%ju:%ju] succeeded, provider %s.",
747                     (uintmax_t)spa_guid(vd->vdev_spa),
748                     (uintmax_t)vd->vdev_guid, cp->provider->name);
749         } else {
750                 ZFS_LOG(1, "Search by guid [%ju:%ju] failed.",
751                     (uintmax_t)spa_guid(vd->vdev_spa),
752                     (uintmax_t)vd->vdev_guid);
753         }
754
755         return (cp);
756 }
757
758 static struct g_consumer *
759 vdev_geom_open_by_path(vdev_t *vd, int check_guid)
760 {
761         struct g_provider *pp;
762         struct g_consumer *cp;
763
764         g_topology_assert();
765
766         cp = NULL;
767         pp = g_provider_by_name(vd->vdev_path + sizeof("/dev/") - 1);
768         if (pp != NULL) {
769                 ZFS_LOG(1, "Found provider by name %s.", vd->vdev_path);
770                 if (!check_guid || vdev_attach_ok(vd, pp) == FULL_MATCH)
771                         cp = vdev_geom_attach(pp, vd);
772         }
773
774         return (cp);
775 }
776
777 static int
778 vdev_geom_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize,
779     uint64_t *logical_ashift, uint64_t *physical_ashift)
780 {
781         struct g_provider *pp;
782         struct g_consumer *cp;
783         size_t bufsize;
784         int error;
785
786         /* Set the TLS to indicate downstack that we should not access zvols*/
787         VERIFY(tsd_set(zfs_geom_probe_vdev_key, vd) == 0);
788
789         /*
790          * We must have a pathname, and it must be absolute.
791          */
792         if (vd->vdev_path == NULL || vd->vdev_path[0] != '/') {
793                 vd->vdev_stat.vs_aux = VDEV_AUX_BAD_LABEL;
794                 return (EINVAL);
795         }
796
797         /*
798          * Reopen the device if it's not currently open. Otherwise,
799          * just update the physical size of the device.
800          */
801         if ((cp = vd->vdev_tsd) != NULL) {
802                 ASSERT(vd->vdev_reopening);
803                 goto skip_open;
804         }
805
806         DROP_GIANT();
807         g_topology_lock();
808         error = 0;
809
810         if (vd->vdev_spa->spa_splitting_newspa ||
811             (vd->vdev_prevstate == VDEV_STATE_UNKNOWN &&
812              vd->vdev_spa->spa_load_state == SPA_LOAD_NONE ||
813              vd->vdev_spa->spa_load_state == SPA_LOAD_CREATE)) {
814                 /*
815                  * We are dealing with a vdev that hasn't been previously
816                  * opened (since boot), and we are not loading an
817                  * existing pool configuration.  This looks like a
818                  * vdev add operation to a new or existing pool.
819                  * Assume the user knows what he/she is doing and find
820                  * GEOM provider by its name, ignoring GUID mismatches.
821                  *
822                  * XXPOLICY: It would be safer to only allow a device
823                  *           that is unlabeled or labeled but missing
824                  *           GUID information to be opened in this fashion,
825                  *           unless we are doing a split, in which case we
826                  *           should allow any guid.
827                  */
828                 cp = vdev_geom_open_by_path(vd, 0);
829         } else {
830                 /*
831                  * Try using the recorded path for this device, but only
832                  * accept it if its label data contains the expected GUIDs.
833                  */
834                 cp = vdev_geom_open_by_path(vd, 1);
835                 if (cp == NULL) {
836                         /*
837                          * The device at vd->vdev_path doesn't have the
838                          * expected GUIDs. The disks might have merely
839                          * moved around so try all other GEOM providers
840                          * to find one with the right GUIDs.
841                          */
842                         cp = vdev_geom_open_by_guids(vd);
843                 }
844         }
845
846         /* Clear the TLS now that tasting is done */
847         VERIFY(tsd_set(zfs_geom_probe_vdev_key, NULL) == 0);
848
849         if (cp == NULL) {
850                 ZFS_LOG(1, "Vdev %s not found.", vd->vdev_path);
851                 error = ENOENT;
852         } else if (cp->provider->sectorsize > VDEV_PAD_SIZE ||
853             !ISP2(cp->provider->sectorsize)) {
854                 ZFS_LOG(1, "Provider %s has unsupported sectorsize.",
855                     cp->provider->name);
856
857                 vdev_geom_close_locked(vd);
858                 error = EINVAL;
859                 cp = NULL;
860         } else if (cp->acw == 0 && (spa_mode(vd->vdev_spa) & FWRITE) != 0) {
861                 int i;
862
863                 for (i = 0; i < 5; i++) {
864                         error = g_access(cp, 0, 1, 0);
865                         if (error == 0)
866                                 break;
867                         g_topology_unlock();
868                         tsleep(vd, 0, "vdev", hz / 2);
869                         g_topology_lock();
870                 }
871                 if (error != 0) {
872                         printf("ZFS WARNING: Unable to open %s for writing (error=%d).\n",
873                             cp->provider->name, error);
874                         vdev_geom_close_locked(vd);
875                         cp = NULL;
876                 }
877         }
878         if (cp != NULL) {
879                 struct consumer_priv_t *priv;
880                 struct consumer_vdev_elem *elem;
881
882                 priv = (struct consumer_priv_t*)&cp->private;
883                 if (cp->private == NULL)
884                         SLIST_INIT(priv);
885                 elem = g_malloc(sizeof(*elem), M_WAITOK|M_ZERO);
886                 elem->vd = vd;
887                 SLIST_INSERT_HEAD(priv, elem, elems);
888         }
889
890         /* Fetch initial physical path information for this device. */
891         if (cp != NULL) {
892                 vdev_geom_attrchanged(cp, "GEOM::physpath");
893         
894                 /* Set other GEOM characteristics */
895                 vdev_geom_set_physpath(vd, cp, /*do_null_update*/B_FALSE);
896                 vdev_geom_set_rotation_rate(vd, cp);
897         }
898
899         g_topology_unlock();
900         PICKUP_GIANT();
901         if (cp == NULL) {
902                 vd->vdev_stat.vs_aux = VDEV_AUX_OPEN_FAILED;
903                 return (error);
904         }
905 skip_open:
906         pp = cp->provider;
907
908         /*
909          * Determine the actual size of the device.
910          */
911         *max_psize = *psize = pp->mediasize;
912
913         /*
914          * Determine the device's minimum transfer size and preferred
915          * transfer size.
916          */
917         *logical_ashift = highbit(MAX(pp->sectorsize, SPA_MINBLOCKSIZE)) - 1;
918         *physical_ashift = 0;
919         if (pp->stripesize > (1 << *logical_ashift) && ISP2(pp->stripesize) &&
920             pp->stripesize <= (1 << SPA_MAXASHIFT) && pp->stripeoffset == 0)
921                 *physical_ashift = highbit(pp->stripesize) - 1;
922
923         /*
924          * Clear the nowritecache settings, so that on a vdev_reopen()
925          * we will try again.
926          */
927         vd->vdev_nowritecache = B_FALSE;
928
929         return (0);
930 }
931
932 static void
933 vdev_geom_close(vdev_t *vd)
934 {
935
936         if (vd->vdev_reopening)
937                 return;
938
939         DROP_GIANT();
940         g_topology_lock();
941         vdev_geom_close_locked(vd);
942         g_topology_unlock();
943         PICKUP_GIANT();
944 }
945
946 static void
947 vdev_geom_io_intr(struct bio *bp)
948 {
949         vdev_t *vd;
950         zio_t *zio;
951
952         zio = bp->bio_caller1;
953         vd = zio->io_vd;
954         zio->io_error = bp->bio_error;
955         if (zio->io_error == 0 && bp->bio_resid != 0)
956                 zio->io_error = SET_ERROR(EIO);
957
958         switch(zio->io_error) {
959         case ENOTSUP:
960                 /*
961                  * If we get ENOTSUP for BIO_FLUSH or BIO_DELETE we know
962                  * that future attempts will never succeed. In this case
963                  * we set a persistent flag so that we don't bother with
964                  * requests in the future.
965                  */
966                 switch(bp->bio_cmd) {
967                 case BIO_FLUSH:
968                         vd->vdev_nowritecache = B_TRUE;
969                         break;
970                 case BIO_DELETE:
971                         vd->vdev_notrim = B_TRUE;
972                         break;
973                 }
974                 break;
975         case ENXIO:
976                 if (!vd->vdev_remove_wanted) {
977                         /*
978                          * If provider's error is set we assume it is being
979                          * removed.
980                          */
981                         if (bp->bio_to->error != 0) {
982                                 vd->vdev_remove_wanted = B_TRUE;
983                                 spa_async_request(zio->io_spa,
984                                     SPA_ASYNC_REMOVE);
985                         } else if (!vd->vdev_delayed_close) {
986                                 vd->vdev_delayed_close = B_TRUE;
987                         }
988                 }
989                 break;
990         }
991
992         /*
993          * We have to split bio freeing into two parts, because the ABD code
994          * cannot be called in this context and vdev_op_io_done is not called
995          * for ZIO_TYPE_IOCTL zio-s.
996          */
997         if (zio->io_type != ZIO_TYPE_READ && zio->io_type != ZIO_TYPE_WRITE) {
998                 g_destroy_bio(bp);
999                 zio->io_bio = NULL;
1000         }
1001         zio_delay_interrupt(zio);
1002 }
1003
1004 static void
1005 vdev_geom_io_start(zio_t *zio)
1006 {
1007         vdev_t *vd;
1008         struct g_consumer *cp;
1009         struct bio *bp;
1010         int error;
1011
1012         vd = zio->io_vd;
1013
1014         switch (zio->io_type) {
1015         case ZIO_TYPE_IOCTL:
1016                 /* XXPOLICY */
1017                 if (!vdev_readable(vd)) {
1018                         zio->io_error = SET_ERROR(ENXIO);
1019                         zio_interrupt(zio);
1020                         return;
1021                 } else {
1022                         switch (zio->io_cmd) {
1023                         case DKIOCFLUSHWRITECACHE:
1024                                 if (zfs_nocacheflush || vdev_geom_bio_flush_disable)
1025                                         break;
1026                                 if (vd->vdev_nowritecache) {
1027                                         zio->io_error = SET_ERROR(ENOTSUP);
1028                                         break;
1029                                 }
1030                                 goto sendreq;
1031                         default:
1032                                 zio->io_error = SET_ERROR(ENOTSUP);
1033                         }
1034                 }
1035
1036                 zio_execute(zio);
1037                 return;
1038         case ZIO_TYPE_FREE:
1039                 if (vd->vdev_notrim) {
1040                         zio->io_error = SET_ERROR(ENOTSUP);
1041                 } else if (!vdev_geom_bio_delete_disable) {
1042                         goto sendreq;
1043                 }
1044                 zio_execute(zio);
1045                 return;
1046         }
1047 sendreq:
1048         ASSERT(zio->io_type == ZIO_TYPE_READ ||
1049             zio->io_type == ZIO_TYPE_WRITE ||
1050             zio->io_type == ZIO_TYPE_FREE ||
1051             zio->io_type == ZIO_TYPE_IOCTL);
1052
1053         cp = vd->vdev_tsd;
1054         if (cp == NULL) {
1055                 zio->io_error = SET_ERROR(ENXIO);
1056                 zio_interrupt(zio);
1057                 return;
1058         }
1059         bp = g_alloc_bio();
1060         bp->bio_caller1 = zio;
1061         switch (zio->io_type) {
1062         case ZIO_TYPE_READ:
1063         case ZIO_TYPE_WRITE:
1064                 zio->io_target_timestamp = zio_handle_io_delay(zio);
1065                 bp->bio_offset = zio->io_offset;
1066                 bp->bio_length = zio->io_size;
1067                 if (zio->io_type == ZIO_TYPE_READ) {
1068                         bp->bio_cmd = BIO_READ;
1069                         bp->bio_data =
1070                             abd_borrow_buf(zio->io_abd, zio->io_size);
1071                 } else {
1072                         bp->bio_cmd = BIO_WRITE;
1073                         bp->bio_data =
1074                             abd_borrow_buf_copy(zio->io_abd, zio->io_size);
1075                 }
1076                 break;
1077         case ZIO_TYPE_FREE:
1078                 bp->bio_cmd = BIO_DELETE;
1079                 bp->bio_data = NULL;
1080                 bp->bio_offset = zio->io_offset;
1081                 bp->bio_length = zio->io_size;
1082                 break;
1083         case ZIO_TYPE_IOCTL:
1084                 bp->bio_cmd = BIO_FLUSH;
1085                 bp->bio_flags |= BIO_ORDERED;
1086                 bp->bio_data = NULL;
1087                 bp->bio_offset = cp->provider->mediasize;
1088                 bp->bio_length = 0;
1089                 break;
1090         }
1091         bp->bio_done = vdev_geom_io_intr;
1092         zio->io_bio = bp;
1093
1094         g_io_request(bp, cp);
1095 }
1096
1097 static void
1098 vdev_geom_io_done(zio_t *zio)
1099 {
1100         struct bio *bp = zio->io_bio;
1101
1102         if (zio->io_type != ZIO_TYPE_READ && zio->io_type != ZIO_TYPE_WRITE) {
1103                 ASSERT(bp == NULL);
1104                 return;
1105         }
1106
1107         if (bp == NULL) {
1108                 ASSERT3S(zio->io_error, ==, ENXIO);
1109                 return;
1110         }
1111
1112         if (zio->io_type == ZIO_TYPE_READ)
1113                 abd_return_buf_copy(zio->io_abd, bp->bio_data, zio->io_size);
1114         else
1115                 abd_return_buf(zio->io_abd, bp->bio_data, zio->io_size);
1116
1117         g_destroy_bio(bp);
1118         zio->io_bio = NULL;
1119 }
1120
1121 static void
1122 vdev_geom_hold(vdev_t *vd)
1123 {
1124 }
1125
1126 static void
1127 vdev_geom_rele(vdev_t *vd)
1128 {
1129 }
1130
1131 vdev_ops_t vdev_geom_ops = {
1132         vdev_geom_open,
1133         vdev_geom_close,
1134         vdev_default_asize,
1135         vdev_geom_io_start,
1136         vdev_geom_io_done,
1137         NULL,
1138         vdev_geom_hold,
1139         vdev_geom_rele,
1140         VDEV_TYPE_DISK,         /* name of this vdev type */
1141         B_TRUE                  /* leaf vdev */
1142 };