g_virstor.c revision 172302
190075Sobrien/*-
290075Sobrien * Copyright (c) 2006-2007 Ivan Voras <ivoras@freebsd.org>
3169689Skan * All rights reserved.
490075Sobrien *
590075Sobrien * Redistribution and use in source and binary forms, with or without
690075Sobrien * modification, are permitted provided that the following conditions
790075Sobrien * are met:
890075Sobrien * 1. Redistributions of source code must retain the above copyright
990075Sobrien *    notice, this list of conditions and the following disclaimer.
1090075Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1190075Sobrien *    notice, this list of conditions and the following disclaimer in the
1290075Sobrien *    documentation and/or other materials provided with the distribution.
1390075Sobrien *
1490075Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1590075Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1690075Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1790075Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
1890075Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20169689Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2190075Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2290075Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2390075Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2490075Sobrien * SUCH DAMAGE.
25132718Skan */
26132718Skan
2790075Sobrien/* Implementation notes:
28169689Skan * - "Components" are wrappers around providers that make up the
2990075Sobrien *   virtual storage (i.e. a virstor has "physical" components)
3090075Sobrien */
3196263Sobrien
3296263Sobrien#include <sys/cdefs.h>
3390075Sobrien__FBSDID("$FreeBSD: head/sys/geom/virstor/g_virstor.c 172302 2007-09-23 07:34:23Z pjd $");
3496263Sobrien
35169689Skan#include <sys/param.h>
3690075Sobrien#include <sys/systm.h>
3790075Sobrien#include <sys/kernel.h>
3890075Sobrien#include <sys/module.h>
3990075Sobrien#include <sys/lock.h>
4090075Sobrien#include <sys/mutex.h>
4190075Sobrien#include <sys/sx.h>
4290075Sobrien#include <sys/bio.h>
4390075Sobrien#include <sys/sysctl.h>
4490075Sobrien#include <sys/malloc.h>
4590075Sobrien#include <sys/time.h>
4690075Sobrien#include <sys/proc.h>
4790075Sobrien#include <sys/kthread.h>
4890075Sobrien#include <sys/mutex.h>
4990075Sobrien#include <vm/uma.h>
5090075Sobrien#include <geom/geom.h>
51132718Skan
52132718Skan#include <geom/virstor/g_virstor.h>
53132718Skan#include <geom/virstor/g_virstor_md.h>
54169689Skan
55169689Skan/* Declare malloc(9) label */
56132718Skanstatic MALLOC_DEFINE(M_GVIRSTOR, "gvirstor", "GEOM_VIRSTOR Data");
57132718Skan
5890075Sobrien/* GEOM class methods */
59107590Sobrienstatic g_init_t g_virstor_init;
60107590Sobrienstatic g_fini_t g_virstor_fini;
61107590Sobrienstatic g_taste_t g_virstor_taste;
62107590Sobrienstatic g_ctl_req_t g_virstor_config;
63132718Skanstatic g_ctl_destroy_geom_t g_virstor_destroy_geom;
64107590Sobrien
65107590Sobrien/* Declare & initialize class structure ("geom class") */
66107590Sobrienstruct g_class g_virstor_class = {
67107590Sobrien	.name =		G_VIRSTOR_CLASS_NAME,
68132718Skan	.version =	G_VERSION,
69117395Skan	.init =		g_virstor_init,
70107590Sobrien	.fini =		g_virstor_fini,
71107590Sobrien	.taste =	g_virstor_taste,
72169689Skan	.ctlreq =	g_virstor_config,
73107590Sobrien	.destroy_geom = g_virstor_destroy_geom
74169689Skan	/* The .dumpconf and the rest are only usable for a geom instance, so
75107590Sobrien	 * they will be set when such instance is created. */
76107590Sobrien};
77107590Sobrien
78107590Sobrien/* Declare sysctl's and loader tunables */
79107590SobrienSYSCTL_DECL(_kern_geom);
80107590SobrienSYSCTL_NODE(_kern_geom, OID_AUTO, virstor, CTLFLAG_RW, 0, "GEOM_GVIRSTOR information");
8190075Sobrien
8290075Sobrienstatic u_int g_virstor_debug = 2; /* XXX: lower to 2 when released to public */
8390075SobrienTUNABLE_INT("kern.geom.virstor.debug", &g_virstor_debug);
8490075SobrienSYSCTL_UINT(_kern_geom_virstor, OID_AUTO, debug, CTLFLAG_RW, &g_virstor_debug,
85132718Skan    0, "Debug level (2=production, 5=normal, 15=excessive)");
8690075Sobrien
8790075Sobrienstatic u_int g_virstor_chunk_watermark = 100;
8890075SobrienTUNABLE_INT("kern.geom.virstor.chunk_watermark", &g_virstor_chunk_watermark);
8990075SobrienSYSCTL_UINT(_kern_geom_virstor, OID_AUTO, chunk_watermark, CTLFLAG_RW,
90169689Skan    &g_virstor_chunk_watermark, 0,
9190075Sobrien    "Minimum number of free chunks before issuing administrative warning");
9290075Sobrien
93132718Skanstatic u_int g_virstor_component_watermark = 1;
94107590SobrienTUNABLE_INT("kern.geom.virstor.component_watermark",
9590075Sobrien    &g_virstor_component_watermark);
9690075SobrienSYSCTL_UINT(_kern_geom_virstor, OID_AUTO, component_watermark, CTLFLAG_RW,
9790075Sobrien    &g_virstor_component_watermark, 0,
98169689Skan    "Minimum number of free components before issuing administrative warning");
99107590Sobrien
10090075Sobrienstatic int read_metadata(struct g_consumer *, struct g_virstor_metadata *);
10190075Sobrienstatic int write_metadata(struct g_consumer *, struct g_virstor_metadata *);
10290075Sobrienstatic int clear_metadata(struct g_virstor_component *);
10390075Sobrienstatic int add_provider_to_geom(struct g_virstor_softc *, struct g_provider *,
10490075Sobrien    struct g_virstor_metadata *);
105132718Skanstatic struct g_geom *create_virstor_geom(struct g_class *,
10690075Sobrien    struct g_virstor_metadata *);
107132718Skanstatic void virstor_check_and_run(struct g_virstor_softc *);
108169689Skanstatic u_int virstor_valid_components(struct g_virstor_softc *);
109169689Skanstatic int virstor_geom_destroy(struct g_virstor_softc *, boolean_t,
110169689Skan    boolean_t);
11190075Sobrienstatic void remove_component(struct g_virstor_softc *,
112169689Skan    struct g_virstor_component *, boolean_t);
113169689Skanstatic void bioq_dismantle(struct bio_queue_head *);
114117395Skanstatic int allocate_chunk(struct g_virstor_softc *,
115117395Skan    struct g_virstor_component **, u_int *, u_int *);
116169689Skanstatic void delay_destroy_consumer(void *, int);
117169689Skanstatic void dump_component(struct g_virstor_component *comp);
118169689Skan#if 0
119169689Skanstatic void dump_me(struct virstor_map_entry *me, unsigned int nr);
120117395Skan#endif
121169689Skan
122132718Skanstatic void virstor_ctl_stop(struct gctl_req *, struct g_class *);
12390075Sobrienstatic void virstor_ctl_add(struct gctl_req *, struct g_class *);
12490075Sobrienstatic void virstor_ctl_remove(struct gctl_req *, struct g_class *);
12590075Sobrienstatic struct g_virstor_softc * virstor_find_geom(const struct g_class *,
12690075Sobrien    const char *);
12790075Sobrienstatic void update_metadata(struct g_virstor_softc *);
128169689Skanstatic void fill_metadata(struct g_virstor_softc *, struct g_virstor_metadata *,
129169689Skan    u_int, u_int);
130169689Skan
131169689Skanstatic void g_virstor_orphan(struct g_consumer *);
132169689Skanstatic int g_virstor_access(struct g_provider *, int, int, int);
133169689Skanstatic void g_virstor_start(struct bio *);
134169689Skanstatic void g_virstor_dumpconf(struct sbuf *, const char *, struct g_geom *,
135169689Skan    struct g_consumer *, struct g_provider *);
136169689Skanstatic void g_virstor_done(struct bio *);
137169689Skan
138169689Skanstatic void invalid_call(void);
139169689Skan/*
140169689Skan * Initialise GEOM class (per-class callback)
141169689Skan */
142169689Skanstatic void
143169689Skang_virstor_init(struct g_class *mp __unused)
144169689Skan{
145169689Skan
14690075Sobrien	/* Catch map struct size mismatch at compile time; Map entries must
14790075Sobrien	 * fit into MAXPHYS exactly, with no wasted space. */
148117395Skan	CTASSERT(VIRSTOR_MAP_BLOCK_ENTRIES*VIRSTOR_MAP_ENTRY_SIZE == MAXPHYS);
14990075Sobrien
15090075Sobrien	/* Init UMA zones, TAILQ's, other global vars */
15190075Sobrien}
15290075Sobrien
15390075Sobrien/*
15490075Sobrien * Finalise GEOM class (per-class callback)
155169689Skan */
15690075Sobrienstatic void
15790075Sobrieng_virstor_fini(struct g_class *mp __unused)
158132718Skan{
15990075Sobrien
160169689Skan	/* Deinit UMA zones & global vars */
16190075Sobrien}
16290075Sobrien
16390075Sobrien/*
16490075Sobrien * Config (per-class callback)
16590075Sobrien */
16690075Sobrienstatic void
16790075Sobrieng_virstor_config(struct gctl_req *req, struct g_class *cp, char const *verb)
16890075Sobrien{
16990075Sobrien	uint32_t *version;
170169689Skan
171169689Skan	g_topology_assert();
17290075Sobrien
17390075Sobrien	version = gctl_get_paraml(req, "version", sizeof(*version));
174169689Skan	if (version == NULL) {
17590075Sobrien		gctl_error(req, "Failed to get 'version' argument");
17690075Sobrien		return;
17790075Sobrien	}
178117395Skan	if (*version != G_VIRSTOR_VERSION) {
17990075Sobrien		gctl_error(req, "Userland and kernel versions out of sync");
18090075Sobrien		return;
18190075Sobrien	}
18290075Sobrien
18390075Sobrien	g_topology_unlock();
184169689Skan	if (strcmp(verb, "add") == 0)
18590075Sobrien		virstor_ctl_add(req, cp);
18690075Sobrien	else if (strcmp(verb, "stop") == 0 || strcmp(verb, "destroy") == 0)
18790075Sobrien		virstor_ctl_stop(req, cp);
188169689Skan	else if (strcmp(verb, "remove") == 0)
18990075Sobrien		virstor_ctl_remove(req, cp);
19090075Sobrien	else
19190075Sobrien		gctl_error(req, "unknown verb: '%s'", verb);
19290075Sobrien	g_topology_lock();
193169689Skan}
194169689Skan
195169689Skan/*
196169689Skan * "stop" verb from userland
19790075Sobrien */
19890075Sobrienstatic void
19990075Sobrienvirstor_ctl_stop(struct gctl_req *req, struct g_class *cp)
20090075Sobrien{
20190075Sobrien	int *force, *nargs;
20290075Sobrien	int i;
20390075Sobrien
20490075Sobrien	nargs = gctl_get_paraml(req, "nargs", sizeof *nargs);
205169689Skan	if (nargs == NULL) {
20690075Sobrien		gctl_error(req, "Error fetching argument '%s'", "nargs");
20790075Sobrien		return;
20890075Sobrien	}
209169689Skan	if (*nargs < 1) {
21090075Sobrien		gctl_error(req, "Invalid number of arguments");
21190075Sobrien		return;
21290075Sobrien	}
21390075Sobrien	force = gctl_get_paraml(req, "force", sizeof *force);
21490075Sobrien	if (force == NULL) {
21590075Sobrien		gctl_error(req, "Error fetching argument '%s'", "force");
21690075Sobrien		return;
21790075Sobrien	}
21890075Sobrien
219169689Skan	g_topology_lock();
22090075Sobrien	for (i = 0; i < *nargs; i++) {
221169689Skan		char param[8];
22290075Sobrien		const char *name;
22390075Sobrien		struct g_virstor_softc *sc;
224169689Skan		int error;
225169689Skan
22690075Sobrien		sprintf(param, "arg%d", i);
22790075Sobrien		name = gctl_get_asciiparam(req, param);
22890075Sobrien		sc = virstor_find_geom(cp, name);
22990075Sobrien		LOG_MSG(LVL_INFO, "Stopping %s by the userland command",
23090075Sobrien		    sc->geom->name);
23190075Sobrien		update_metadata(sc);
23290075Sobrien		if ((error = virstor_geom_destroy(sc, TRUE, TRUE)) != 0) {
23390075Sobrien			LOG_MSG(LVL_ERROR, "Cannot destroy %s: %d",
23490075Sobrien			    sc->geom->name, error);
23590075Sobrien		}
23690075Sobrien	}
23790075Sobrien	g_topology_unlock();
23890075Sobrien}
239117395Skan
240117395Skan/*
241117395Skan * "add" verb from userland - add new component(s) to the structure.
242132718Skan * This will be done all at once in here, without going through the
243117395Skan * .taste function for new components.
244117395Skan */
245117395Skanstatic void
246117395Skanvirstor_ctl_add(struct gctl_req *req, struct g_class *cp)
247117395Skan{
248117395Skan	/* Note: while this is going on, I/O is being done on
249169689Skan	 * the g_up and g_down threads. The idea is to make changes
250117395Skan	 * to softc members in a way that can atomically activate
251169689Skan	 * them all at once. */
252117395Skan	struct g_virstor_softc *sc;
253117395Skan	int *hardcode, *nargs;
254117395Skan	const char *geom_name;	/* geom to add a component to */
255117395Skan	struct g_consumer *fcp;
256117395Skan	struct g_virstor_bio_q *bq;
257117395Skan	u_int added;
258117395Skan	int error;
259117395Skan	int i;
260132718Skan
261117395Skan	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
262169689Skan	if (nargs == NULL) {
263117395Skan		gctl_error(req, "Error fetching argument '%s'", "nargs");
264132718Skan		return;
265117395Skan	}
266132718Skan	if (*nargs < 2) {
267117395Skan		gctl_error(req, "Invalid number of arguments");
268132718Skan		return;
269169689Skan	}
270169689Skan	hardcode = gctl_get_paraml(req, "hardcode", sizeof(*hardcode));
271117395Skan	if (hardcode == NULL) {
272117395Skan		gctl_error(req, "Error fetching argument '%s'", "hardcode");
273117395Skan		return;
27490075Sobrien	}
275117395Skan
27690075Sobrien	/* Find "our" geom */
27790075Sobrien	geom_name = gctl_get_asciiparam(req, "arg0");
27890075Sobrien	if (geom_name == NULL) {
279132718Skan		gctl_error(req, "Error fetching argument '%s'", "geom_name (arg0)");
28090075Sobrien		return;
28190075Sobrien	}
282169689Skan	sc = virstor_find_geom(cp, geom_name);
283117395Skan	if (sc == NULL) {
28490075Sobrien		gctl_error(req, "Don't know anything about '%s'", geom_name);
285169689Skan		return;
28690075Sobrien	}
28790075Sobrien
28890075Sobrien	if (virstor_valid_components(sc) != sc->n_components) {
289117395Skan		LOG_MSG(LVL_ERROR, "Cannot add components to incomplete "
290117395Skan		    "virstor %s", sc->geom->name);
29190075Sobrien		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
29290075Sobrien		return;
29390075Sobrien	}
29490075Sobrien
29590075Sobrien	fcp = sc->components[0].gcons;
296169689Skan	added = 0;
29790075Sobrien	g_topology_lock();
29890075Sobrien	for (i = 1; i < *nargs; i++) {
29990075Sobrien		struct g_virstor_metadata md;
30090075Sobrien		char aname[8];
30190075Sobrien		const char *prov_name;
30290075Sobrien		struct g_provider *pp;
30390075Sobrien		struct g_consumer *cp;
30490075Sobrien		u_int nc;
30590075Sobrien		u_int j;
30690075Sobrien
30790075Sobrien		snprintf(aname, sizeof aname, "arg%d", i);
30890075Sobrien		prov_name = gctl_get_asciiparam(req, aname);
30990075Sobrien		if (strncmp(prov_name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
310169689Skan			prov_name += strlen(_PATH_DEV);
311169689Skan
312169689Skan		pp = g_provider_by_name(prov_name);
313169689Skan		if (pp == NULL) {
314169689Skan			/* This is the most common error so be verbose about it */
315169689Skan			if (added != 0) {
316169689Skan				gctl_error(req, "Invalid provider: '%s' (added"
317169689Skan				    " %u components)", prov_name, added);
318169689Skan				update_metadata(sc);
319169689Skan			} else {
32090075Sobrien				gctl_error(req, "Invalid provider: '%s'",
32190075Sobrien				    prov_name);
32290075Sobrien			}
32390075Sobrien			g_topology_unlock();
32490075Sobrien			return;
32590075Sobrien		}
32690075Sobrien		cp = g_new_consumer(sc->geom);
32790075Sobrien		if (cp == NULL) {
32890075Sobrien			gctl_error(req, "Cannot create consumer");
32990075Sobrien			g_topology_unlock();
33090075Sobrien			return;
33190075Sobrien		}
33290075Sobrien		error = g_attach(cp, pp);
33390075Sobrien		if (error != 0) {
33490075Sobrien			gctl_error(req, "Cannot attach a consumer to %s",
33590075Sobrien			    pp->name);
33690075Sobrien			g_destroy_consumer(cp);
33790075Sobrien			g_topology_unlock();
33890075Sobrien			return;
339132718Skan		}
34090075Sobrien		if (fcp->acr != 0 || fcp->acw != 0 || fcp->ace != 0) {
34190075Sobrien			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
34290075Sobrien			if (error != 0) {
34390075Sobrien				gctl_error(req, "Access request failed for %s",
34490075Sobrien				    pp->name);
345117395Skan				g_destroy_consumer(cp);
346169689Skan				g_topology_unlock();
34790075Sobrien				return;
348169689Skan			}
34990075Sobrien		}
35090075Sobrien		if (fcp->provider->sectorsize != pp->sectorsize) {
35190075Sobrien			gctl_error(req, "Sector size doesn't fit for %s",
35290075Sobrien			    pp->name);
35390075Sobrien			g_destroy_consumer(cp);
354117395Skan			g_topology_unlock();
35590075Sobrien			return;
356169689Skan		}
35790075Sobrien		for (j = 0; j < sc->n_components; j++) {
35890075Sobrien			if (strcmp(sc->components[j].gcons->provider->name,
359169689Skan			    pp->name) == 0) {
36090075Sobrien				gctl_error(req, "Component %s already in %s",
36190075Sobrien				    pp->name, sc->geom->name);
362169689Skan				g_destroy_consumer(cp);
36390075Sobrien				g_topology_unlock();
36490075Sobrien				return;
36590075Sobrien			}
366117395Skan		}
367117395Skan		sc->components = realloc(sc->components,
368169689Skan		    sizeof(*sc->components) * (sc->n_components + 1),
369117395Skan		    M_GVIRSTOR, M_WAITOK);
37090075Sobrien
37190075Sobrien		nc = sc->n_components;
37290075Sobrien		sc->components[nc].gcons = cp;
37390075Sobrien		sc->components[nc].sc = sc;
37490075Sobrien		sc->components[nc].index = nc;
37590075Sobrien		sc->components[nc].chunk_count = cp->provider->mediasize /
37690075Sobrien		    sc->chunk_size;
377132718Skan		sc->components[nc].chunk_next = 0;
37890075Sobrien		sc->components[nc].chunk_reserved = 0;
37990075Sobrien
38090075Sobrien		if (sc->components[nc].chunk_count < 4) {
38190075Sobrien			gctl_error(req, "Provider too small: %s",
38290075Sobrien			    cp->provider->name);
38390075Sobrien			g_destroy_consumer(cp);
38490075Sobrien			g_topology_unlock();
38590075Sobrien			return;
38690075Sobrien		}
38790075Sobrien		fill_metadata(sc, &md, nc, *hardcode);
38890075Sobrien		write_metadata(cp, &md);
389132718Skan		/* The new component becomes visible when n_components is
39090075Sobrien		 * incremented */
39190075Sobrien		sc->n_components++;
39290075Sobrien		added++;
39390075Sobrien
394169689Skan	}
39590075Sobrien	/* This call to update_metadata() is critical. In case there's a
39690075Sobrien	 * power failure in the middle of it and some components are updated
39790075Sobrien	 * while others are not, there will be trouble on next .taste() iff
39890075Sobrien	 * a non-updated component is detected first */
39990075Sobrien	update_metadata(sc);
40090075Sobrien	g_topology_unlock();
40190075Sobrien	LOG_MSG(LVL_INFO, "Added %d component(s) to %s", added,
40290075Sobrien	    sc->geom->name);
40390075Sobrien	/* Fire off BIOs previously queued because there wasn't any
40490075Sobrien	 * physical space left. If the BIOs still can't be satisfied
40590075Sobrien	 * they will again be added to the end of the queue (during
40690075Sobrien	 * which the mutex will be recursed) */
40790075Sobrien	bq = malloc(sizeof(*bq), M_GVIRSTOR, M_WAITOK);
40890075Sobrien	bq->bio = NULL;
40990075Sobrien	mtx_lock(&sc->delayed_bio_q_mtx);
41090075Sobrien	/* First, insert a sentinel to the queue end, so we don't
41190075Sobrien	 * end up in an infinite loop if there's still no free
41290075Sobrien	 * space available. */
41390075Sobrien	STAILQ_INSERT_TAIL(&sc->delayed_bio_q, bq, linkage);
41490075Sobrien	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
41590075Sobrien		bq = STAILQ_FIRST(&sc->delayed_bio_q);
416132718Skan		if (bq->bio != NULL) {
41790075Sobrien			g_virstor_start(bq->bio);
418117395Skan			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
41990075Sobrien			free(bq, M_GVIRSTOR);
420117395Skan		} else {
421169689Skan			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
42290075Sobrien			free(bq, M_GVIRSTOR);
423117395Skan			break;
42490075Sobrien		}
425169689Skan	}
42690075Sobrien	mtx_unlock(&sc->delayed_bio_q_mtx);
42790075Sobrien
42890075Sobrien}
42990075Sobrien
43090075Sobrien/*
43190075Sobrien * Find a geom handled by the class
43290075Sobrien */
43390075Sobrienstatic struct g_virstor_softc *
43490075Sobrienvirstor_find_geom(const struct g_class *cp, const char *name)
43590075Sobrien{
43690075Sobrien	struct g_geom *gp;
43790075Sobrien
43890075Sobrien	LIST_FOREACH(gp, &cp->geom, geom) {
43990075Sobrien		if (strcmp(name, gp->name) == 0)
44090075Sobrien			return (gp->softc);
44190075Sobrien	}
44290075Sobrien	return (NULL);
44390075Sobrien}
44490075Sobrien
445117395Skan/*
44690075Sobrien * Update metadata on all components to reflect the current state
44790075Sobrien * of these fields:
448117395Skan *    - chunk_next
449117395Skan *    - flags
45090075Sobrien *    - md_count
45190075Sobrien * Expects things to be set up so write_metadata() can work, i.e.
45290075Sobrien * the topology lock must be held.
453169689Skan */
45490075Sobrienstatic void
45590075Sobrienupdate_metadata(struct g_virstor_softc *sc)
45690075Sobrien{
45790075Sobrien	struct g_virstor_metadata md;
45890075Sobrien	int n;
45990075Sobrien
460169689Skan	if (virstor_valid_components(sc) != sc->n_components)
46190075Sobrien		return; /* Incomplete device */
46290075Sobrien	LOG_MSG(LVL_DEBUG, "Updating metadata on components for %s",
46390075Sobrien	    sc->geom->name);
46490075Sobrien	/* Update metadata on components */
46590075Sobrien	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__,
46690075Sobrien	    sc->geom->class->name, sc->geom->name);
467117395Skan	g_topology_assert();
46890075Sobrien	for (n = 0; n < sc->n_components; n++) {
46990075Sobrien		read_metadata(sc->components[n].gcons, &md);
470117395Skan		md.chunk_next = sc->components[n].chunk_next;
471117395Skan		md.flags = sc->components[n].flags;
47290075Sobrien		md.md_count = sc->n_components;
47390075Sobrien		write_metadata(sc->components[n].gcons, &md);
474117395Skan	}
47590075Sobrien}
47690075Sobrien
47790075Sobrien/*
478169689Skan * Fills metadata (struct md) from information stored in softc and the nc'th
479169689Skan * component of virstor
480169689Skan */
481169689Skanstatic void
482169689Skanfill_metadata(struct g_virstor_softc *sc, struct g_virstor_metadata *md,
483169689Skan    u_int nc, u_int hardcode)
484169689Skan{
485169689Skan	struct g_virstor_component *c;
486169689Skan
487169689Skan	bzero(md, sizeof *md);
488169689Skan	c = &sc->components[nc];
489169689Skan
490169689Skan	strncpy(md->md_magic, G_VIRSTOR_MAGIC, sizeof md->md_magic);
491169689Skan	md->md_version = G_VIRSTOR_VERSION;
492169689Skan	strncpy(md->md_name, sc->geom->name, sizeof md->md_name);
493169689Skan	md->md_id = sc->id;
494169689Skan	md->md_virsize = sc->virsize;
495169689Skan	md->md_chunk_size = sc->chunk_size;
496169689Skan	md->md_count = sc->n_components;
497169689Skan
498169689Skan	if (hardcode) {
499169689Skan		strncpy(md->provider, c->gcons->provider->name,
500169689Skan		    sizeof md->provider);
501169689Skan	}
502169689Skan	md->no = nc;
50390075Sobrien	md->provsize = c->gcons->provider->mediasize;
50490075Sobrien	md->chunk_count = c->chunk_count;
50590075Sobrien	md->chunk_next = c->chunk_next;
50690075Sobrien	md->chunk_reserved = c->chunk_reserved;
507132718Skan	md->flags = c->flags;
50890075Sobrien}
50990075Sobrien
51090075Sobrien/*
51190075Sobrien * Remove a component from virstor device.
51290075Sobrien * Can only be done if the component is unallocated.
51390075Sobrien */
51490075Sobrienstatic void
51590075Sobrienvirstor_ctl_remove(struct gctl_req *req, struct g_class *cp)
51690075Sobrien{
51790075Sobrien	/* As this is executed in parallel to I/O, operations on virstor
51890075Sobrien	 * structures must be as atomic as possible. */
51990075Sobrien	struct g_virstor_softc *sc;
52090075Sobrien	int *nargs;
52190075Sobrien	const char *geom_name;
522132718Skan	u_int removed;
52390075Sobrien	int i;
524169689Skan
525169689Skan	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
52690075Sobrien	if (nargs == NULL) {
52790075Sobrien		gctl_error(req, "Error fetching argument '%s'", "nargs");
52890075Sobrien		return;
52990075Sobrien	}
53090075Sobrien	if (*nargs < 2) {
531169689Skan		gctl_error(req, "Invalid number of arguments");
532169689Skan		return;
53390075Sobrien	}
53490075Sobrien	/* Find "our" geom */
53590075Sobrien	geom_name = gctl_get_asciiparam(req, "arg0");
53690075Sobrien	if (geom_name == NULL) {
53790075Sobrien		gctl_error(req, "Error fetching argument '%s'",
53890075Sobrien		    "geom_name (arg0)");
539132718Skan		return;
54090075Sobrien	}
54190075Sobrien	sc = virstor_find_geom(cp, geom_name);
54290075Sobrien	if (sc == NULL) {
54390075Sobrien		gctl_error(req, "Don't know anything about '%s'", geom_name);
54490075Sobrien		return;
54590075Sobrien	}
54690075Sobrien
54790075Sobrien	if (virstor_valid_components(sc) != sc->n_components) {
54890075Sobrien		LOG_MSG(LVL_ERROR, "Cannot remove components from incomplete "
54990075Sobrien		    "virstor %s", sc->geom->name);
55090075Sobrien		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
55190075Sobrien		return;
55290075Sobrien	}
55390075Sobrien
55490075Sobrien	removed = 0;
555169689Skan	for (i = 1; i < *nargs; i++) {
556169689Skan		char param[8];
55790075Sobrien		const char *prov_name;
55890075Sobrien		int j, found;
55990075Sobrien		struct g_virstor_component *newcomp, *compbak;
560169689Skan
56190075Sobrien		sprintf(param, "arg%d", i);
56290075Sobrien		prov_name = gctl_get_asciiparam(req, param);
563169689Skan		if (strncmp(prov_name, _PATH_DEV, strlen(_PATH_DEV)) == 0)
56490075Sobrien			prov_name += strlen(_PATH_DEV);
565169689Skan
56690075Sobrien		found = -1;
567169689Skan		for (j = 0; j < sc->n_components; j++) {
568169689Skan			if (strcmp(sc->components[j].gcons->provider->name,
569169689Skan			    prov_name) == 0) {
570169689Skan				found = j;
57190075Sobrien				break;
57290075Sobrien			}
57390075Sobrien		}
57490075Sobrien		if (found == -1) {
57590075Sobrien			LOG_MSG(LVL_ERROR, "No %s component in %s",
57690075Sobrien			    prov_name, sc->geom->name);
57790075Sobrien			continue;
57890075Sobrien		}
579132718Skan
58090075Sobrien		compbak = sc->components;
581117395Skan		newcomp = malloc(sc->n_components * sizeof(*sc->components),
58290075Sobrien		    M_GVIRSTOR, M_WAITOK | M_ZERO);
583169689Skan		bcopy(sc->components, newcomp, found * sizeof(*sc->components));
584169689Skan		bcopy(&sc->components[found + 1], newcomp + found,
58590075Sobrien		    found * sizeof(*sc->components));
58690075Sobrien		if ((sc->components[j].flags & VIRSTOR_PROVIDER_ALLOCATED) != 0) {
587169689Skan			LOG_MSG(LVL_ERROR, "Allocated provider %s cannot be "
588169689Skan			    "removed from %s",
589169689Skan			    prov_name, sc->geom->name);
590169689Skan			free(newcomp, M_GVIRSTOR);
591169689Skan			/* We'll consider this non-fatal error */
592169689Skan			continue;
593169689Skan		}
594169689Skan		/* Renumerate unallocated components */
595169689Skan		for (j = 0; j < sc->n_components-1; j++) {
59690075Sobrien			if ((sc->components[j].flags &
59790075Sobrien			    VIRSTOR_PROVIDER_ALLOCATED) == 0) {
59890075Sobrien				sc->components[j].index = j;
59990075Sobrien			}
60090075Sobrien		}
601132718Skan		/* This is the critical section. If a component allocation
60290075Sobrien		 * event happens while both variables are not yet set,
603117395Skan		 * there will be trouble. Something will panic on encountering
60490075Sobrien		 * NULL sc->components[x].gcomp member.
605117395Skan		 * Luckily, component allocation happens very rarely and
606169689Skan		 * removing components is an abnormal action in any case. */
607117395Skan		sc->components = newcomp;
60890075Sobrien		sc->n_components--;
60990075Sobrien		/* End critical section */
61090075Sobrien
61190075Sobrien		g_topology_lock();
61290075Sobrien		if (clear_metadata(&compbak[found]) != 0) {
61390075Sobrien			LOG_MSG(LVL_WARNING, "Trouble ahead: cannot clear "
61490075Sobrien			    "metadata on %s", prov_name);
61590075Sobrien		}
61690075Sobrien		g_detach(compbak[found].gcons);
61790075Sobrien		g_destroy_consumer(compbak[found].gcons);
61890075Sobrien		g_topology_unlock();
61990075Sobrien
62090075Sobrien		free(compbak, M_GVIRSTOR);
62190075Sobrien
622132718Skan		removed++;
62390075Sobrien	}
624169689Skan
62590075Sobrien	/* This call to update_metadata() is critical. In case there's a
62690075Sobrien	 * power failure in the middle of it and some components are updated
62790075Sobrien	 * while others are not, there will be trouble on next .taste() iff
62890075Sobrien	 * a non-updated component is detected first */
62990075Sobrien	g_topology_lock();
63090075Sobrien	update_metadata(sc);
63190075Sobrien	g_topology_unlock();
63290075Sobrien	LOG_MSG(LVL_INFO, "Removed %d component(s) from %s", removed,
63390075Sobrien	    sc->geom->name);
63490075Sobrien}
635169689Skan
636169689Skan/*
63790075Sobrien * Clear metadata sector on component
63890075Sobrien */
63990075Sobrienstatic int
64090075Sobrienclear_metadata(struct g_virstor_component *comp)
64190075Sobrien{
64290075Sobrien	char *buf;
64390075Sobrien	int error;
64490075Sobrien
64590075Sobrien	LOG_MSG(LVL_INFO, "Clearing metadata on %s",
64690075Sobrien	    comp->gcons->provider->name);
64790075Sobrien	g_topology_assert();
648169689Skan	error = g_access(comp->gcons, 0, 1, 0);
649169689Skan	if (error != 0)
65090075Sobrien		return (error);
651169689Skan	buf = malloc(comp->gcons->provider->sectorsize, M_GVIRSTOR,
652169689Skan	    M_WAITOK | M_ZERO);
65390075Sobrien	error = g_write_data(comp->gcons,
654169689Skan	    comp->gcons->provider->mediasize -
65590075Sobrien	    comp->gcons->provider->sectorsize,
656169689Skan	    buf,
65790075Sobrien	    comp->gcons->provider->sectorsize);
65890075Sobrien	free(buf, M_GVIRSTOR);
659169689Skan	g_access(comp->gcons, 0, -1, 0);
660169689Skan	return (error);
661169689Skan}
66290075Sobrien
663169689Skan/*
66490075Sobrien * Destroy geom forcibly.
66590075Sobrien */
66690075Sobrienstatic int
667117395Skang_virstor_destroy_geom(struct gctl_req *req __unused, struct g_class *mp,
66890075Sobrien    struct g_geom *gp)
66990075Sobrien{
67090075Sobrien	struct g_virstor_softc *sc;
67190075Sobrien	int exitval;
67290075Sobrien
673169689Skan	sc = gp->softc;
67490075Sobrien	KASSERT(sc != NULL, ("%s: NULL sc", __func__));
67590075Sobrien
67690075Sobrien	exitval = 0;
677169689Skan	LOG_MSG(LVL_DEBUG, "%s called for %s, sc=%p", __func__, gp->name,
67890075Sobrien	    gp->softc);
67990075Sobrien
68090075Sobrien	if (sc != NULL) {
68190075Sobrien#ifdef INVARIANTS
682169689Skan		char *buf;
683169689Skan		int error;
684169689Skan		off_t off;
68590075Sobrien		int isclean, count;
68690075Sobrien		int n;
68790075Sobrien
68890075Sobrien		LOG_MSG(LVL_INFO, "INVARIANTS detected");
68990075Sobrien		LOG_MSG(LVL_INFO, "Verifying allocation "
69090075Sobrien		    "table for %s", sc->geom->name);
69190075Sobrien		count = 0;
692169689Skan		for (n = 0; n < sc->chunk_count; n++) {
69390075Sobrien			if (sc->map[n].flags || VIRSTOR_MAP_ALLOCATED != 0)
69490075Sobrien				count++;
695169689Skan		}
69690075Sobrien		LOG_MSG(LVL_INFO, "Device %s has %d allocated chunks",
697169689Skan		    sc->geom->name, count);
69890075Sobrien		n = off = count = 0;
69990075Sobrien		isclean = 1;
70090075Sobrien		if (virstor_valid_components(sc) != sc->n_components) {
701169689Skan			/* This is a incomplete virstor device (not all
702169689Skan			 * components have been found) */
70390075Sobrien			LOG_MSG(LVL_ERROR, "Device %s is incomplete",
704169689Skan			    sc->geom->name);
705169689Skan			goto bailout;
70690075Sobrien		}
70790075Sobrien		error = g_access(sc->components[0].gcons, 1, 0, 0);
70890075Sobrien		KASSERT(error == 0, ("%s: g_access failed (%d)", __func__,
70990075Sobrien		    error));
71090075Sobrien		/* Compare the whole on-disk allocation table with what's
711169689Skan		 * currently in memory */
712169689Skan		while (n < sc->chunk_count) {
713169689Skan			buf = g_read_data(sc->components[0].gcons, off,
71490075Sobrien			    sc->sectorsize, &error);
71590075Sobrien			KASSERT(buf != NULL, ("g_read_data returned NULL (%d) "
716169689Skan			    "for read at %jd", error, off));
71790075Sobrien			if (bcmp(buf, &sc->map[n], sc->sectorsize) != 0) {
71890075Sobrien				LOG_MSG(LVL_ERROR, "ERROR in allocation table, "
71990075Sobrien				    "entry %d, offset %jd", n, off);
720169689Skan				isclean = 0;
721169689Skan				count++;
72290075Sobrien			}
72390075Sobrien			n += sc->me_per_sector;
724169689Skan			off += sc->sectorsize;
72590075Sobrien			g_free(buf);
726169689Skan		}
727169689Skan		error = g_access(sc->components[0].gcons, -1, 0, 0);
728169689Skan		KASSERT(error == 0, ("%s: g_access failed (%d) on exit",
729169689Skan		    __func__, error));
73090075Sobrien		if (isclean != 1) {
731169689Skan			LOG_MSG(LVL_ERROR, "ALLOCATION TABLE CORRUPTED FOR %s "
732169689Skan			    "(%d sectors don't match, max %d allocations)",
73390075Sobrien			    sc->geom->name, count,
734169689Skan			    count * sc->me_per_sector);
73590075Sobrien		} else {
736169689Skan			LOG_MSG(LVL_INFO, "Allocation table ok for %s",
737169689Skan			    sc->geom->name);
73890075Sobrien		}
73990075Sobrienbailout:
74090075Sobrien#endif
741169689Skan		update_metadata(sc);
74290075Sobrien		virstor_geom_destroy(sc, FALSE, FALSE);
74390075Sobrien		exitval = EAGAIN;
744169689Skan	} else
745169689Skan		exitval = 0;
746169689Skan	return (exitval);
747169689Skan}
748169689Skan
749169689Skan/*
750169689Skan * Taste event (per-class callback)
751169689Skan * Examines a provider and creates geom instances if needed
752169689Skan */
753169689Skanstatic struct g_geom *
754169689Skang_virstor_taste(struct g_class *mp, struct g_provider *pp, int flags)
75590075Sobrien{
756117395Skan	struct g_virstor_metadata md;
75790075Sobrien	struct g_geom *gp;
75890075Sobrien	struct g_consumer *cp;
75990075Sobrien	struct g_virstor_softc *sc;
76090075Sobrien	int error;
76190075Sobrien
762169689Skan	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
76390075Sobrien	g_topology_assert();
76490075Sobrien	LOG_MSG(LVL_DEBUG, "Tasting %s", pp->name);
76590075Sobrien
766169689Skan	/* We need a dummy geom to attach a consumer to the given provider */
76790075Sobrien	gp = g_new_geomf(mp, "virstor:taste.helper");
76890075Sobrien	gp->start = (void *)invalid_call;	/* XXX: hacked up so the        */
76990075Sobrien	gp->access = (void *)invalid_call;	/* compiler doesn't complain.   */
77090075Sobrien	gp->orphan = (void *)invalid_call;	/* I really want these to fail. */
771169689Skan
772169689Skan	cp = g_new_consumer(gp);
773169689Skan	g_attach(cp, pp);
77490075Sobrien	error = read_metadata(cp, &md);
77590075Sobrien	g_detach(cp);
77690075Sobrien	g_destroy_consumer(cp);
77790075Sobrien	g_destroy_geom(gp);
77890075Sobrien
77990075Sobrien	if (error != 0)
78090075Sobrien		return (NULL);
781169689Skan
782169689Skan	if (strcmp(md.md_magic, G_VIRSTOR_MAGIC) != 0)
78390075Sobrien		return (NULL);
784169689Skan	if (md.md_version != G_VIRSTOR_VERSION) {
78590075Sobrien		LOG_MSG(LVL_ERROR, "Kernel module version invalid "
786169689Skan		    "to handle %s (%s) : %d should be %d",
78790075Sobrien		    md.md_name, pp->name, md.md_version, G_VIRSTOR_VERSION);
78890075Sobrien		return (NULL);
789169689Skan	}
790169689Skan	if (md.provsize != pp->mediasize)
79190075Sobrien		return (NULL);
79290075Sobrien
793169689Skan	/* If the provider name is hardcoded, use the offered provider only
79490075Sobrien	 * if it's been offered with its proper name (the one used in
79590075Sobrien	 * the label command). */
79690075Sobrien	if (md.provider[0] != '\0') {
797169689Skan		if (strcmp(md.provider, pp->name) != 0)
798169689Skan			return (NULL);
79990075Sobrien	}
80090075Sobrien
801169689Skan	/* Iterate all geoms this class already knows about to see if a new
80290075Sobrien	 * geom instance of this class needs to be created (in case the provider
803169689Skan	 * is first from a (possibly) multi-consumer geom) or it just needs
804169689Skan	 * to be added to an existing instance. */
80590075Sobrien	sc = NULL;
80690075Sobrien	gp = NULL;
80790075Sobrien	LIST_FOREACH(gp, &mp->geom, geom) {
80890075Sobrien		sc = gp->softc;
80990075Sobrien		if (sc == NULL)
81090075Sobrien			continue;
81190075Sobrien		if (strcmp(md.md_name, sc->geom->name) != 0)
81290075Sobrien			continue;
813169689Skan		if (md.md_id != sc->id)
81490075Sobrien			continue;
815169689Skan		break;
816169689Skan	}
817169689Skan	if (gp != NULL) { /* We found an existing geom instance; add to it */
818169689Skan		LOG_MSG(LVL_INFO, "Adding %s to %s", pp->name, md.md_name);
819169689Skan		error = add_provider_to_geom(sc, pp, &md);
820169689Skan		if (error != 0) {
821169689Skan			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
82290075Sobrien			    pp->name, md.md_name, error);
823169689Skan			return (NULL);
824169689Skan		}
825169689Skan	} else { /* New geom instance needs to be created */
826169689Skan		gp = create_virstor_geom(mp, &md);
82790075Sobrien		if (gp == NULL) {
828169689Skan			LOG_MSG(LVL_ERROR, "Error creating new instance of "
82990075Sobrien			    "class %s: %s", mp->name, md.md_name);
83090075Sobrien			LOG_MSG(LVL_DEBUG, "Error creating %s at %s",
83190075Sobrien			    md.md_name, pp->name);
83290075Sobrien			return (NULL);
83390075Sobrien		}
83490075Sobrien		sc = gp->softc;
83590075Sobrien		LOG_MSG(LVL_INFO, "Adding %s to %s (first found)", pp->name,
83690075Sobrien		    md.md_name);
83790075Sobrien		error = add_provider_to_geom(sc, pp, &md);
83890075Sobrien		if (error != 0) {
83990075Sobrien			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
84090075Sobrien			    pp->name, md.md_name, error);
84190075Sobrien			virstor_geom_destroy(sc, TRUE, FALSE);
84290075Sobrien			return (NULL);
84390075Sobrien		}
84490075Sobrien	}
84590075Sobrien
84690075Sobrien	return (gp);
84790075Sobrien}
84890075Sobrien
84990075Sobrien/*
85090075Sobrien * Destroyes consumer passed to it in arguments. Used as a callback
85190075Sobrien * on g_event queue.
85290075Sobrien */
85390075Sobrienstatic void
85490075Sobriendelay_destroy_consumer(void *arg, int flags __unused)
85590075Sobrien{
85690075Sobrien	struct g_consumer *c = arg;
85790075Sobrien	KASSERT(c != NULL, ("%s: invalid consumer", __func__));
858117395Skan	LOG_MSG(LVL_DEBUG, "Consumer %s destroyed with delay",
85990075Sobrien	    c->provider->name);
86090075Sobrien	g_detach(c);
86190075Sobrien	g_destroy_consumer(c);
862132718Skan}
86390075Sobrien
86490075Sobrien/*
865169689Skan * Remove a component (consumer) from geom instance; If it's the first
86690075Sobrien * component being removed, orphan the provider to announce geom's being
86790075Sobrien * dismantled
86890075Sobrien */
869169689Skanstatic void
87090075Sobrienremove_component(struct g_virstor_softc *sc, struct g_virstor_component *comp,
87190075Sobrien    boolean_t delay)
87290075Sobrien{
87390075Sobrien	struct g_consumer *c;
87490075Sobrien
87590075Sobrien	KASSERT(comp->gcons != NULL, ("Component with no consumer in %s",
87690075Sobrien	    sc->geom->name));
87790075Sobrien	c = comp->gcons;
87890075Sobrien
87990075Sobrien	comp->gcons = NULL;
88090075Sobrien	KASSERT(c->provider != NULL, ("%s: no provider", __func__));
88190075Sobrien	LOG_MSG(LVL_DEBUG, "Component %s removed from %s", c->provider->name,
882132718Skan	    sc->geom->name);
88390075Sobrien	if (sc->provider != NULL) {
88490075Sobrien		/* Whither, GEOM? */
885169689Skan		sc->provider->flags |= G_PF_WITHER;
88690075Sobrien		g_orphan_provider(sc->provider, ENXIO);
88790075Sobrien		sc->provider = NULL;
88890075Sobrien		LOG_MSG(LVL_INFO, "Removing provider %s", sc->geom->name);
88990075Sobrien	}
89090075Sobrien
89190075Sobrien	if (c->acr > 0 || c->acw > 0 || c->ace > 0)
89290075Sobrien		g_access(c, -c->acr, -c->acw, -c->ace);
89390075Sobrien	if (delay) {
894169689Skan		/* Destroy consumer after it's tasted */
895169689Skan		g_post_event(delay_destroy_consumer, c, M_WAITOK, NULL);
89690075Sobrien	} else {
89790075Sobrien		g_detach(c);
89890075Sobrien		g_destroy_consumer(c);
899169689Skan	}
90090075Sobrien}
90190075Sobrien
90290075Sobrien/*
90390075Sobrien * Destroy geom - called internally
90490075Sobrien * See g_virstor_destroy_geom for the other one
90590075Sobrien */
906169689Skanstatic int
907169689Skanvirstor_geom_destroy(struct g_virstor_softc *sc, boolean_t force,
90890075Sobrien    boolean_t delay)
90990075Sobrien{
91090075Sobrien	struct g_provider *pp;
91190075Sobrien	struct g_geom *gp;
912169689Skan	int n;
913169689Skan
914117395Skan	g_topology_assert();
91590075Sobrien
91690075Sobrien	if (sc == NULL)
91790075Sobrien		return (ENXIO);
91890075Sobrien
91990075Sobrien	pp = sc->provider;
92090075Sobrien	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
92190075Sobrien		LOG_MSG(force ? LVL_WARNING : LVL_ERROR,
92290075Sobrien		    "Device %s is still open.", pp->name);
923132718Skan		if (!force)
92490075Sobrien			return (EBUSY);
92590075Sobrien	}
92690075Sobrien
92790075Sobrien	for (n = 0; n < sc->n_components; n++) {
928117395Skan		if (sc->components[n].gcons != NULL)
929117395Skan			remove_component(sc, &sc->components[n], delay);
930117395Skan	}
931117395Skan
932117395Skan	gp = sc->geom;
933132718Skan	gp->softc = NULL;
934132718Skan
935132718Skan	KASSERT(sc->provider == NULL, ("Provider still exists for %s",
936117395Skan	    gp->name));
937117395Skan
938117395Skan	/* XXX: This might or might not work, since we're called with
939169689Skan	 * the topology lock held. Also, it might panic the kernel if
940117395Skan	 * the error'd BIO is in softupdates code. */
941169689Skan	mtx_lock(&sc->delayed_bio_q_mtx);
942169689Skan	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
943169689Skan		struct g_virstor_bio_q *bq;
944169689Skan		bq = STAILQ_FIRST(&sc->delayed_bio_q);
945169689Skan		bq->bio->bio_error = ENOSPC;
946169689Skan		g_io_deliver(bq->bio, EIO);
947169689Skan		STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
948169689Skan		free(bq, M_GVIRSTOR);
949169689Skan	}
950169689Skan	mtx_unlock(&sc->delayed_bio_q_mtx);
951169689Skan	mtx_destroy(&sc->delayed_bio_q_mtx);
952169689Skan
953169689Skan	free(sc->map, M_GVIRSTOR);
954169689Skan	free(sc->components, M_GVIRSTOR);
955169689Skan	bzero(sc, sizeof *sc);
956169689Skan	free(sc, M_GVIRSTOR);
957169689Skan
958169689Skan	pp = LIST_FIRST(&gp->provider); /* We only offer one provider */
959169689Skan	if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
960169689Skan		LOG_MSG(LVL_DEBUG, "Device %s destroyed", gp->name);
961169689Skan
962169689Skan	g_wither_geom(gp, ENXIO);
963169689Skan
964169689Skan	return (0);
965169689Skan}
966169689Skan
967169689Skan/*
968169689Skan * Utility function: read metadata & decode. Wants topology lock to be
969169689Skan * held.
970169689Skan */
971169689Skanstatic int
972169689Skanread_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
973169689Skan{
974169689Skan	struct g_provider *pp;
975169689Skan	char *buf;
976117395Skan	int error;
977169689Skan
978117395Skan	g_topology_assert();
979117395Skan	error = g_access(cp, 1, 0, 0);
980117395Skan	if (error != 0)
981169689Skan		return (error);
982117395Skan	pp = cp->provider;
983117395Skan	g_topology_unlock();
984169689Skan	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
985169689Skan	    &error);
986169689Skan	g_topology_lock();
987117395Skan	g_access(cp, -1, 0, 0);
988169689Skan	if (buf == NULL)
989169689Skan		return (error);
990169689Skan
991117395Skan	virstor_metadata_decode(buf, md);
992169689Skan	g_free(buf);
993117395Skan
994169689Skan	return (0);
995169689Skan}
996169689Skan
997117395Skan/**
998169689Skan * Utility function: encode & write metadata. Assumes topology lock is
999169689Skan * held.
1000169689Skan */
1001117395Skanstatic int
1002117395Skanwrite_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
1003117395Skan{
1004117395Skan	struct g_provider *pp;
1005117395Skan	char *buf;
1006169689Skan	int error;
1007117395Skan
1008169689Skan	KASSERT(cp != NULL && md != NULL && cp->provider != NULL,
1009169689Skan	    ("Something's fishy in %s", __func__));
1010169689Skan	LOG_MSG(LVL_DEBUG, "Writing metadata on %s", cp->provider->name);
1011117395Skan	g_topology_assert();
1012169689Skan	error = g_access(cp, 0, 1, 0);
1013169689Skan	if (error != 0)
1014169689Skan		return (error);
1015169689Skan	pp = cp->provider;
1016169689Skan
1017169689Skan	buf = malloc(pp->sectorsize, M_GVIRSTOR, M_WAITOK);
1018169689Skan	virstor_metadata_encode(md, buf);
1019169689Skan	g_topology_unlock();
1020169689Skan	error = g_write_data(cp, pp->mediasize - pp->sectorsize, buf,
1021169689Skan	    pp->sectorsize);
1022169689Skan	g_topology_lock();
1023169689Skan	g_access(cp, 0, -1, 0);
1024169689Skan
1025169689Skan	free(buf, M_GVIRSTOR);
1026169689Skan	return (0);
1027169689Skan}
1028169689Skan
1029169689Skan/*
1030169689Skan * Creates a new instance of this GEOM class, initialise softc
1031169689Skan */
1032169689Skanstatic struct g_geom *
1033169689Skancreate_virstor_geom(struct g_class *mp, struct g_virstor_metadata *md)
1034169689Skan{
1035169689Skan	struct g_geom *gp;
1036169689Skan	struct g_virstor_softc *sc;
1037169689Skan
1038169689Skan	LOG_MSG(LVL_DEBUG, "Creating geom instance for %s (id=%u)",
1039169689Skan	    md->md_name, md->md_id);
1040169689Skan
1041169689Skan	if (md->md_count < 1 || md->md_chunk_size < 1 ||
1042169689Skan	    md->md_virsize < md->md_chunk_size) {
1043169689Skan		/* This is bogus configuration, and probably means data is
1044169689Skan		 * somehow corrupted. Panic, maybe? */
1045169689Skan		LOG_MSG(LVL_ERROR, "Nonsensical metadata information for %s",
1046169689Skan		    md->md_name);
1047169689Skan		return (NULL);
1048169689Skan	}
1049169689Skan
1050169689Skan	/* Check if it's already created */
1051169689Skan	LIST_FOREACH(gp, &mp->geom, geom) {
1052169689Skan		sc = gp->softc;
1053169689Skan		if (sc != NULL && strcmp(sc->geom->name, md->md_name) == 0) {
1054169689Skan			LOG_MSG(LVL_WARNING, "Geom %s already exists",
1055169689Skan			    md->md_name);
1056169689Skan			if (sc->id != md->md_id) {
1057169689Skan				LOG_MSG(LVL_ERROR,
1058169689Skan				    "Some stale or invalid components "
1059169689Skan				    "exist for virstor device named %s. "
1060169689Skan				    "You will need to <CLEAR> all stale "
1061169689Skan				    "components and maybe reconfigure "
1062169689Skan				    "the virstor device. Tune "
1063169689Skan				    "kern.geom.virstor.debug sysctl up "
1064169689Skan				    "for more information.",
1065169689Skan				    sc->geom->name);
1066169689Skan			}
1067169689Skan			return (NULL);
1068169689Skan		}
1069169689Skan	}
1070169689Skan	gp = g_new_geomf(mp, "%s", md->md_name);
1071169689Skan	gp->softc = NULL; /* to circumevent races that test softc */
1072169689Skan
1073169689Skan	gp->start = g_virstor_start;
1074169689Skan	gp->spoiled = g_virstor_orphan;
1075169689Skan	gp->orphan = g_virstor_orphan;
1076169689Skan	gp->access = g_virstor_access;
1077169689Skan	gp->dumpconf = g_virstor_dumpconf;
1078169689Skan
1079169689Skan	sc = malloc(sizeof(*sc), M_GVIRSTOR, M_WAITOK | M_ZERO);
1080	sc->id = md->md_id;
1081	sc->n_components = md->md_count;
1082	sc->components = malloc(sizeof(struct g_virstor_component) * md->md_count,
1083	    M_GVIRSTOR, M_WAITOK | M_ZERO);
1084	sc->chunk_size = md->md_chunk_size;
1085	sc->virsize = md->md_virsize;
1086	STAILQ_INIT(&sc->delayed_bio_q);
1087	mtx_init(&sc->delayed_bio_q_mtx, "gvirstor_delayed_bio_q_mtx",
1088	    "gvirstor", MTX_DEF | MTX_RECURSE);
1089
1090	sc->geom = gp;
1091	sc->provider = NULL; /* virstor_check_and_run will create it */
1092	gp->softc = sc;
1093
1094	LOG_MSG(LVL_ANNOUNCE, "Device %s created", sc->geom->name);
1095
1096	return (gp);
1097}
1098
1099/*
1100 * Add provider to a GEOM class instance
1101 */
1102static int
1103add_provider_to_geom(struct g_virstor_softc *sc, struct g_provider *pp,
1104    struct g_virstor_metadata *md)
1105{
1106	struct g_virstor_component *component;
1107	struct g_consumer *cp, *fcp;
1108	struct g_geom *gp;
1109	int error;
1110
1111	if (md->no >= sc->n_components)
1112		return (EINVAL);
1113
1114	/* "Current" compontent */
1115	component = &(sc->components[md->no]);
1116	if (component->gcons != NULL)
1117		return (EEXIST);
1118
1119	gp = sc->geom;
1120	fcp = LIST_FIRST(&gp->consumer);
1121
1122	cp = g_new_consumer(gp);
1123	error = g_attach(cp, pp);
1124
1125	if (error != 0) {
1126		g_destroy_consumer(cp);
1127		return (error);
1128	}
1129
1130	if (fcp != NULL) {
1131		if (fcp->provider->sectorsize != pp->sectorsize) {
1132			/* TODO: this can be made to work */
1133			LOG_MSG(LVL_ERROR, "Provider %s of %s has invalid "
1134			    "sector size (%d)", pp->name, sc->geom->name,
1135			    pp->sectorsize);
1136			return (EINVAL);
1137		}
1138		if (fcp->acr > 0 || fcp->acw || fcp->ace > 0) {
1139			/* Replicate access permissions from first "live" consumer
1140			 * to the new one */
1141			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
1142			if (error != 0) {
1143				g_detach(cp);
1144				g_destroy_consumer(cp);
1145				return (error);
1146			}
1147		}
1148	}
1149
1150	/* Bring up a new component */
1151	cp->private = component;
1152	component->gcons = cp;
1153	component->sc = sc;
1154	component->index = md->no;
1155	component->chunk_count = md->chunk_count;
1156	component->chunk_next = md->chunk_next;
1157	component->chunk_reserved = md->chunk_reserved;
1158	component->flags = md->flags;
1159
1160	LOG_MSG(LVL_DEBUG, "%s attached to %s", pp->name, sc->geom->name);
1161
1162	virstor_check_and_run(sc);
1163	return (0);
1164}
1165
1166/*
1167 * Check if everything's ready to create the geom provider & device entry,
1168 * create and start provider.
1169 * Called ultimately by .taste, from g_event thread
1170 */
1171static void
1172virstor_check_and_run(struct g_virstor_softc *sc)
1173{
1174	off_t off;
1175	size_t n, count;
1176	int index;
1177	int error;
1178
1179	if (virstor_valid_components(sc) != sc->n_components)
1180		return;
1181
1182	if (virstor_valid_components(sc) == 0) {
1183		/* This is actually a candidate for panic() */
1184		LOG_MSG(LVL_ERROR, "No valid components for %s?",
1185		    sc->provider->name);
1186		return;
1187	}
1188
1189	sc->sectorsize = sc->components[0].gcons->provider->sectorsize;
1190
1191	/* Initialise allocation map from the first consumer */
1192	sc->chunk_count = sc->virsize / sc->chunk_size;
1193	if (sc->chunk_count * (off_t)sc->chunk_size != sc->virsize) {
1194		LOG_MSG(LVL_WARNING, "Device %s truncated to %ju bytes",
1195		    sc->provider->name,
1196		    sc->chunk_count * (off_t)sc->chunk_size);
1197	}
1198	sc->map_size = sc->chunk_count * sizeof *(sc->map);
1199	/* The following allocation is in order of 4MB - 8MB */
1200	sc->map = malloc(sc->map_size, M_GVIRSTOR, M_WAITOK);
1201	KASSERT(sc->map != NULL, ("%s: Memory allocation error (%zu bytes) for %s",
1202	    __func__, sc->map_size, sc->provider->name));
1203	sc->map_sectors = sc->map_size / sc->sectorsize;
1204
1205	count = 0;
1206	for (n = 0; n < sc->n_components; n++)
1207		count += sc->components[n].chunk_count;
1208	LOG_MSG(LVL_INFO, "Device %s has %zu physical chunks and %zu virtual "
1209	    "(%zu KB chunks)",
1210	    sc->geom->name, count, sc->chunk_count, sc->chunk_size / 1024);
1211
1212	error = g_access(sc->components[0].gcons, 1, 0, 0);
1213	if (error != 0) {
1214		LOG_MSG(LVL_ERROR, "Cannot acquire read access for %s to "
1215		    "read allocation map for %s",
1216		    sc->components[0].gcons->provider->name,
1217		    sc->geom->name);
1218		return;
1219	}
1220	/* Read in the allocation map */
1221	LOG_MSG(LVL_DEBUG, "Reading map for %s from %s", sc->geom->name,
1222	    sc->components[0].gcons->provider->name);
1223	off = count = n = 0;
1224	while (count < sc->map_size) {
1225		struct g_virstor_map_entry *mapbuf;
1226		size_t bs;
1227
1228		bs = MIN(MAXPHYS, sc->map_size - count);
1229		if (bs % sc->sectorsize != 0) {
1230			/* Check for alignment errors */
1231			bs = (bs / sc->sectorsize) * sc->sectorsize;
1232			if (bs == 0)
1233				break;
1234			LOG_MSG(LVL_ERROR, "Trouble: map is not sector-aligned "
1235			    "for %s on %s", sc->geom->name,
1236			    sc->components[0].gcons->provider->name);
1237		}
1238		mapbuf = g_read_data(sc->components[0].gcons, off, bs, &error);
1239		if (mapbuf == NULL) {
1240			free(sc->map, M_GVIRSTOR);
1241			LOG_MSG(LVL_ERROR, "Error reading allocation map "
1242			    "for %s from %s (offset %ju) (error %d)",
1243			    sc->geom->name,
1244			    sc->components[0].gcons->provider->name,
1245			    off, error);
1246			return;
1247		}
1248
1249		bcopy(mapbuf, &sc->map[n], bs);
1250		off += bs;
1251		count += bs;
1252		n += bs / sizeof *(sc->map);
1253		g_free(mapbuf);
1254	}
1255	g_access(sc->components[0].gcons, -1, 0, 0);
1256	LOG_MSG(LVL_DEBUG, "Read map for %s", sc->geom->name);
1257
1258	/* find first component with allocatable chunks */
1259	index = -1;
1260	for (n = 0; n < sc->n_components; n++) {
1261		if (sc->components[n].chunk_next <
1262		    sc->components[n].chunk_count) {
1263			index = n;
1264			break;
1265		}
1266	}
1267	if (index == -1)
1268		/* not found? set it to the last component and handle it
1269		 * later */
1270		index = sc->n_components - 1;
1271
1272	if (index >= sc->n_components - g_virstor_component_watermark - 1) {
1273		LOG_MSG(LVL_WARNING, "Device %s running out of components "
1274		    "(%d/%u: %s)", sc->geom->name,
1275		    index+1,
1276		    sc->n_components,
1277		    sc->components[index].gcons->provider->name);
1278	}
1279	sc->curr_component = index;
1280
1281	if (sc->components[index].chunk_next >=
1282	    sc->components[index].chunk_count - g_virstor_chunk_watermark) {
1283		LOG_MSG(LVL_WARNING,
1284		    "Component %s of %s is running out of free space "
1285		    "(%u chunks left)",
1286		    sc->components[index].gcons->provider->name,
1287		    sc->geom->name, sc->components[index].chunk_count -
1288		    sc->components[index].chunk_next);
1289	}
1290
1291	sc->me_per_sector = sc->sectorsize / sizeof *(sc->map);
1292	if (sc->sectorsize % sizeof *(sc->map) != 0) {
1293		LOG_MSG(LVL_ERROR,
1294		    "%s: Map entries don't fit exactly in a sector (%s)",
1295		    __func__, sc->geom->name);
1296		return;
1297	}
1298
1299	/* Recalculate allocated chunks in components & at the same time
1300	 * verify map data is sane. We could trust metadata on this, but
1301	 * we want to make sure. */
1302	for (n = 0; n < sc->n_components; n++)
1303		sc->components[n].chunk_next = sc->components[n].chunk_reserved;
1304
1305	for (n = 0; n < sc->chunk_count; n++) {
1306		if (sc->map[n].provider_no >= sc->n_components ||
1307			sc->map[n].provider_chunk >=
1308			sc->components[sc->map[n].provider_no].chunk_count) {
1309			LOG_MSG(LVL_ERROR, "%s: Invalid entry %u in map for %s",
1310			    __func__, (u_int)n, sc->geom->name);
1311			LOG_MSG(LVL_ERROR, "%s: provider_no: %u, n_components: %u"
1312			    " provider_chunk: %u, chunk_count: %u", __func__,
1313			    sc->map[n].provider_no, sc->n_components,
1314			    sc->map[n].provider_chunk,
1315			    sc->components[sc->map[n].provider_no].chunk_count);
1316			return;
1317		}
1318		if (sc->map[n].flags & VIRSTOR_MAP_ALLOCATED)
1319			sc->components[sc->map[n].provider_no].chunk_next++;
1320	}
1321
1322	sc->provider = g_new_providerf(sc->geom, "virstor/%s",
1323	    sc->geom->name);
1324
1325	sc->provider->sectorsize = sc->sectorsize;
1326	sc->provider->mediasize = sc->virsize;
1327	g_error_provider(sc->provider, 0);
1328
1329	LOG_MSG(LVL_INFO, "%s activated", sc->provider->name);
1330	LOG_MSG(LVL_DEBUG, "%s starting with current component %u, starting "
1331	    "chunk %u", sc->provider->name, sc->curr_component,
1332	    sc->components[sc->curr_component].chunk_next);
1333}
1334
1335/*
1336 * Returns count of active providers in this geom instance
1337 */
1338static u_int
1339virstor_valid_components(struct g_virstor_softc *sc)
1340{
1341	unsigned int nc, i;
1342
1343	nc = 0;
1344	KASSERT(sc != NULL, ("%s: softc is NULL", __func__));
1345	KASSERT(sc->components != NULL, ("%s: sc->components is NULL", __func__));
1346	for (i = 0; i < sc->n_components; i++)
1347		if (sc->components[i].gcons != NULL)
1348			nc++;
1349	return (nc);
1350}
1351
1352/*
1353 * Called when the consumer gets orphaned (?)
1354 */
1355static void
1356g_virstor_orphan(struct g_consumer *cp)
1357{
1358	struct g_virstor_softc *sc;
1359	struct g_virstor_component *comp;
1360	struct g_geom *gp;
1361
1362	g_topology_assert();
1363	gp = cp->geom;
1364	sc = gp->softc;
1365	if (sc == NULL)
1366		return;
1367
1368	comp = cp->private;
1369	KASSERT(comp != NULL, ("%s: No component in private part of consumer",
1370	    __func__));
1371	remove_component(sc, comp, FALSE);
1372	if (virstor_valid_components(sc) == 0)
1373		virstor_geom_destroy(sc, TRUE, FALSE);
1374}
1375
1376/*
1377 * Called to notify geom when it's been opened, and for what intent
1378 */
1379static int
1380g_virstor_access(struct g_provider *pp, int dr, int dw, int de)
1381{
1382	struct g_consumer *c;
1383	struct g_virstor_softc *sc;
1384	struct g_geom *gp;
1385	int error;
1386
1387	KASSERT(pp != NULL, ("%s: NULL provider", __func__));
1388	gp = pp->geom;
1389	KASSERT(gp != NULL, ("%s: NULL geom", __func__));
1390	sc = gp->softc;
1391
1392	if (sc == NULL) {
1393		/* It seems that .access can be called with negative dr,dw,dx
1394		 * in this case but I want to check for myself */
1395		LOG_MSG(LVL_WARNING, "access(%d, %d, %d) for %s",
1396		    dr, dw, de, pp->name);
1397		/* This should only happen when geom is withered so
1398		 * allow only negative requests */
1399		KASSERT(dr <= 0 && dw <= 0 && de <= 0,
1400		    ("%s: Positive access for %s", __func__, pp->name));
1401		if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0)
1402			LOG_MSG(LVL_DEBUG, "Device %s definitely destroyed",
1403			    pp->name);
1404		return (0);
1405	}
1406
1407	/* Grab an exclusive bit to propagate on our consumers on first open */
1408	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0)
1409		de++;
1410	/* ... drop it on close */
1411	if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0) {
1412		de--;
1413		update_metadata(sc);	/* Writes statistical information */
1414	}
1415
1416	error = ENXIO;
1417	LIST_FOREACH(c, &gp->consumer, consumer) {
1418		KASSERT(c != NULL, ("%s: consumer is NULL", __func__));
1419		error = g_access(c, dr, dw, de);
1420		if (error != 0) {
1421			struct g_consumer *c2;
1422
1423			/* Backout earlier changes */
1424			LIST_FOREACH(c2, &gp->consumer, consumer) {
1425				if (c2 == c) /* all eariler components fixed */
1426					return (error);
1427				g_access(c2, -dr, -dw, -de);
1428			}
1429		}
1430	}
1431
1432	return (error);
1433}
1434
1435/*
1436 * Generate XML dump of current state
1437 */
1438static void
1439g_virstor_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1440    struct g_consumer *cp, struct g_provider *pp)
1441{
1442	struct g_virstor_softc *sc;
1443
1444	g_topology_assert();
1445	sc = gp->softc;
1446
1447	if (sc == NULL || pp != NULL)
1448		return;
1449
1450	if (cp != NULL) {
1451		/* For each component */
1452		struct g_virstor_component *comp;
1453
1454		comp = cp->private;
1455		if (comp == NULL)
1456			return;
1457		sbuf_printf(sb, "%s<ComponentIndex>%u</ComponentIndex>\n",
1458		    indent, comp->index);
1459		sbuf_printf(sb, "%s<ChunkCount>%u</ChunkCount>\n",
1460		    indent, comp->chunk_count);
1461		sbuf_printf(sb, "%s<ChunksUsed>%u</ChunksUsed>\n",
1462		    indent, comp->chunk_next);
1463		sbuf_printf(sb, "%s<ChunksReserved>%u</ChunksReserved>\n",
1464		    indent, comp->chunk_reserved);
1465		sbuf_printf(sb, "%s<StorageFree>%u%%</StorageFree>\n",
1466		    indent,
1467		    comp->chunk_next > 0 ? 100 -
1468		    ((comp->chunk_next + comp->chunk_reserved) * 100) /
1469		    comp->chunk_count : 100);
1470	} else {
1471		/* For the whole thing */
1472		u_int count, used, i;
1473		off_t size;
1474
1475		count = used = size = 0;
1476		for (i = 0; i < sc->n_components; i++) {
1477			if (sc->components[i].gcons != NULL) {
1478				count += sc->components[i].chunk_count;
1479				used += sc->components[i].chunk_next +
1480				    sc->components[i].chunk_reserved;
1481				size += sc->components[i].gcons->
1482				    provider->mediasize;
1483			}
1484		}
1485
1486		sbuf_printf(sb, "%s<Status>"
1487		    "Components=%u, Online=%u</Status>\n", indent,
1488		    sc->n_components, virstor_valid_components(sc));
1489		sbuf_printf(sb, "%s<State>%u%% physical free</State>\n",
1490		    indent, 100-(used * 100) / count);
1491		sbuf_printf(sb, "%s<ChunkSize>%zu</ChunkSize>\n", indent,
1492		    sc->chunk_size);
1493		sbuf_printf(sb, "%s<PhysicalFree>%u%%</PhysicalFree>\n",
1494		    indent, used > 0 ? 100 - (used * 100) / count : 100);
1495		sbuf_printf(sb, "%s<ChunkPhysicalCount>%u</ChunkPhysicalCount>\n",
1496		    indent, count);
1497		sbuf_printf(sb, "%s<ChunkVirtualCount>%zu</ChunkVirtualCount>\n",
1498		    indent, sc->chunk_count);
1499		sbuf_printf(sb, "%s<PhysicalBacking>%zu%%</PhysicalBacking>\n",
1500		    indent,
1501		    (count * 100) / sc->chunk_count);
1502		sbuf_printf(sb, "%s<PhysicalBackingSize>%jd</PhysicalBackingSize>\n",
1503		    indent, size);
1504		sbuf_printf(sb, "%s<VirtualSize>%jd</VirtualSize>\n", indent,
1505		    sc->virsize);
1506	}
1507}
1508
1509/*
1510 * GEOM .done handler
1511 * Can't use standard handler because one requested IO may
1512 * fork into additional data IOs
1513 */
1514static void
1515g_virstor_done(struct bio *b)
1516{
1517	struct g_virstor_softc *sc;
1518	struct bio *parent_b;
1519
1520	parent_b = b->bio_parent;
1521	sc = parent_b->bio_to->geom->softc;
1522
1523	if (b->bio_error != 0) {
1524		LOG_MSG(LVL_ERROR, "Error %d for offset=%ju, length=%ju, %s",
1525		    b->bio_error, b->bio_offset, b->bio_length,
1526		    b->bio_to->name);
1527		if (parent_b->bio_error == 0)
1528			parent_b->bio_error = b->bio_error;
1529	}
1530
1531	parent_b->bio_inbed++;
1532	parent_b->bio_completed += b->bio_completed;
1533
1534	if (parent_b->bio_children == parent_b->bio_inbed) {
1535		parent_b->bio_completed = parent_b->bio_length;
1536		g_io_deliver(parent_b, parent_b->bio_error);
1537	}
1538	g_destroy_bio(b);
1539}
1540
1541/*
1542 * I/O starts here
1543 * Called in g_down thread
1544 */
1545static void
1546g_virstor_start(struct bio *b)
1547{
1548	struct g_virstor_softc *sc;
1549	struct g_virstor_component *comp;
1550	struct bio *cb;
1551	struct g_provider *pp;
1552	char *addr;
1553	off_t offset, length;
1554	struct bio_queue_head bq;
1555	size_t chunk_size;	/* cached for convenience */
1556	u_int count;
1557
1558	pp = b->bio_to;
1559	sc = pp->geom->softc;
1560	KASSERT(sc != NULL, ("%s: no softc (error=%d, device=%s)", __func__,
1561	    b->bio_to->error, b->bio_to->name));
1562
1563	LOG_REQ(LVL_MOREDEBUG, b, "%s", __func__);
1564
1565	switch (b->bio_cmd) {
1566	case BIO_READ:
1567	case BIO_WRITE:
1568	case BIO_DELETE:
1569		break;
1570	default:
1571		g_io_deliver(b, EOPNOTSUPP);
1572		return;
1573	}
1574
1575	LOG_MSG(LVL_DEBUG2, "BIO arrived, size=%ju", b->bio_length);
1576	bioq_init(&bq);
1577
1578	chunk_size = sc->chunk_size;
1579	addr = b->bio_data;
1580	offset = b->bio_offset;	/* virtual offset and length */
1581	length = b->bio_length;
1582
1583	while (length > 0) {
1584		size_t chunk_index, in_chunk_offset, in_chunk_length;
1585		struct virstor_map_entry *me;
1586
1587		chunk_index = offset / chunk_size; /* round downwards */
1588		in_chunk_offset = offset % chunk_size;
1589		in_chunk_length = min(length, chunk_size - in_chunk_offset);
1590		LOG_MSG(LVL_DEBUG, "Mapped %s(%ju, %ju) to (%zu,%zu,%zu)",
1591		    b->bio_cmd == BIO_READ ? "R" : "W",
1592		    offset, length,
1593		    chunk_index, in_chunk_offset, in_chunk_length);
1594		me = &sc->map[chunk_index];
1595
1596		if (b->bio_cmd == BIO_READ || b->bio_cmd == BIO_DELETE) {
1597			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1598				/* Reads from unallocated chunks return zeroed
1599				 * buffers */
1600				if (b->bio_cmd == BIO_READ)
1601					bzero(addr, in_chunk_length);
1602			} else {
1603				comp = &sc->components[me->provider_no];
1604
1605				cb = g_clone_bio(b);
1606				if (cb == NULL) {
1607					bioq_dismantle(&bq);
1608					if (b->bio_error == 0)
1609						b->bio_error = ENOMEM;
1610					g_io_deliver(b, b->bio_error);
1611					return;
1612				}
1613				cb->bio_to = comp->gcons->provider;
1614				cb->bio_done = g_virstor_done;
1615				cb->bio_offset =
1616				    (off_t)me->provider_chunk * (off_t)chunk_size
1617				    + in_chunk_offset;
1618				cb->bio_length = in_chunk_length;
1619				cb->bio_data = addr;
1620				cb->bio_caller1 = comp;
1621				bioq_disksort(&bq, cb);
1622			}
1623		} else { /* handle BIO_WRITE */
1624			KASSERT(b->bio_cmd == BIO_WRITE,
1625			    ("%s: Unknown command %d", __func__,
1626			    b->bio_cmd));
1627
1628			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1629				/* We have a virtual chunk, represented by
1630				 * the "me" entry, but it's not yet allocated
1631				 * (tied to) a physical chunk. So do it now. */
1632				struct virstor_map_entry *data_me;
1633				u_int phys_chunk, comp_no;
1634				off_t s_offset;
1635				int error;
1636
1637				error = allocate_chunk(sc, &comp, &comp_no,
1638				    &phys_chunk);
1639				if (error != 0) {
1640					/* We cannot allocate a physical chunk
1641					 * to satisfy this request, so we'll
1642					 * delay it to when we can...
1643					 * XXX: this will prevent the fs from
1644					 * being umounted! */
1645					struct g_virstor_bio_q *biq;
1646					biq = malloc(sizeof *biq, M_GVIRSTOR,
1647					    M_NOWAIT);
1648					if (biq == NULL) {
1649						bioq_dismantle(&bq);
1650						if (b->bio_error == 0)
1651							b->bio_error = ENOMEM;
1652						g_io_deliver(b, b->bio_error);
1653						return;
1654					}
1655					biq->bio = b;
1656					mtx_lock(&sc->delayed_bio_q_mtx);
1657					STAILQ_INSERT_TAIL(&sc->delayed_bio_q,
1658					    biq, linkage);
1659					mtx_unlock(&sc->delayed_bio_q_mtx);
1660					LOG_MSG(LVL_WARNING, "Delaying BIO "
1661					    "(size=%ju) until free physical "
1662					    "space can be found on %s",
1663					    b->bio_length,
1664					    sc->provider->name);
1665					return;
1666				}
1667				LOG_MSG(LVL_DEBUG, "Allocated chunk %u on %s "
1668				    "for %s",
1669				    phys_chunk,
1670				    comp->gcons->provider->name,
1671				    sc->provider->name);
1672
1673				me->provider_no = comp_no;
1674				me->provider_chunk = phys_chunk;
1675				me->flags |= VIRSTOR_MAP_ALLOCATED;
1676
1677				cb = g_clone_bio(b);
1678				if (cb == NULL) {
1679					me->flags &= ~VIRSTOR_MAP_ALLOCATED;
1680					me->provider_no = 0;
1681					me->provider_chunk = 0;
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
1689				/* The allocation table is stored continuously
1690				 * at the start of the drive. We need to
1691				 * calculate the offset of the sector that holds
1692				 * this map entry both on the drive and in the
1693				 * map array.
1694				 * sc_offset will end up pointing to the drive
1695				 * sector. */
1696				s_offset = chunk_index * sizeof *me;
1697				s_offset = (s_offset / sc->sectorsize) *
1698				    sc->sectorsize;
1699
1700				/* data_me points to map entry sector
1701				 * in memory (analoguos to offset) */
1702				data_me = &sc->map[(chunk_index /
1703				    sc->me_per_sector) * sc->me_per_sector];
1704
1705				/* Commit sector with map entry to storage */
1706				cb->bio_to = sc->components[0].gcons->provider;
1707				cb->bio_done = g_virstor_done;
1708				cb->bio_offset = s_offset;
1709				cb->bio_data = (char *)data_me;
1710				cb->bio_length = sc->sectorsize;
1711				cb->bio_caller1 = &sc->components[0];
1712				bioq_disksort(&bq, cb);
1713			}
1714
1715			comp = &sc->components[me->provider_no];
1716			cb = g_clone_bio(b);
1717			if (cb == NULL) {
1718				bioq_dismantle(&bq);
1719				if (b->bio_error == 0)
1720					b->bio_error = ENOMEM;
1721				g_io_deliver(b, b->bio_error);
1722				return;
1723			}
1724			/* Finally, handle the data */
1725			cb->bio_to = comp->gcons->provider;
1726			cb->bio_done = g_virstor_done;
1727			cb->bio_offset = (off_t)me->provider_chunk*(off_t)chunk_size +
1728			    in_chunk_offset;
1729			cb->bio_length = in_chunk_length;
1730			cb->bio_data = addr;
1731			cb->bio_caller1 = comp;
1732			bioq_disksort(&bq, cb);
1733		}
1734		addr += in_chunk_length;
1735		length -= in_chunk_length;
1736		offset += in_chunk_length;
1737	}
1738
1739	/* Fire off bio's here */
1740	count = 0;
1741	for (cb = bioq_first(&bq); cb != NULL; cb = bioq_first(&bq)) {
1742		bioq_remove(&bq, cb);
1743		LOG_REQ(LVL_MOREDEBUG, cb, "Firing request");
1744		comp = cb->bio_caller1;
1745		cb->bio_caller1 = NULL;
1746		LOG_MSG(LVL_DEBUG, " firing bio, offset=%ju, length=%ju",
1747		    cb->bio_offset, cb->bio_length);
1748		g_io_request(cb, comp->gcons);
1749		count++;
1750	}
1751	if (count == 0) { /* We handled everything locally */
1752		b->bio_completed = b->bio_length;
1753		g_io_deliver(b, 0);
1754	}
1755
1756}
1757
1758/*
1759 * Allocate a chunk from a physical provider. Returns physical component,
1760 * chunk index relative to the component and the component's index.
1761 */
1762static int
1763allocate_chunk(struct g_virstor_softc *sc, struct g_virstor_component **comp,
1764    u_int *comp_no_p, u_int *chunk)
1765{
1766	u_int comp_no;
1767
1768	KASSERT(sc->curr_component < sc->n_components,
1769	    ("%s: Invalid curr_component: %u",  __func__, sc->curr_component));
1770
1771	comp_no = sc->curr_component;
1772	*comp = &sc->components[comp_no];
1773	dump_component(*comp);
1774	if ((*comp)->chunk_next >= (*comp)->chunk_count) {
1775		/* This component is full. Allocate next component */
1776		if (comp_no >= sc->n_components-1) {
1777			LOG_MSG(LVL_ERROR, "All physical space allocated for %s",
1778			    sc->geom->name);
1779			return (-1);
1780		}
1781		(*comp)->flags &= ~VIRSTOR_PROVIDER_CURRENT;
1782		sc->curr_component = ++comp_no;
1783
1784		*comp = &sc->components[comp_no];
1785		if (comp_no >= sc->n_components - g_virstor_component_watermark-1)
1786			LOG_MSG(LVL_WARNING, "Device %s running out of components "
1787			    "(switching to %u/%u: %s)", sc->geom->name,
1788			    comp_no+1, sc->n_components,
1789			    (*comp)->gcons->provider->name);
1790		/* Take care not to overwrite reserved chunks */
1791		if ( (*comp)->chunk_reserved > 0 &&
1792		    (*comp)->chunk_next < (*comp)->chunk_reserved)
1793			(*comp)->chunk_next = (*comp)->chunk_reserved;
1794
1795		(*comp)->flags |=
1796		    VIRSTOR_PROVIDER_ALLOCATED | VIRSTOR_PROVIDER_CURRENT;
1797		dump_component(*comp);
1798		*comp_no_p = comp_no;
1799		*chunk = (*comp)->chunk_next++;
1800	} else {
1801		*comp_no_p = comp_no;
1802		*chunk = (*comp)->chunk_next++;
1803	}
1804	return (0);
1805}
1806
1807/* Dump a component */
1808static void
1809dump_component(struct g_virstor_component *comp)
1810{
1811
1812	if (g_virstor_debug < LVL_DEBUG2)
1813		return;
1814	printf("Component %d: %s\n", comp->index, comp->gcons->provider->name);
1815	printf("  chunk_count: %u\n", comp->chunk_count);
1816	printf("   chunk_next: %u\n", comp->chunk_next);
1817	printf("        flags: %u\n", comp->flags);
1818}
1819
1820#if 0
1821/* Dump a map entry */
1822static void
1823dump_me(struct virstor_map_entry *me, unsigned int nr)
1824{
1825	if (g_virstor_debug < LVL_DEBUG)
1826		return;
1827	printf("VIRT. CHUNK #%d: ", nr);
1828	if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0)
1829		printf("(unallocated)\n");
1830	else
1831		printf("allocated at provider %u, provider_chunk %u\n",
1832		    me->provider_no, me->provider_chunk);
1833}
1834#endif
1835
1836/*
1837 * Dismantle bio_queue and destroy its components
1838 */
1839static void
1840bioq_dismantle(struct bio_queue_head *bq)
1841{
1842	struct bio *b;
1843
1844	for (b = bioq_first(bq); b != NULL; b = bioq_first(bq)) {
1845		bioq_remove(bq, b);
1846		g_destroy_bio(b);
1847	}
1848}
1849
1850/*
1851 * The function that shouldn't be called.
1852 * When this is called, the stack is already garbled because of
1853 * argument mismatch. There's nothing to do now but panic, which is
1854 * accidentally the whole purpose of this function.
1855 * Motivation: to guard from accidentally calling geom methods when
1856 * they shouldn't be called. (see g_..._taste)
1857 */
1858static void
1859invalid_call(void)
1860{
1861	panic("invalid_call() has just been called. Something's fishy here.");
1862}
1863
1864DECLARE_GEOM_CLASS(g_virstor_class, g_virstor); /* Let there be light */
1865