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