g_virstor.c revision 299397
1249033Ssjg/*-
2246149Ssjg * Copyright (c) 2006-2007 Ivan Voras <ivoras@freebsd.org>
3246149Ssjg * All rights reserved.
4246149Ssjg *
5246149Ssjg * Redistribution and use in source and binary forms, with or without
6246149Ssjg * modification, are permitted provided that the following conditions
7246149Ssjg * are met:
8246149Ssjg * 1. Redistributions of source code must retain the above copyright
9246149Ssjg *    notice, this list of conditions and the following disclaimer.
10246149Ssjg * 2. Redistributions in binary form must reproduce the above copyright
11246149Ssjg *    notice, this list of conditions and the following disclaimer in the
12246149Ssjg *    documentation and/or other materials provided with the distribution.
13246149Ssjg *
14246149Ssjg * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15246149Ssjg * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16246149Ssjg * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17246149Ssjg * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18246149Ssjg * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19246149Ssjg * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20246149Ssjg * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21246149Ssjg * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22246149Ssjg * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23246149Ssjg * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24246149Ssjg * SUCH DAMAGE.
25246149Ssjg */
26246149Ssjg
27246149Ssjg/* Implementation notes:
28249033Ssjg * - "Components" are wrappers around providers that make up the
29249033Ssjg *   virtual storage (i.e. a virstor has "physical" components)
30246149Ssjg */
31246149Ssjg
32246149Ssjg#include <sys/cdefs.h>
33246149Ssjg__FBSDID("$FreeBSD: stable/10/sys/geom/virstor/g_virstor.c 299397 2016-05-11 00:36:31Z pfg $");
34249033Ssjg
35249033Ssjg#include <sys/param.h>
36249033Ssjg#include <sys/systm.h>
37249033Ssjg#include <sys/kernel.h>
38246149Ssjg#include <sys/module.h>
39246149Ssjg#include <sys/lock.h>
40246149Ssjg#include <sys/mutex.h>
41249033Ssjg#include <sys/sx.h>
42246149Ssjg#include <sys/bio.h>
43246149Ssjg#include <sys/sbuf.h>
44246149Ssjg#include <sys/sysctl.h>
45246149Ssjg#include <sys/malloc.h>
46246149Ssjg#include <sys/time.h>
47246149Ssjg#include <sys/proc.h>
48246149Ssjg#include <sys/kthread.h>
49246149Ssjg#include <sys/mutex.h>
50246149Ssjg#include <vm/uma.h>
51249033Ssjg#include <geom/geom.h>
52
53#include <geom/virstor/g_virstor.h>
54#include <geom/virstor/g_virstor_md.h>
55
56FEATURE(g_virstor, "GEOM virtual storage support");
57
58/* Declare malloc(9) label */
59static MALLOC_DEFINE(M_GVIRSTOR, "gvirstor", "GEOM_VIRSTOR Data");
60
61/* GEOM class methods */
62static g_init_t g_virstor_init;
63static g_fini_t g_virstor_fini;
64static g_taste_t g_virstor_taste;
65static g_ctl_req_t g_virstor_config;
66static g_ctl_destroy_geom_t g_virstor_destroy_geom;
67
68/* Declare & initialize class structure ("geom class") */
69struct g_class g_virstor_class = {
70	.name =		G_VIRSTOR_CLASS_NAME,
71	.version =	G_VERSION,
72	.init =		g_virstor_init,
73	.fini =		g_virstor_fini,
74	.taste =	g_virstor_taste,
75	.ctlreq =	g_virstor_config,
76	.destroy_geom = g_virstor_destroy_geom
77	/* The .dumpconf and the rest are only usable for a geom instance, so
78	 * they will be set when such instance is created. */
79};
80
81/* Declare sysctl's and loader tunables */
82SYSCTL_DECL(_kern_geom);
83static SYSCTL_NODE(_kern_geom, OID_AUTO, virstor, CTLFLAG_RW, 0,
84    "GEOM_GVIRSTOR information");
85
86static u_int g_virstor_debug = 2; /* XXX: lower to 2 when released to public */
87TUNABLE_INT("kern.geom.virstor.debug", &g_virstor_debug);
88SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, debug, CTLFLAG_RW, &g_virstor_debug,
89    0, "Debug level (2=production, 5=normal, 15=excessive)");
90
91static u_int g_virstor_chunk_watermark = 100;
92TUNABLE_INT("kern.geom.virstor.chunk_watermark", &g_virstor_chunk_watermark);
93SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, chunk_watermark, CTLFLAG_RW,
94    &g_virstor_chunk_watermark, 0,
95    "Minimum number of free chunks before issuing administrative warning");
96
97static u_int g_virstor_component_watermark = 1;
98TUNABLE_INT("kern.geom.virstor.component_watermark",
99    &g_virstor_component_watermark);
100SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, component_watermark, CTLFLAG_RW,
101    &g_virstor_component_watermark, 0,
102    "Minimum number of free components before issuing administrative warning");
103
104static int read_metadata(struct g_consumer *, struct g_virstor_metadata *);
105static void write_metadata(struct g_consumer *, struct g_virstor_metadata *);
106static int clear_metadata(struct g_virstor_component *);
107static int add_provider_to_geom(struct g_virstor_softc *, struct g_provider *,
108    struct g_virstor_metadata *);
109static struct g_geom *create_virstor_geom(struct g_class *,
110    struct g_virstor_metadata *);
111static void virstor_check_and_run(struct g_virstor_softc *);
112static u_int virstor_valid_components(struct g_virstor_softc *);
113static int virstor_geom_destroy(struct g_virstor_softc *, boolean_t,
114    boolean_t);
115static void remove_component(struct g_virstor_softc *,
116    struct g_virstor_component *, boolean_t);
117static void bioq_dismantle(struct bio_queue_head *);
118static int allocate_chunk(struct g_virstor_softc *,
119    struct g_virstor_component **, u_int *, u_int *);
120static void delay_destroy_consumer(void *, int);
121static void dump_component(struct g_virstor_component *comp);
122#if 0
123static void dump_me(struct virstor_map_entry *me, unsigned int nr);
124#endif
125
126static void virstor_ctl_stop(struct gctl_req *, struct g_class *);
127static void virstor_ctl_add(struct gctl_req *, struct g_class *);
128static void virstor_ctl_remove(struct gctl_req *, struct g_class *);
129static struct g_virstor_softc * virstor_find_geom(const struct g_class *,
130    const char *);
131static void update_metadata(struct g_virstor_softc *);
132static void fill_metadata(struct g_virstor_softc *, struct g_virstor_metadata *,
133    u_int, u_int);
134
135static void g_virstor_orphan(struct g_consumer *);
136static int g_virstor_access(struct g_provider *, int, int, int);
137static void g_virstor_start(struct bio *);
138static void g_virstor_dumpconf(struct sbuf *, const char *, struct g_geom *,
139    struct g_consumer *, struct g_provider *);
140static void g_virstor_done(struct bio *);
141
142static void invalid_call(void);
143/*
144 * Initialise GEOM class (per-class callback)
145 */
146static void
147g_virstor_init(struct g_class *mp __unused)
148{
149
150	/* Catch map struct size mismatch at compile time; Map entries must
151	 * fit into MAXPHYS exactly, with no wasted space. */
152	CTASSERT(VIRSTOR_MAP_BLOCK_ENTRIES*VIRSTOR_MAP_ENTRY_SIZE == MAXPHYS);
153
154	/* Init UMA zones, TAILQ's, other global vars */
155}
156
157/*
158 * Finalise GEOM class (per-class callback)
159 */
160static void
161g_virstor_fini(struct g_class *mp __unused)
162{
163
164	/* Deinit UMA zones & global vars */
165}
166
167/*
168 * Config (per-class callback)
169 */
170static void
171g_virstor_config(struct gctl_req *req, struct g_class *cp, char const *verb)
172{
173	uint32_t *version;
174
175	g_topology_assert();
176
177	version = gctl_get_paraml(req, "version", sizeof(*version));
178	if (version == NULL) {
179		gctl_error(req, "Failed to get 'version' argument");
180		return;
181	}
182	if (*version != G_VIRSTOR_VERSION) {
183		gctl_error(req, "Userland and kernel versions out of sync");
184		return;
185	}
186
187	g_topology_unlock();
188	if (strcmp(verb, "add") == 0)
189		virstor_ctl_add(req, cp);
190	else if (strcmp(verb, "stop") == 0 || strcmp(verb, "destroy") == 0)
191		virstor_ctl_stop(req, cp);
192	else if (strcmp(verb, "remove") == 0)
193		virstor_ctl_remove(req, cp);
194	else
195		gctl_error(req, "unknown verb: '%s'", verb);
196	g_topology_lock();
197}
198
199/*
200 * "stop" verb from userland
201 */
202static void
203virstor_ctl_stop(struct gctl_req *req, struct g_class *cp)
204{
205	int *force, *nargs;
206	int i;
207
208	nargs = gctl_get_paraml(req, "nargs", sizeof *nargs);
209	if (nargs == NULL) {
210		gctl_error(req, "Error fetching argument '%s'", "nargs");
211		return;
212	}
213	if (*nargs < 1) {
214		gctl_error(req, "Invalid number of arguments");
215		return;
216	}
217	force = gctl_get_paraml(req, "force", sizeof *force);
218	if (force == NULL) {
219		gctl_error(req, "Error fetching argument '%s'", "force");
220		return;
221	}
222
223	g_topology_lock();
224	for (i = 0; i < *nargs; i++) {
225		char param[8];
226		const char *name;
227		struct g_virstor_softc *sc;
228		int error;
229
230		sprintf(param, "arg%d", i);
231		name = gctl_get_asciiparam(req, param);
232		if (name == NULL) {
233			gctl_error(req, "No 'arg%d' argument", i);
234			g_topology_unlock();
235			return;
236		}
237		sc = virstor_find_geom(cp, name);
238		if (sc == NULL) {
239			gctl_error(req, "Don't know anything about '%s'", name);
240			g_topology_unlock();
241			return;
242		}
243
244		LOG_MSG(LVL_INFO, "Stopping %s by the userland command",
245		    sc->geom->name);
246		update_metadata(sc);
247		if ((error = virstor_geom_destroy(sc, TRUE, TRUE)) != 0) {
248			LOG_MSG(LVL_ERROR, "Cannot destroy %s: %d",
249			    sc->geom->name, error);
250		}
251	}
252	g_topology_unlock();
253}
254
255/*
256 * "add" verb from userland - add new component(s) to the structure.
257 * This will be done all at once in here, without going through the
258 * .taste function for new components.
259 */
260static void
261virstor_ctl_add(struct gctl_req *req, struct g_class *cp)
262{
263	/* Note: while this is going on, I/O is being done on
264	 * the g_up and g_down threads. The idea is to make changes
265	 * to softc members in a way that can atomically activate
266	 * them all at once. */
267	struct g_virstor_softc *sc;
268	int *hardcode, *nargs;
269	const char *geom_name;	/* geom to add a component to */
270	struct g_consumer *fcp;
271	struct g_virstor_bio_q *bq;
272	u_int added;
273	int error;
274	int i;
275
276	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
277	if (nargs == NULL) {
278		gctl_error(req, "Error fetching argument '%s'", "nargs");
279		return;
280	}
281	if (*nargs < 2) {
282		gctl_error(req, "Invalid number of arguments");
283		return;
284	}
285	hardcode = gctl_get_paraml(req, "hardcode", sizeof(*hardcode));
286	if (hardcode == NULL) {
287		gctl_error(req, "Error fetching argument '%s'", "hardcode");
288		return;
289	}
290
291	/* Find "our" geom */
292	geom_name = gctl_get_asciiparam(req, "arg0");
293	if (geom_name == NULL) {
294		gctl_error(req, "Error fetching argument '%s'", "geom_name (arg0)");
295		return;
296	}
297	sc = virstor_find_geom(cp, geom_name);
298	if (sc == NULL) {
299		gctl_error(req, "Don't know anything about '%s'", geom_name);
300		return;
301	}
302
303	if (virstor_valid_components(sc) != sc->n_components) {
304		LOG_MSG(LVL_ERROR, "Cannot add components to incomplete "
305		    "virstor %s", sc->geom->name);
306		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
307		return;
308	}
309
310	fcp = sc->components[0].gcons;
311	added = 0;
312	g_topology_lock();
313	for (i = 1; i < *nargs; i++) {
314		struct g_virstor_metadata md;
315		char aname[8];
316		const char *prov_name;
317		struct g_provider *pp;
318		struct g_consumer *cp;
319		u_int nc;
320		u_int j;
321
322		snprintf(aname, sizeof aname, "arg%d", i);
323		prov_name = gctl_get_asciiparam(req, aname);
324		if (prov_name == NULL) {
325			gctl_error(req, "Error fetching argument '%s'", aname);
326			g_topology_unlock();
327			return;
328		}
329		if (strncmp(prov_name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
330			prov_name += sizeof(_PATH_DEV) - 1;
331
332		pp = g_provider_by_name(prov_name);
333		if (pp == NULL) {
334			/* This is the most common error so be verbose about it */
335			if (added != 0) {
336				gctl_error(req, "Invalid provider: '%s' (added"
337				    " %u components)", prov_name, added);
338				update_metadata(sc);
339			} else {
340				gctl_error(req, "Invalid provider: '%s'",
341				    prov_name);
342			}
343			g_topology_unlock();
344			return;
345		}
346		cp = g_new_consumer(sc->geom);
347		if (cp == NULL) {
348			gctl_error(req, "Cannot create consumer");
349			g_topology_unlock();
350			return;
351		}
352		error = g_attach(cp, pp);
353		if (error != 0) {
354			gctl_error(req, "Cannot attach a consumer to %s",
355			    pp->name);
356			g_destroy_consumer(cp);
357			g_topology_unlock();
358			return;
359		}
360		if (fcp->acr != 0 || fcp->acw != 0 || fcp->ace != 0) {
361			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
362			if (error != 0) {
363				gctl_error(req, "Access request failed for %s",
364				    pp->name);
365				g_destroy_consumer(cp);
366				g_topology_unlock();
367				return;
368			}
369		}
370		if (fcp->provider->sectorsize != pp->sectorsize) {
371			gctl_error(req, "Sector size doesn't fit for %s",
372			    pp->name);
373			g_destroy_consumer(cp);
374			g_topology_unlock();
375			return;
376		}
377		for (j = 0; j < sc->n_components; j++) {
378			if (strcmp(sc->components[j].gcons->provider->name,
379			    pp->name) == 0) {
380				gctl_error(req, "Component %s already in %s",
381				    pp->name, sc->geom->name);
382				g_destroy_consumer(cp);
383				g_topology_unlock();
384				return;
385			}
386		}
387		sc->components = realloc(sc->components,
388		    sizeof(*sc->components) * (sc->n_components + 1),
389		    M_GVIRSTOR, M_WAITOK);
390
391		nc = sc->n_components;
392		sc->components[nc].gcons = cp;
393		sc->components[nc].sc = sc;
394		sc->components[nc].index = nc;
395		sc->components[nc].chunk_count = cp->provider->mediasize /
396		    sc->chunk_size;
397		sc->components[nc].chunk_next = 0;
398		sc->components[nc].chunk_reserved = 0;
399
400		if (sc->components[nc].chunk_count < 4) {
401			gctl_error(req, "Provider too small: %s",
402			    cp->provider->name);
403			g_destroy_consumer(cp);
404			g_topology_unlock();
405			return;
406		}
407		fill_metadata(sc, &md, nc, *hardcode);
408		write_metadata(cp, &md);
409		/* The new component becomes visible when n_components is
410		 * incremented */
411		sc->n_components++;
412		added++;
413
414	}
415	/* This call to update_metadata() is critical. In case there's a
416	 * power failure in the middle of it and some components are updated
417	 * while others are not, there will be trouble on next .taste() iff
418	 * a non-updated component is detected first */
419	update_metadata(sc);
420	g_topology_unlock();
421	LOG_MSG(LVL_INFO, "Added %d component(s) to %s", added,
422	    sc->geom->name);
423	/* Fire off BIOs previously queued because there wasn't any
424	 * physical space left. If the BIOs still can't be satisfied
425	 * they will again be added to the end of the queue (during
426	 * which the mutex will be recursed) */
427	bq = malloc(sizeof(*bq), M_GVIRSTOR, M_WAITOK);
428	bq->bio = NULL;
429	mtx_lock(&sc->delayed_bio_q_mtx);
430	/* First, insert a sentinel to the queue end, so we don't
431	 * end up in an infinite loop if there's still no free
432	 * space available. */
433	STAILQ_INSERT_TAIL(&sc->delayed_bio_q, bq, linkage);
434	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
435		bq = STAILQ_FIRST(&sc->delayed_bio_q);
436		if (bq->bio != NULL) {
437			g_virstor_start(bq->bio);
438			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
439			free(bq, M_GVIRSTOR);
440		} else {
441			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
442			free(bq, M_GVIRSTOR);
443			break;
444		}
445	}
446	mtx_unlock(&sc->delayed_bio_q_mtx);
447
448}
449
450/*
451 * Find a geom handled by the class
452 */
453static struct g_virstor_softc *
454virstor_find_geom(const struct g_class *cp, const char *name)
455{
456	struct g_geom *gp;
457
458	LIST_FOREACH(gp, &cp->geom, geom) {
459		if (strcmp(name, gp->name) == 0)
460			return (gp->softc);
461	}
462	return (NULL);
463}
464
465/*
466 * Update metadata on all components to reflect the current state
467 * of these fields:
468 *    - chunk_next
469 *    - flags
470 *    - md_count
471 * Expects things to be set up so write_metadata() can work, i.e.
472 * the topology lock must be held.
473 */
474static void
475update_metadata(struct g_virstor_softc *sc)
476{
477	struct g_virstor_metadata md;
478	u_int n;
479
480	if (virstor_valid_components(sc) != sc->n_components)
481		return; /* Incomplete device */
482	LOG_MSG(LVL_DEBUG, "Updating metadata on components for %s",
483	    sc->geom->name);
484	/* Update metadata on components */
485	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__,
486	    sc->geom->class->name, sc->geom->name);
487	g_topology_assert();
488	for (n = 0; n < sc->n_components; n++) {
489		read_metadata(sc->components[n].gcons, &md);
490		md.chunk_next = sc->components[n].chunk_next;
491		md.flags = sc->components[n].flags;
492		md.md_count = sc->n_components;
493		write_metadata(sc->components[n].gcons, &md);
494	}
495}
496
497/*
498 * Fills metadata (struct md) from information stored in softc and the nc'th
499 * component of virstor
500 */
501static void
502fill_metadata(struct g_virstor_softc *sc, struct g_virstor_metadata *md,
503    u_int nc, u_int hardcode)
504{
505	struct g_virstor_component *c;
506
507	bzero(md, sizeof *md);
508	c = &sc->components[nc];
509
510	strncpy(md->md_magic, G_VIRSTOR_MAGIC, sizeof md->md_magic);
511	md->md_version = G_VIRSTOR_VERSION;
512	strncpy(md->md_name, sc->geom->name, sizeof md->md_name);
513	md->md_id = sc->id;
514	md->md_virsize = sc->virsize;
515	md->md_chunk_size = sc->chunk_size;
516	md->md_count = sc->n_components;
517
518	if (hardcode) {
519		strncpy(md->provider, c->gcons->provider->name,
520		    sizeof md->provider);
521	}
522	md->no = nc;
523	md->provsize = c->gcons->provider->mediasize;
524	md->chunk_count = c->chunk_count;
525	md->chunk_next = c->chunk_next;
526	md->chunk_reserved = c->chunk_reserved;
527	md->flags = c->flags;
528}
529
530/*
531 * Remove a component from virstor device.
532 * Can only be done if the component is unallocated.
533 */
534static void
535virstor_ctl_remove(struct gctl_req *req, struct g_class *cp)
536{
537	/* As this is executed in parallel to I/O, operations on virstor
538	 * structures must be as atomic as possible. */
539	struct g_virstor_softc *sc;
540	int *nargs;
541	const char *geom_name;
542	u_int removed;
543	int i;
544
545	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
546	if (nargs == NULL) {
547		gctl_error(req, "Error fetching argument '%s'", "nargs");
548		return;
549	}
550	if (*nargs < 2) {
551		gctl_error(req, "Invalid number of arguments");
552		return;
553	}
554	/* Find "our" geom */
555	geom_name = gctl_get_asciiparam(req, "arg0");
556	if (geom_name == NULL) {
557		gctl_error(req, "Error fetching argument '%s'",
558		    "geom_name (arg0)");
559		return;
560	}
561	sc = virstor_find_geom(cp, geom_name);
562	if (sc == NULL) {
563		gctl_error(req, "Don't know anything about '%s'", geom_name);
564		return;
565	}
566
567	if (virstor_valid_components(sc) != sc->n_components) {
568		LOG_MSG(LVL_ERROR, "Cannot remove components from incomplete "
569		    "virstor %s", sc->geom->name);
570		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
571		return;
572	}
573
574	removed = 0;
575	for (i = 1; i < *nargs; i++) {
576		char param[8];
577		const char *prov_name;
578		int j, found;
579		struct g_virstor_component *newcomp, *compbak;
580
581		sprintf(param, "arg%d", i);
582		prov_name = gctl_get_asciiparam(req, param);
583		if (prov_name == NULL) {
584			gctl_error(req, "Error fetching argument '%s'", param);
585			return;
586		}
587		if (strncmp(prov_name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
588			prov_name += sizeof(_PATH_DEV) - 1;
589
590		found = -1;
591		for (j = 0; j < sc->n_components; j++) {
592			if (strcmp(sc->components[j].gcons->provider->name,
593			    prov_name) == 0) {
594				found = j;
595				break;
596			}
597		}
598		if (found == -1) {
599			LOG_MSG(LVL_ERROR, "No %s component in %s",
600			    prov_name, sc->geom->name);
601			continue;
602		}
603
604		compbak = sc->components;
605		newcomp = malloc(sc->n_components * sizeof(*sc->components),
606		    M_GVIRSTOR, M_WAITOK | M_ZERO);
607		bcopy(sc->components, newcomp, found * sizeof(*sc->components));
608		bcopy(&sc->components[found + 1], newcomp + found,
609		    found * sizeof(*sc->components));
610		if ((sc->components[j].flags & VIRSTOR_PROVIDER_ALLOCATED) != 0) {
611			LOG_MSG(LVL_ERROR, "Allocated provider %s cannot be "
612			    "removed from %s",
613			    prov_name, sc->geom->name);
614			free(newcomp, M_GVIRSTOR);
615			/* We'll consider this non-fatal error */
616			continue;
617		}
618		/* Renumerate unallocated components */
619		for (j = 0; j < sc->n_components-1; j++) {
620			if ((sc->components[j].flags &
621			    VIRSTOR_PROVIDER_ALLOCATED) == 0) {
622				sc->components[j].index = j;
623			}
624		}
625		/* This is the critical section. If a component allocation
626		 * event happens while both variables are not yet set,
627		 * there will be trouble. Something will panic on encountering
628		 * NULL sc->components[x].gcomp member.
629		 * Luckily, component allocation happens very rarely and
630		 * removing components is an abnormal action in any case. */
631		sc->components = newcomp;
632		sc->n_components--;
633		/* End critical section */
634
635		g_topology_lock();
636		if (clear_metadata(&compbak[found]) != 0) {
637			LOG_MSG(LVL_WARNING, "Trouble ahead: cannot clear "
638			    "metadata on %s", prov_name);
639		}
640		g_detach(compbak[found].gcons);
641		g_destroy_consumer(compbak[found].gcons);
642		g_topology_unlock();
643
644		free(compbak, M_GVIRSTOR);
645
646		removed++;
647	}
648
649	/* This call to update_metadata() is critical. In case there's a
650	 * power failure in the middle of it and some components are updated
651	 * while others are not, there will be trouble on next .taste() iff
652	 * a non-updated component is detected first */
653	g_topology_lock();
654	update_metadata(sc);
655	g_topology_unlock();
656	LOG_MSG(LVL_INFO, "Removed %d component(s) from %s", removed,
657	    sc->geom->name);
658}
659
660/*
661 * Clear metadata sector on component
662 */
663static int
664clear_metadata(struct g_virstor_component *comp)
665{
666	char *buf;
667	int error;
668
669	LOG_MSG(LVL_INFO, "Clearing metadata on %s",
670	    comp->gcons->provider->name);
671	g_topology_assert();
672	error = g_access(comp->gcons, 0, 1, 0);
673	if (error != 0)
674		return (error);
675	buf = malloc(comp->gcons->provider->sectorsize, M_GVIRSTOR,
676	    M_WAITOK | M_ZERO);
677	error = g_write_data(comp->gcons,
678	    comp->gcons->provider->mediasize -
679	    comp->gcons->provider->sectorsize,
680	    buf,
681	    comp->gcons->provider->sectorsize);
682	free(buf, M_GVIRSTOR);
683	g_access(comp->gcons, 0, -1, 0);
684	return (error);
685}
686
687/*
688 * Destroy geom forcibly.
689 */
690static int
691g_virstor_destroy_geom(struct gctl_req *req __unused, struct g_class *mp,
692    struct g_geom *gp)
693{
694	struct g_virstor_softc *sc;
695	int exitval;
696
697	sc = gp->softc;
698	KASSERT(sc != NULL, ("%s: NULL sc", __func__));
699
700	exitval = 0;
701	LOG_MSG(LVL_DEBUG, "%s called for %s, sc=%p", __func__, gp->name,
702	    gp->softc);
703
704	if (sc != NULL) {
705#ifdef INVARIANTS
706		char *buf;
707		int error;
708		off_t off;
709		int isclean, count;
710		int n;
711
712		LOG_MSG(LVL_INFO, "INVARIANTS detected");
713		LOG_MSG(LVL_INFO, "Verifying allocation "
714		    "table for %s", sc->geom->name);
715		count = 0;
716		for (n = 0; n < sc->chunk_count; n++) {
717			if (sc->map[n].flags || VIRSTOR_MAP_ALLOCATED != 0)
718				count++;
719		}
720		LOG_MSG(LVL_INFO, "Device %s has %d allocated chunks",
721		    sc->geom->name, count);
722		n = off = count = 0;
723		isclean = 1;
724		if (virstor_valid_components(sc) != sc->n_components) {
725			/* This is a incomplete virstor device (not all
726			 * components have been found) */
727			LOG_MSG(LVL_ERROR, "Device %s is incomplete",
728			    sc->geom->name);
729			goto bailout;
730		}
731		error = g_access(sc->components[0].gcons, 1, 0, 0);
732		KASSERT(error == 0, ("%s: g_access failed (%d)", __func__,
733		    error));
734		/* Compare the whole on-disk allocation table with what's
735		 * currently in memory */
736		while (n < sc->chunk_count) {
737			buf = g_read_data(sc->components[0].gcons, off,
738			    sc->sectorsize, &error);
739			KASSERT(buf != NULL, ("g_read_data returned NULL (%d) "
740			    "for read at %jd", error, off));
741			if (bcmp(buf, &sc->map[n], sc->sectorsize) != 0) {
742				LOG_MSG(LVL_ERROR, "ERROR in allocation table, "
743				    "entry %d, offset %jd", n, off);
744				isclean = 0;
745				count++;
746			}
747			n += sc->me_per_sector;
748			off += sc->sectorsize;
749			g_free(buf);
750		}
751		error = g_access(sc->components[0].gcons, -1, 0, 0);
752		KASSERT(error == 0, ("%s: g_access failed (%d) on exit",
753		    __func__, error));
754		if (isclean != 1) {
755			LOG_MSG(LVL_ERROR, "ALLOCATION TABLE CORRUPTED FOR %s "
756			    "(%d sectors don't match, max %zu allocations)",
757			    sc->geom->name, count,
758			    count * sc->me_per_sector);
759		} else {
760			LOG_MSG(LVL_INFO, "Allocation table ok for %s",
761			    sc->geom->name);
762		}
763bailout:
764#endif
765		update_metadata(sc);
766		virstor_geom_destroy(sc, FALSE, FALSE);
767		exitval = EAGAIN;
768	} else
769		exitval = 0;
770	return (exitval);
771}
772
773/*
774 * Taste event (per-class callback)
775 * Examines a provider and creates geom instances if needed
776 */
777static struct g_geom *
778g_virstor_taste(struct g_class *mp, struct g_provider *pp, int flags)
779{
780	struct g_virstor_metadata md;
781	struct g_geom *gp;
782	struct g_consumer *cp;
783	struct g_virstor_softc *sc;
784	int error;
785
786	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
787	g_topology_assert();
788	LOG_MSG(LVL_DEBUG, "Tasting %s", pp->name);
789
790	/* We need a dummy geom to attach a consumer to the given provider */
791	gp = g_new_geomf(mp, "virstor:taste.helper");
792	gp->start = (void *)invalid_call;	/* XXX: hacked up so the        */
793	gp->access = (void *)invalid_call;	/* compiler doesn't complain.   */
794	gp->orphan = (void *)invalid_call;	/* I really want these to fail. */
795
796	cp = g_new_consumer(gp);
797	g_attach(cp, pp);
798	error = read_metadata(cp, &md);
799	g_detach(cp);
800	g_destroy_consumer(cp);
801	g_destroy_geom(gp);
802
803	if (error != 0)
804		return (NULL);
805
806	if (strcmp(md.md_magic, G_VIRSTOR_MAGIC) != 0)
807		return (NULL);
808	if (md.md_version != G_VIRSTOR_VERSION) {
809		LOG_MSG(LVL_ERROR, "Kernel module version invalid "
810		    "to handle %s (%s) : %d should be %d",
811		    md.md_name, pp->name, md.md_version, G_VIRSTOR_VERSION);
812		return (NULL);
813	}
814	if (md.provsize != pp->mediasize)
815		return (NULL);
816
817	/* If the provider name is hardcoded, use the offered provider only
818	 * if it's been offered with its proper name (the one used in
819	 * the label command). */
820	if (md.provider[0] != '\0' &&
821	    !g_compare_names(md.provider, pp->name))
822		return (NULL);
823
824	/* Iterate all geoms this class already knows about to see if a new
825	 * geom instance of this class needs to be created (in case the provider
826	 * is first from a (possibly) multi-consumer geom) or it just needs
827	 * to be added to an existing instance. */
828	sc = NULL;
829	gp = NULL;
830	LIST_FOREACH(gp, &mp->geom, geom) {
831		sc = gp->softc;
832		if (sc == NULL)
833			continue;
834		if (strcmp(md.md_name, sc->geom->name) != 0)
835			continue;
836		if (md.md_id != sc->id)
837			continue;
838		break;
839	}
840	if (gp != NULL) { /* We found an existing geom instance; add to it */
841		LOG_MSG(LVL_INFO, "Adding %s to %s", pp->name, md.md_name);
842		error = add_provider_to_geom(sc, pp, &md);
843		if (error != 0) {
844			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
845			    pp->name, md.md_name, error);
846			return (NULL);
847		}
848	} else { /* New geom instance needs to be created */
849		gp = create_virstor_geom(mp, &md);
850		if (gp == NULL) {
851			LOG_MSG(LVL_ERROR, "Error creating new instance of "
852			    "class %s: %s", mp->name, md.md_name);
853			LOG_MSG(LVL_DEBUG, "Error creating %s at %s",
854			    md.md_name, pp->name);
855			return (NULL);
856		}
857		sc = gp->softc;
858		LOG_MSG(LVL_INFO, "Adding %s to %s (first found)", pp->name,
859		    md.md_name);
860		error = add_provider_to_geom(sc, pp, &md);
861		if (error != 0) {
862			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
863			    pp->name, md.md_name, error);
864			virstor_geom_destroy(sc, TRUE, FALSE);
865			return (NULL);
866		}
867	}
868
869	return (gp);
870}
871
872/*
873 * Destroyes consumer passed to it in arguments. Used as a callback
874 * on g_event queue.
875 */
876static void
877delay_destroy_consumer(void *arg, int flags __unused)
878{
879	struct g_consumer *c = arg;
880	KASSERT(c != NULL, ("%s: invalid consumer", __func__));
881	LOG_MSG(LVL_DEBUG, "Consumer %s destroyed with delay",
882	    c->provider->name);
883	g_detach(c);
884	g_destroy_consumer(c);
885}
886
887/*
888 * Remove a component (consumer) from geom instance; If it's the first
889 * component being removed, orphan the provider to announce geom's being
890 * dismantled
891 */
892static void
893remove_component(struct g_virstor_softc *sc, struct g_virstor_component *comp,
894    boolean_t delay)
895{
896	struct g_consumer *c;
897
898	KASSERT(comp->gcons != NULL, ("Component with no consumer in %s",
899	    sc->geom->name));
900	c = comp->gcons;
901
902	comp->gcons = NULL;
903	KASSERT(c->provider != NULL, ("%s: no provider", __func__));
904	LOG_MSG(LVL_DEBUG, "Component %s removed from %s", c->provider->name,
905	    sc->geom->name);
906	if (sc->provider != NULL) {
907		/* Whither, GEOM? */
908		sc->provider->flags |= G_PF_WITHER;
909		g_orphan_provider(sc->provider, ENXIO);
910		sc->provider = NULL;
911		LOG_MSG(LVL_INFO, "Removing provider %s", sc->geom->name);
912	}
913
914	if (c->acr > 0 || c->acw > 0 || c->ace > 0)
915		g_access(c, -c->acr, -c->acw, -c->ace);
916	if (delay) {
917		/* Destroy consumer after it's tasted */
918		g_post_event(delay_destroy_consumer, c, M_WAITOK, NULL);
919	} else {
920		g_detach(c);
921		g_destroy_consumer(c);
922	}
923}
924
925/*
926 * Destroy geom - called internally
927 * See g_virstor_destroy_geom for the other one
928 */
929static int
930virstor_geom_destroy(struct g_virstor_softc *sc, boolean_t force,
931    boolean_t delay)
932{
933	struct g_provider *pp;
934	struct g_geom *gp;
935	u_int n;
936
937	g_topology_assert();
938
939	if (sc == NULL)
940		return (ENXIO);
941
942	pp = sc->provider;
943	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
944		LOG_MSG(force ? LVL_WARNING : LVL_ERROR,
945		    "Device %s is still open.", pp->name);
946		if (!force)
947			return (EBUSY);
948	}
949
950	for (n = 0; n < sc->n_components; n++) {
951		if (sc->components[n].gcons != NULL)
952			remove_component(sc, &sc->components[n], delay);
953	}
954
955	gp = sc->geom;
956	gp->softc = NULL;
957
958	KASSERT(sc->provider == NULL, ("Provider still exists for %s",
959	    gp->name));
960
961	/* XXX: This might or might not work, since we're called with
962	 * the topology lock held. Also, it might panic the kernel if
963	 * the error'd BIO is in softupdates code. */
964	mtx_lock(&sc->delayed_bio_q_mtx);
965	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
966		struct g_virstor_bio_q *bq;
967		bq = STAILQ_FIRST(&sc->delayed_bio_q);
968		bq->bio->bio_error = ENOSPC;
969		g_io_deliver(bq->bio, EIO);
970		STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
971		free(bq, M_GVIRSTOR);
972	}
973	mtx_unlock(&sc->delayed_bio_q_mtx);
974	mtx_destroy(&sc->delayed_bio_q_mtx);
975
976	free(sc->map, M_GVIRSTOR);
977	free(sc->components, M_GVIRSTOR);
978	bzero(sc, sizeof *sc);
979	free(sc, M_GVIRSTOR);
980
981	pp = LIST_FIRST(&gp->provider); /* We only offer one provider */
982	if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
983		LOG_MSG(LVL_DEBUG, "Device %s destroyed", gp->name);
984
985	g_wither_geom(gp, ENXIO);
986
987	return (0);
988}
989
990/*
991 * Utility function: read metadata & decode. Wants topology lock to be
992 * held.
993 */
994static int
995read_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
996{
997	struct g_provider *pp;
998	char *buf;
999	int error;
1000
1001	g_topology_assert();
1002	error = g_access(cp, 1, 0, 0);
1003	if (error != 0)
1004		return (error);
1005	pp = cp->provider;
1006	g_topology_unlock();
1007	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
1008	    &error);
1009	g_topology_lock();
1010	g_access(cp, -1, 0, 0);
1011	if (buf == NULL)
1012		return (error);
1013
1014	virstor_metadata_decode(buf, md);
1015	g_free(buf);
1016
1017	return (0);
1018}
1019
1020/**
1021 * Utility function: encode & write metadata. Assumes topology lock is
1022 * held.
1023 *
1024 * There is no useful way of recovering from errors in this function,
1025 * not involving panicking the kernel. If the metadata cannot be written
1026 * the most we can do is notify the operator and hope he spots it and
1027 * replaces the broken drive.
1028 */
1029static void
1030write_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
1031{
1032	struct g_provider *pp;
1033	char *buf;
1034	int error;
1035
1036	KASSERT(cp != NULL && md != NULL && cp->provider != NULL,
1037	    ("Something's fishy in %s", __func__));
1038	LOG_MSG(LVL_DEBUG, "Writing metadata on %s", cp->provider->name);
1039	g_topology_assert();
1040	error = g_access(cp, 0, 1, 0);
1041	if (error != 0) {
1042		LOG_MSG(LVL_ERROR, "g_access(0,1,0) failed for %s: %d",
1043		    cp->provider->name, error);
1044		return;
1045	}
1046	pp = cp->provider;
1047
1048	buf = malloc(pp->sectorsize, M_GVIRSTOR, M_WAITOK);
1049	virstor_metadata_encode(md, buf);
1050	g_topology_unlock();
1051	error = g_write_data(cp, pp->mediasize - pp->sectorsize, buf,
1052	    pp->sectorsize);
1053	g_topology_lock();
1054	g_access(cp, 0, -1, 0);
1055	free(buf, M_GVIRSTOR);
1056
1057	if (error != 0)
1058		LOG_MSG(LVL_ERROR, "Error %d writing metadata to %s",
1059		    error, cp->provider->name);
1060}
1061
1062/*
1063 * Creates a new instance of this GEOM class, initialise softc
1064 */
1065static struct g_geom *
1066create_virstor_geom(struct g_class *mp, struct g_virstor_metadata *md)
1067{
1068	struct g_geom *gp;
1069	struct g_virstor_softc *sc;
1070
1071	LOG_MSG(LVL_DEBUG, "Creating geom instance for %s (id=%u)",
1072	    md->md_name, md->md_id);
1073
1074	if (md->md_count < 1 || md->md_chunk_size < 1 ||
1075	    md->md_virsize < md->md_chunk_size) {
1076		/* This is bogus configuration, and probably means data is
1077		 * somehow corrupted. Panic, maybe? */
1078		LOG_MSG(LVL_ERROR, "Nonsensical metadata information for %s",
1079		    md->md_name);
1080		return (NULL);
1081	}
1082
1083	/* Check if it's already created */
1084	LIST_FOREACH(gp, &mp->geom, geom) {
1085		sc = gp->softc;
1086		if (sc != NULL && strcmp(sc->geom->name, md->md_name) == 0) {
1087			LOG_MSG(LVL_WARNING, "Geom %s already exists",
1088			    md->md_name);
1089			if (sc->id != md->md_id) {
1090				LOG_MSG(LVL_ERROR,
1091				    "Some stale or invalid components "
1092				    "exist for virstor device named %s. "
1093				    "You will need to <CLEAR> all stale "
1094				    "components and maybe reconfigure "
1095				    "the virstor device. Tune "
1096				    "kern.geom.virstor.debug sysctl up "
1097				    "for more information.",
1098				    sc->geom->name);
1099			}
1100			return (NULL);
1101		}
1102	}
1103	gp = g_new_geomf(mp, "%s", md->md_name);
1104	gp->softc = NULL; /* to circumevent races that test softc */
1105
1106	gp->start = g_virstor_start;
1107	gp->spoiled = g_virstor_orphan;
1108	gp->orphan = g_virstor_orphan;
1109	gp->access = g_virstor_access;
1110	gp->dumpconf = g_virstor_dumpconf;
1111
1112	sc = malloc(sizeof(*sc), M_GVIRSTOR, M_WAITOK | M_ZERO);
1113	sc->id = md->md_id;
1114	sc->n_components = md->md_count;
1115	sc->components = malloc(sizeof(struct g_virstor_component) * md->md_count,
1116	    M_GVIRSTOR, M_WAITOK | M_ZERO);
1117	sc->chunk_size = md->md_chunk_size;
1118	sc->virsize = md->md_virsize;
1119	STAILQ_INIT(&sc->delayed_bio_q);
1120	mtx_init(&sc->delayed_bio_q_mtx, "gvirstor_delayed_bio_q_mtx",
1121	    "gvirstor", MTX_DEF | MTX_RECURSE);
1122
1123	sc->geom = gp;
1124	sc->provider = NULL; /* virstor_check_and_run will create it */
1125	gp->softc = sc;
1126
1127	LOG_MSG(LVL_ANNOUNCE, "Device %s created", sc->geom->name);
1128
1129	return (gp);
1130}
1131
1132/*
1133 * Add provider to a GEOM class instance
1134 */
1135static int
1136add_provider_to_geom(struct g_virstor_softc *sc, struct g_provider *pp,
1137    struct g_virstor_metadata *md)
1138{
1139	struct g_virstor_component *component;
1140	struct g_consumer *cp, *fcp;
1141	struct g_geom *gp;
1142	int error;
1143
1144	if (md->no >= sc->n_components)
1145		return (EINVAL);
1146
1147	/* "Current" compontent */
1148	component = &(sc->components[md->no]);
1149	if (component->gcons != NULL)
1150		return (EEXIST);
1151
1152	gp = sc->geom;
1153	fcp = LIST_FIRST(&gp->consumer);
1154
1155	cp = g_new_consumer(gp);
1156	error = g_attach(cp, pp);
1157
1158	if (error != 0) {
1159		g_destroy_consumer(cp);
1160		return (error);
1161	}
1162
1163	if (fcp != NULL) {
1164		if (fcp->provider->sectorsize != pp->sectorsize) {
1165			/* TODO: this can be made to work */
1166			LOG_MSG(LVL_ERROR, "Provider %s of %s has invalid "
1167			    "sector size (%d)", pp->name, sc->geom->name,
1168			    pp->sectorsize);
1169			return (EINVAL);
1170		}
1171		if (fcp->acr > 0 || fcp->acw || fcp->ace > 0) {
1172			/* Replicate access permissions from first "live" consumer
1173			 * to the new one */
1174			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
1175			if (error != 0) {
1176				g_detach(cp);
1177				g_destroy_consumer(cp);
1178				return (error);
1179			}
1180		}
1181	}
1182
1183	/* Bring up a new component */
1184	cp->private = component;
1185	component->gcons = cp;
1186	component->sc = sc;
1187	component->index = md->no;
1188	component->chunk_count = md->chunk_count;
1189	component->chunk_next = md->chunk_next;
1190	component->chunk_reserved = md->chunk_reserved;
1191	component->flags = md->flags;
1192
1193	LOG_MSG(LVL_DEBUG, "%s attached to %s", pp->name, sc->geom->name);
1194
1195	virstor_check_and_run(sc);
1196	return (0);
1197}
1198
1199/*
1200 * Check if everything's ready to create the geom provider & device entry,
1201 * create and start provider.
1202 * Called ultimately by .taste, from g_event thread
1203 */
1204static void
1205virstor_check_and_run(struct g_virstor_softc *sc)
1206{
1207	off_t off;
1208	size_t n, count;
1209	int index;
1210	int error;
1211
1212	if (virstor_valid_components(sc) != sc->n_components)
1213		return;
1214
1215	if (virstor_valid_components(sc) == 0) {
1216		/* This is actually a candidate for panic() */
1217		LOG_MSG(LVL_ERROR, "No valid components for %s?",
1218		    sc->provider->name);
1219		return;
1220	}
1221
1222	sc->sectorsize = sc->components[0].gcons->provider->sectorsize;
1223
1224	/* Initialise allocation map from the first consumer */
1225	sc->chunk_count = sc->virsize / sc->chunk_size;
1226	if (sc->chunk_count * (off_t)sc->chunk_size != sc->virsize) {
1227		LOG_MSG(LVL_WARNING, "Device %s truncated to %ju bytes",
1228		    sc->provider->name,
1229		    sc->chunk_count * (off_t)sc->chunk_size);
1230	}
1231	sc->map_size = sc->chunk_count * sizeof *(sc->map);
1232	/* The following allocation is in order of 4MB - 8MB */
1233	sc->map = malloc(sc->map_size, M_GVIRSTOR, M_WAITOK);
1234	KASSERT(sc->map != NULL, ("%s: Memory allocation error (%zu bytes) for %s",
1235	    __func__, sc->map_size, sc->provider->name));
1236	sc->map_sectors = sc->map_size / sc->sectorsize;
1237
1238	count = 0;
1239	for (n = 0; n < sc->n_components; n++)
1240		count += sc->components[n].chunk_count;
1241	LOG_MSG(LVL_INFO, "Device %s has %zu physical chunks and %zu virtual "
1242	    "(%zu KB chunks)",
1243	    sc->geom->name, count, sc->chunk_count, sc->chunk_size / 1024);
1244
1245	error = g_access(sc->components[0].gcons, 1, 0, 0);
1246	if (error != 0) {
1247		LOG_MSG(LVL_ERROR, "Cannot acquire read access for %s to "
1248		    "read allocation map for %s",
1249		    sc->components[0].gcons->provider->name,
1250		    sc->geom->name);
1251		return;
1252	}
1253	/* Read in the allocation map */
1254	LOG_MSG(LVL_DEBUG, "Reading map for %s from %s", sc->geom->name,
1255	    sc->components[0].gcons->provider->name);
1256	off = count = n = 0;
1257	while (count < sc->map_size) {
1258		struct g_virstor_map_entry *mapbuf;
1259		size_t bs;
1260
1261		bs = MIN(MAXPHYS, sc->map_size - count);
1262		if (bs % sc->sectorsize != 0) {
1263			/* Check for alignment errors */
1264			bs = (bs / sc->sectorsize) * sc->sectorsize;
1265			if (bs == 0)
1266				break;
1267			LOG_MSG(LVL_ERROR, "Trouble: map is not sector-aligned "
1268			    "for %s on %s", sc->geom->name,
1269			    sc->components[0].gcons->provider->name);
1270		}
1271		mapbuf = g_read_data(sc->components[0].gcons, off, bs, &error);
1272		if (mapbuf == NULL) {
1273			free(sc->map, M_GVIRSTOR);
1274			LOG_MSG(LVL_ERROR, "Error reading allocation map "
1275			    "for %s from %s (offset %ju) (error %d)",
1276			    sc->geom->name,
1277			    sc->components[0].gcons->provider->name,
1278			    off, error);
1279			return;
1280		}
1281
1282		bcopy(mapbuf, &sc->map[n], bs);
1283		off += bs;
1284		count += bs;
1285		n += bs / sizeof *(sc->map);
1286		g_free(mapbuf);
1287	}
1288	g_access(sc->components[0].gcons, -1, 0, 0);
1289	LOG_MSG(LVL_DEBUG, "Read map for %s", sc->geom->name);
1290
1291	/* find first component with allocatable chunks */
1292	index = -1;
1293	for (n = 0; n < sc->n_components; n++) {
1294		if (sc->components[n].chunk_next <
1295		    sc->components[n].chunk_count) {
1296			index = n;
1297			break;
1298		}
1299	}
1300	if (index == -1)
1301		/* not found? set it to the last component and handle it
1302		 * later */
1303		index = sc->n_components - 1;
1304
1305	if (index >= sc->n_components - g_virstor_component_watermark - 1) {
1306		LOG_MSG(LVL_WARNING, "Device %s running out of components "
1307		    "(%d/%u: %s)", sc->geom->name,
1308		    index+1,
1309		    sc->n_components,
1310		    sc->components[index].gcons->provider->name);
1311	}
1312	sc->curr_component = index;
1313
1314	if (sc->components[index].chunk_next >=
1315	    sc->components[index].chunk_count - g_virstor_chunk_watermark) {
1316		LOG_MSG(LVL_WARNING,
1317		    "Component %s of %s is running out of free space "
1318		    "(%u chunks left)",
1319		    sc->components[index].gcons->provider->name,
1320		    sc->geom->name, sc->components[index].chunk_count -
1321		    sc->components[index].chunk_next);
1322	}
1323
1324	sc->me_per_sector = sc->sectorsize / sizeof *(sc->map);
1325	if (sc->sectorsize % sizeof *(sc->map) != 0) {
1326		LOG_MSG(LVL_ERROR,
1327		    "%s: Map entries don't fit exactly in a sector (%s)",
1328		    __func__, sc->geom->name);
1329		return;
1330	}
1331
1332	/* Recalculate allocated chunks in components & at the same time
1333	 * verify map data is sane. We could trust metadata on this, but
1334	 * we want to make sure. */
1335	for (n = 0; n < sc->n_components; n++)
1336		sc->components[n].chunk_next = sc->components[n].chunk_reserved;
1337
1338	for (n = 0; n < sc->chunk_count; n++) {
1339		if (sc->map[n].provider_no >= sc->n_components ||
1340			sc->map[n].provider_chunk >=
1341			sc->components[sc->map[n].provider_no].chunk_count) {
1342			LOG_MSG(LVL_ERROR, "%s: Invalid entry %u in map for %s",
1343			    __func__, (u_int)n, sc->geom->name);
1344			LOG_MSG(LVL_ERROR, "%s: provider_no: %u, n_components: %u"
1345			    " provider_chunk: %u, chunk_count: %u", __func__,
1346			    sc->map[n].provider_no, sc->n_components,
1347			    sc->map[n].provider_chunk,
1348			    sc->components[sc->map[n].provider_no].chunk_count);
1349			return;
1350		}
1351		if (sc->map[n].flags & VIRSTOR_MAP_ALLOCATED)
1352			sc->components[sc->map[n].provider_no].chunk_next++;
1353	}
1354
1355	sc->provider = g_new_providerf(sc->geom, "virstor/%s",
1356	    sc->geom->name);
1357
1358	sc->provider->sectorsize = sc->sectorsize;
1359	sc->provider->mediasize = sc->virsize;
1360	g_error_provider(sc->provider, 0);
1361
1362	LOG_MSG(LVL_INFO, "%s activated", sc->provider->name);
1363	LOG_MSG(LVL_DEBUG, "%s starting with current component %u, starting "
1364	    "chunk %u", sc->provider->name, sc->curr_component,
1365	    sc->components[sc->curr_component].chunk_next);
1366}
1367
1368/*
1369 * Returns count of active providers in this geom instance
1370 */
1371static u_int
1372virstor_valid_components(struct g_virstor_softc *sc)
1373{
1374	unsigned int nc, i;
1375
1376	nc = 0;
1377	KASSERT(sc != NULL, ("%s: softc is NULL", __func__));
1378	KASSERT(sc->components != NULL, ("%s: sc->components is NULL", __func__));
1379	for (i = 0; i < sc->n_components; i++)
1380		if (sc->components[i].gcons != NULL)
1381			nc++;
1382	return (nc);
1383}
1384
1385/*
1386 * Called when the consumer gets orphaned (?)
1387 */
1388static void
1389g_virstor_orphan(struct g_consumer *cp)
1390{
1391	struct g_virstor_softc *sc;
1392	struct g_virstor_component *comp;
1393	struct g_geom *gp;
1394
1395	g_topology_assert();
1396	gp = cp->geom;
1397	sc = gp->softc;
1398	if (sc == NULL)
1399		return;
1400
1401	comp = cp->private;
1402	KASSERT(comp != NULL, ("%s: No component in private part of consumer",
1403	    __func__));
1404	remove_component(sc, comp, FALSE);
1405	if (virstor_valid_components(sc) == 0)
1406		virstor_geom_destroy(sc, TRUE, FALSE);
1407}
1408
1409/*
1410 * Called to notify geom when it's been opened, and for what intent
1411 */
1412static int
1413g_virstor_access(struct g_provider *pp, int dr, int dw, int de)
1414{
1415	struct g_consumer *c;
1416	struct g_virstor_softc *sc;
1417	struct g_geom *gp;
1418	int error;
1419
1420	KASSERT(pp != NULL, ("%s: NULL provider", __func__));
1421	gp = pp->geom;
1422	KASSERT(gp != NULL, ("%s: NULL geom", __func__));
1423	sc = gp->softc;
1424
1425	if (sc == NULL) {
1426		/* It seems that .access can be called with negative dr,dw,dx
1427		 * in this case but I want to check for myself */
1428		LOG_MSG(LVL_WARNING, "access(%d, %d, %d) for %s",
1429		    dr, dw, de, pp->name);
1430		/* This should only happen when geom is withered so
1431		 * allow only negative requests */
1432		KASSERT(dr <= 0 && dw <= 0 && de <= 0,
1433		    ("%s: Positive access for %s", __func__, pp->name));
1434		if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0)
1435			LOG_MSG(LVL_DEBUG, "Device %s definitely destroyed",
1436			    pp->name);
1437		return (0);
1438	}
1439
1440	/* Grab an exclusive bit to propagate on our consumers on first open */
1441	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0)
1442		de++;
1443	/* ... drop it on close */
1444	if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0) {
1445		de--;
1446		update_metadata(sc);	/* Writes statistical information */
1447	}
1448
1449	error = ENXIO;
1450	LIST_FOREACH(c, &gp->consumer, consumer) {
1451		KASSERT(c != NULL, ("%s: consumer is NULL", __func__));
1452		error = g_access(c, dr, dw, de);
1453		if (error != 0) {
1454			struct g_consumer *c2;
1455
1456			/* Backout earlier changes */
1457			LIST_FOREACH(c2, &gp->consumer, consumer) {
1458				if (c2 == c) /* all eariler components fixed */
1459					return (error);
1460				g_access(c2, -dr, -dw, -de);
1461			}
1462		}
1463	}
1464
1465	return (error);
1466}
1467
1468/*
1469 * Generate XML dump of current state
1470 */
1471static void
1472g_virstor_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1473    struct g_consumer *cp, struct g_provider *pp)
1474{
1475	struct g_virstor_softc *sc;
1476
1477	g_topology_assert();
1478	sc = gp->softc;
1479
1480	if (sc == NULL || pp != NULL)
1481		return;
1482
1483	if (cp != NULL) {
1484		/* For each component */
1485		struct g_virstor_component *comp;
1486
1487		comp = cp->private;
1488		if (comp == NULL)
1489			return;
1490		sbuf_printf(sb, "%s<ComponentIndex>%u</ComponentIndex>\n",
1491		    indent, comp->index);
1492		sbuf_printf(sb, "%s<ChunkCount>%u</ChunkCount>\n",
1493		    indent, comp->chunk_count);
1494		sbuf_printf(sb, "%s<ChunksUsed>%u</ChunksUsed>\n",
1495		    indent, comp->chunk_next);
1496		sbuf_printf(sb, "%s<ChunksReserved>%u</ChunksReserved>\n",
1497		    indent, comp->chunk_reserved);
1498		sbuf_printf(sb, "%s<StorageFree>%u%%</StorageFree>\n",
1499		    indent,
1500		    comp->chunk_next > 0 ? 100 -
1501		    ((comp->chunk_next + comp->chunk_reserved) * 100) /
1502		    comp->chunk_count : 100);
1503	} else {
1504		/* For the whole thing */
1505		u_int count, used, i;
1506		off_t size;
1507
1508		count = used = size = 0;
1509		for (i = 0; i < sc->n_components; i++) {
1510			if (sc->components[i].gcons != NULL) {
1511				count += sc->components[i].chunk_count;
1512				used += sc->components[i].chunk_next +
1513				    sc->components[i].chunk_reserved;
1514				size += sc->components[i].gcons->
1515				    provider->mediasize;
1516			}
1517		}
1518
1519		sbuf_printf(sb, "%s<Status>"
1520		    "Components=%u, Online=%u</Status>\n", indent,
1521		    sc->n_components, virstor_valid_components(sc));
1522		sbuf_printf(sb, "%s<State>%u%% physical free</State>\n",
1523		    indent, 100-(used * 100) / count);
1524		sbuf_printf(sb, "%s<ChunkSize>%zu</ChunkSize>\n", indent,
1525		    sc->chunk_size);
1526		sbuf_printf(sb, "%s<PhysicalFree>%u%%</PhysicalFree>\n",
1527		    indent, used > 0 ? 100 - (used * 100) / count : 100);
1528		sbuf_printf(sb, "%s<ChunkPhysicalCount>%u</ChunkPhysicalCount>\n",
1529		    indent, count);
1530		sbuf_printf(sb, "%s<ChunkVirtualCount>%zu</ChunkVirtualCount>\n",
1531		    indent, sc->chunk_count);
1532		sbuf_printf(sb, "%s<PhysicalBacking>%zu%%</PhysicalBacking>\n",
1533		    indent,
1534		    (count * 100) / sc->chunk_count);
1535		sbuf_printf(sb, "%s<PhysicalBackingSize>%jd</PhysicalBackingSize>\n",
1536		    indent, size);
1537		sbuf_printf(sb, "%s<VirtualSize>%jd</VirtualSize>\n", indent,
1538		    sc->virsize);
1539	}
1540}
1541
1542/*
1543 * GEOM .done handler
1544 * Can't use standard handler because one requested IO may
1545 * fork into additional data IOs
1546 */
1547static void
1548g_virstor_done(struct bio *b)
1549{
1550	struct g_virstor_softc *sc;
1551	struct bio *parent_b;
1552
1553	parent_b = b->bio_parent;
1554	sc = parent_b->bio_to->geom->softc;
1555
1556	if (b->bio_error != 0) {
1557		LOG_MSG(LVL_ERROR, "Error %d for offset=%ju, length=%ju, %s",
1558		    b->bio_error, b->bio_offset, b->bio_length,
1559		    b->bio_to->name);
1560		if (parent_b->bio_error == 0)
1561			parent_b->bio_error = b->bio_error;
1562	}
1563
1564	parent_b->bio_inbed++;
1565	parent_b->bio_completed += b->bio_completed;
1566
1567	if (parent_b->bio_children == parent_b->bio_inbed) {
1568		parent_b->bio_completed = parent_b->bio_length;
1569		g_io_deliver(parent_b, parent_b->bio_error);
1570	}
1571	g_destroy_bio(b);
1572}
1573
1574/*
1575 * I/O starts here
1576 * Called in g_down thread
1577 */
1578static void
1579g_virstor_start(struct bio *b)
1580{
1581	struct g_virstor_softc *sc;
1582	struct g_virstor_component *comp;
1583	struct bio *cb;
1584	struct g_provider *pp;
1585	char *addr;
1586	off_t offset, length;
1587	struct bio_queue_head bq;
1588	size_t chunk_size;	/* cached for convenience */
1589	u_int count;
1590
1591	pp = b->bio_to;
1592	sc = pp->geom->softc;
1593	KASSERT(sc != NULL, ("%s: no softc (error=%d, device=%s)", __func__,
1594	    b->bio_to->error, b->bio_to->name));
1595
1596	LOG_REQ(LVL_MOREDEBUG, b, "%s", __func__);
1597
1598	switch (b->bio_cmd) {
1599	case BIO_READ:
1600	case BIO_WRITE:
1601	case BIO_DELETE:
1602		break;
1603	default:
1604		g_io_deliver(b, EOPNOTSUPP);
1605		return;
1606	}
1607
1608	LOG_MSG(LVL_DEBUG2, "BIO arrived, size=%ju", b->bio_length);
1609	bioq_init(&bq);
1610
1611	chunk_size = sc->chunk_size;
1612	addr = b->bio_data;
1613	offset = b->bio_offset;	/* virtual offset and length */
1614	length = b->bio_length;
1615
1616	while (length > 0) {
1617		size_t chunk_index, in_chunk_offset, in_chunk_length;
1618		struct virstor_map_entry *me;
1619
1620		chunk_index = offset / chunk_size; /* round downwards */
1621		in_chunk_offset = offset % chunk_size;
1622		in_chunk_length = min(length, chunk_size - in_chunk_offset);
1623		LOG_MSG(LVL_DEBUG, "Mapped %s(%ju, %ju) to (%zu,%zu,%zu)",
1624		    b->bio_cmd == BIO_READ ? "R" : "W",
1625		    offset, length,
1626		    chunk_index, in_chunk_offset, in_chunk_length);
1627		me = &sc->map[chunk_index];
1628
1629		if (b->bio_cmd == BIO_READ || b->bio_cmd == BIO_DELETE) {
1630			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1631				/* Reads from unallocated chunks return zeroed
1632				 * buffers */
1633				if (b->bio_cmd == BIO_READ)
1634					bzero(addr, in_chunk_length);
1635			} else {
1636				comp = &sc->components[me->provider_no];
1637
1638				cb = g_clone_bio(b);
1639				if (cb == NULL) {
1640					bioq_dismantle(&bq);
1641					if (b->bio_error == 0)
1642						b->bio_error = ENOMEM;
1643					g_io_deliver(b, b->bio_error);
1644					return;
1645				}
1646				cb->bio_to = comp->gcons->provider;
1647				cb->bio_done = g_virstor_done;
1648				cb->bio_offset =
1649				    (off_t)me->provider_chunk * (off_t)chunk_size
1650				    + in_chunk_offset;
1651				cb->bio_length = in_chunk_length;
1652				cb->bio_data = addr;
1653				cb->bio_caller1 = comp;
1654				bioq_disksort(&bq, cb);
1655			}
1656		} else { /* handle BIO_WRITE */
1657			KASSERT(b->bio_cmd == BIO_WRITE,
1658			    ("%s: Unknown command %d", __func__,
1659			    b->bio_cmd));
1660
1661			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1662				/* We have a virtual chunk, represented by
1663				 * the "me" entry, but it's not yet allocated
1664				 * (tied to) a physical chunk. So do it now. */
1665				struct virstor_map_entry *data_me;
1666				u_int phys_chunk, comp_no;
1667				off_t s_offset;
1668				int error;
1669
1670				error = allocate_chunk(sc, &comp, &comp_no,
1671				    &phys_chunk);
1672				if (error != 0) {
1673					/* We cannot allocate a physical chunk
1674					 * to satisfy this request, so we'll
1675					 * delay it to when we can...
1676					 * XXX: this will prevent the fs from
1677					 * being umounted! */
1678					struct g_virstor_bio_q *biq;
1679					biq = malloc(sizeof *biq, M_GVIRSTOR,
1680					    M_NOWAIT);
1681					if (biq == NULL) {
1682						bioq_dismantle(&bq);
1683						if (b->bio_error == 0)
1684							b->bio_error = ENOMEM;
1685						g_io_deliver(b, b->bio_error);
1686						return;
1687					}
1688					biq->bio = b;
1689					mtx_lock(&sc->delayed_bio_q_mtx);
1690					STAILQ_INSERT_TAIL(&sc->delayed_bio_q,
1691					    biq, linkage);
1692					mtx_unlock(&sc->delayed_bio_q_mtx);
1693					LOG_MSG(LVL_WARNING, "Delaying BIO "
1694					    "(size=%ju) until free physical "
1695					    "space can be found on %s",
1696					    b->bio_length,
1697					    sc->provider->name);
1698					return;
1699				}
1700				LOG_MSG(LVL_DEBUG, "Allocated chunk %u on %s "
1701				    "for %s",
1702				    phys_chunk,
1703				    comp->gcons->provider->name,
1704				    sc->provider->name);
1705
1706				me->provider_no = comp_no;
1707				me->provider_chunk = phys_chunk;
1708				me->flags |= VIRSTOR_MAP_ALLOCATED;
1709
1710				cb = g_clone_bio(b);
1711				if (cb == NULL) {
1712					me->flags &= ~VIRSTOR_MAP_ALLOCATED;
1713					me->provider_no = 0;
1714					me->provider_chunk = 0;
1715					bioq_dismantle(&bq);
1716					if (b->bio_error == 0)
1717						b->bio_error = ENOMEM;
1718					g_io_deliver(b, b->bio_error);
1719					return;
1720				}
1721
1722				/* The allocation table is stored continuously
1723				 * at the start of the drive. We need to
1724				 * calculate the offset of the sector that holds
1725				 * this map entry both on the drive and in the
1726				 * map array.
1727				 * sc_offset will end up pointing to the drive
1728				 * sector. */
1729				s_offset = chunk_index * sizeof *me;
1730				s_offset = (s_offset / sc->sectorsize) *
1731				    sc->sectorsize;
1732
1733				/* data_me points to map entry sector
1734				 * in memory (analoguos to offset) */
1735				data_me = &sc->map[(chunk_index /
1736				    sc->me_per_sector) * sc->me_per_sector];
1737
1738				/* Commit sector with map entry to storage */
1739				cb->bio_to = sc->components[0].gcons->provider;
1740				cb->bio_done = g_virstor_done;
1741				cb->bio_offset = s_offset;
1742				cb->bio_data = (char *)data_me;
1743				cb->bio_length = sc->sectorsize;
1744				cb->bio_caller1 = &sc->components[0];
1745				bioq_disksort(&bq, cb);
1746			}
1747
1748			comp = &sc->components[me->provider_no];
1749			cb = g_clone_bio(b);
1750			if (cb == NULL) {
1751				bioq_dismantle(&bq);
1752				if (b->bio_error == 0)
1753					b->bio_error = ENOMEM;
1754				g_io_deliver(b, b->bio_error);
1755				return;
1756			}
1757			/* Finally, handle the data */
1758			cb->bio_to = comp->gcons->provider;
1759			cb->bio_done = g_virstor_done;
1760			cb->bio_offset = (off_t)me->provider_chunk*(off_t)chunk_size +
1761			    in_chunk_offset;
1762			cb->bio_length = in_chunk_length;
1763			cb->bio_data = addr;
1764			cb->bio_caller1 = comp;
1765			bioq_disksort(&bq, cb);
1766		}
1767		addr += in_chunk_length;
1768		length -= in_chunk_length;
1769		offset += in_chunk_length;
1770	}
1771
1772	/* Fire off bio's here */
1773	count = 0;
1774	for (cb = bioq_first(&bq); cb != NULL; cb = bioq_first(&bq)) {
1775		bioq_remove(&bq, cb);
1776		LOG_REQ(LVL_MOREDEBUG, cb, "Firing request");
1777		comp = cb->bio_caller1;
1778		cb->bio_caller1 = NULL;
1779		LOG_MSG(LVL_DEBUG, " firing bio, offset=%ju, length=%ju",
1780		    cb->bio_offset, cb->bio_length);
1781		g_io_request(cb, comp->gcons);
1782		count++;
1783	}
1784	if (count == 0) { /* We handled everything locally */
1785		b->bio_completed = b->bio_length;
1786		g_io_deliver(b, 0);
1787	}
1788
1789}
1790
1791/*
1792 * Allocate a chunk from a physical provider. Returns physical component,
1793 * chunk index relative to the component and the component's index.
1794 */
1795static int
1796allocate_chunk(struct g_virstor_softc *sc, struct g_virstor_component **comp,
1797    u_int *comp_no_p, u_int *chunk)
1798{
1799	u_int comp_no;
1800
1801	KASSERT(sc->curr_component < sc->n_components,
1802	    ("%s: Invalid curr_component: %u",  __func__, sc->curr_component));
1803
1804	comp_no = sc->curr_component;
1805	*comp = &sc->components[comp_no];
1806	dump_component(*comp);
1807	if ((*comp)->chunk_next >= (*comp)->chunk_count) {
1808		/* This component is full. Allocate next component */
1809		if (comp_no >= sc->n_components-1) {
1810			LOG_MSG(LVL_ERROR, "All physical space allocated for %s",
1811			    sc->geom->name);
1812			return (-1);
1813		}
1814		(*comp)->flags &= ~VIRSTOR_PROVIDER_CURRENT;
1815		sc->curr_component = ++comp_no;
1816
1817		*comp = &sc->components[comp_no];
1818		if (comp_no >= sc->n_components - g_virstor_component_watermark-1)
1819			LOG_MSG(LVL_WARNING, "Device %s running out of components "
1820			    "(switching to %u/%u: %s)", sc->geom->name,
1821			    comp_no+1, sc->n_components,
1822			    (*comp)->gcons->provider->name);
1823		/* Take care not to overwrite reserved chunks */
1824		if ( (*comp)->chunk_reserved > 0 &&
1825		    (*comp)->chunk_next < (*comp)->chunk_reserved)
1826			(*comp)->chunk_next = (*comp)->chunk_reserved;
1827
1828		(*comp)->flags |=
1829		    VIRSTOR_PROVIDER_ALLOCATED | VIRSTOR_PROVIDER_CURRENT;
1830		dump_component(*comp);
1831		*comp_no_p = comp_no;
1832		*chunk = (*comp)->chunk_next++;
1833	} else {
1834		*comp_no_p = comp_no;
1835		*chunk = (*comp)->chunk_next++;
1836	}
1837	return (0);
1838}
1839
1840/* Dump a component */
1841static void
1842dump_component(struct g_virstor_component *comp)
1843{
1844
1845	if (g_virstor_debug < LVL_DEBUG2)
1846		return;
1847	printf("Component %d: %s\n", comp->index, comp->gcons->provider->name);
1848	printf("  chunk_count: %u\n", comp->chunk_count);
1849	printf("   chunk_next: %u\n", comp->chunk_next);
1850	printf("        flags: %u\n", comp->flags);
1851}
1852
1853#if 0
1854/* Dump a map entry */
1855static void
1856dump_me(struct virstor_map_entry *me, unsigned int nr)
1857{
1858	if (g_virstor_debug < LVL_DEBUG)
1859		return;
1860	printf("VIRT. CHUNK #%d: ", nr);
1861	if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0)
1862		printf("(unallocated)\n");
1863	else
1864		printf("allocated at provider %u, provider_chunk %u\n",
1865		    me->provider_no, me->provider_chunk);
1866}
1867#endif
1868
1869/*
1870 * Dismantle bio_queue and destroy its components
1871 */
1872static void
1873bioq_dismantle(struct bio_queue_head *bq)
1874{
1875	struct bio *b;
1876
1877	for (b = bioq_first(bq); b != NULL; b = bioq_first(bq)) {
1878		bioq_remove(bq, b);
1879		g_destroy_bio(b);
1880	}
1881}
1882
1883/*
1884 * The function that shouldn't be called.
1885 * When this is called, the stack is already garbled because of
1886 * argument mismatch. There's nothing to do now but panic, which is
1887 * accidentally the whole purpose of this function.
1888 * Motivation: to guard from accidentally calling geom methods when
1889 * they shouldn't be called. (see g_..._taste)
1890 */
1891static void
1892invalid_call(void)
1893{
1894	panic("invalid_call() has just been called. Something's fishy here.");
1895}
1896
1897DECLARE_GEOM_CLASS(g_virstor_class, g_virstor); /* Let there be light */
1898