g_virstor.c revision 223921
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 223921 2011-07-11 05:22:31Z ae $");
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/sbuf.h>
44#include <sys/sysctl.h>
45#include <sys/malloc.h>
46#include <sys/time.h>
47#include <sys/proc.h>
48#include <sys/kthread.h>
49#include <sys/mutex.h>
50#include <vm/uma.h>
51#include <geom/geom.h>
52
53#include <geom/virstor/g_virstor.h>
54#include <geom/virstor/g_virstor_md.h>
55
56FEATURE(g_virstor, "GEOM virtual storage support");
57
58/* Declare malloc(9) label */
59static MALLOC_DEFINE(M_GVIRSTOR, "gvirstor", "GEOM_VIRSTOR Data");
60
61/* GEOM class methods */
62static g_init_t g_virstor_init;
63static g_fini_t g_virstor_fini;
64static g_taste_t g_virstor_taste;
65static g_ctl_req_t g_virstor_config;
66static g_ctl_destroy_geom_t g_virstor_destroy_geom;
67
68/* Declare & initialize class structure ("geom class") */
69struct g_class g_virstor_class = {
70	.name =		G_VIRSTOR_CLASS_NAME,
71	.version =	G_VERSION,
72	.init =		g_virstor_init,
73	.fini =		g_virstor_fini,
74	.taste =	g_virstor_taste,
75	.ctlreq =	g_virstor_config,
76	.destroy_geom = g_virstor_destroy_geom
77	/* The .dumpconf and the rest are only usable for a geom instance, so
78	 * they will be set when such instance is created. */
79};
80
81/* Declare sysctl's and loader tunables */
82SYSCTL_DECL(_kern_geom);
83SYSCTL_NODE(_kern_geom, OID_AUTO, virstor, CTLFLAG_RW, 0, "GEOM_GVIRSTOR information");
84
85static u_int g_virstor_debug = 2; /* XXX: lower to 2 when released to public */
86TUNABLE_INT("kern.geom.virstor.debug", &g_virstor_debug);
87SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, debug, CTLFLAG_RW, &g_virstor_debug,
88    0, "Debug level (2=production, 5=normal, 15=excessive)");
89
90static u_int g_virstor_chunk_watermark = 100;
91TUNABLE_INT("kern.geom.virstor.chunk_watermark", &g_virstor_chunk_watermark);
92SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, chunk_watermark, CTLFLAG_RW,
93    &g_virstor_chunk_watermark, 0,
94    "Minimum number of free chunks before issuing administrative warning");
95
96static u_int g_virstor_component_watermark = 1;
97TUNABLE_INT("kern.geom.virstor.component_watermark",
98    &g_virstor_component_watermark);
99SYSCTL_UINT(_kern_geom_virstor, OID_AUTO, component_watermark, CTLFLAG_RW,
100    &g_virstor_component_watermark, 0,
101    "Minimum number of free components before issuing administrative warning");
102
103static int read_metadata(struct g_consumer *, struct g_virstor_metadata *);
104static void write_metadata(struct g_consumer *, struct g_virstor_metadata *);
105static int clear_metadata(struct g_virstor_component *);
106static int add_provider_to_geom(struct g_virstor_softc *, struct g_provider *,
107    struct g_virstor_metadata *);
108static struct g_geom *create_virstor_geom(struct g_class *,
109    struct g_virstor_metadata *);
110static void virstor_check_and_run(struct g_virstor_softc *);
111static u_int virstor_valid_components(struct g_virstor_softc *);
112static int virstor_geom_destroy(struct g_virstor_softc *, boolean_t,
113    boolean_t);
114static void remove_component(struct g_virstor_softc *,
115    struct g_virstor_component *, boolean_t);
116static void bioq_dismantle(struct bio_queue_head *);
117static int allocate_chunk(struct g_virstor_softc *,
118    struct g_virstor_component **, u_int *, u_int *);
119static void delay_destroy_consumer(void *, int);
120static void dump_component(struct g_virstor_component *comp);
121#if 0
122static void dump_me(struct virstor_map_entry *me, unsigned int nr);
123#endif
124
125static void virstor_ctl_stop(struct gctl_req *, struct g_class *);
126static void virstor_ctl_add(struct gctl_req *, struct g_class *);
127static void virstor_ctl_remove(struct gctl_req *, struct g_class *);
128static struct g_virstor_softc * virstor_find_geom(const struct g_class *,
129    const char *);
130static void update_metadata(struct g_virstor_softc *);
131static void fill_metadata(struct g_virstor_softc *, struct g_virstor_metadata *,
132    u_int, u_int);
133
134static void g_virstor_orphan(struct g_consumer *);
135static int g_virstor_access(struct g_provider *, int, int, int);
136static void g_virstor_start(struct bio *);
137static void g_virstor_dumpconf(struct sbuf *, const char *, struct g_geom *,
138    struct g_consumer *, struct g_provider *);
139static void g_virstor_done(struct bio *);
140
141static void invalid_call(void);
142/*
143 * Initialise GEOM class (per-class callback)
144 */
145static void
146g_virstor_init(struct g_class *mp __unused)
147{
148
149	/* Catch map struct size mismatch at compile time; Map entries must
150	 * fit into MAXPHYS exactly, with no wasted space. */
151	CTASSERT(VIRSTOR_MAP_BLOCK_ENTRIES*VIRSTOR_MAP_ENTRY_SIZE == MAXPHYS);
152
153	/* Init UMA zones, TAILQ's, other global vars */
154}
155
156/*
157 * Finalise GEOM class (per-class callback)
158 */
159static void
160g_virstor_fini(struct g_class *mp __unused)
161{
162
163	/* Deinit UMA zones & global vars */
164}
165
166/*
167 * Config (per-class callback)
168 */
169static void
170g_virstor_config(struct gctl_req *req, struct g_class *cp, char const *verb)
171{
172	uint32_t *version;
173
174	g_topology_assert();
175
176	version = gctl_get_paraml(req, "version", sizeof(*version));
177	if (version == NULL) {
178		gctl_error(req, "Failed to get 'version' argument");
179		return;
180	}
181	if (*version != G_VIRSTOR_VERSION) {
182		gctl_error(req, "Userland and kernel versions out of sync");
183		return;
184	}
185
186	g_topology_unlock();
187	if (strcmp(verb, "add") == 0)
188		virstor_ctl_add(req, cp);
189	else if (strcmp(verb, "stop") == 0 || strcmp(verb, "destroy") == 0)
190		virstor_ctl_stop(req, cp);
191	else if (strcmp(verb, "remove") == 0)
192		virstor_ctl_remove(req, cp);
193	else
194		gctl_error(req, "unknown verb: '%s'", verb);
195	g_topology_lock();
196}
197
198/*
199 * "stop" verb from userland
200 */
201static void
202virstor_ctl_stop(struct gctl_req *req, struct g_class *cp)
203{
204	int *force, *nargs;
205	int i;
206
207	nargs = gctl_get_paraml(req, "nargs", sizeof *nargs);
208	if (nargs == NULL) {
209		gctl_error(req, "Error fetching argument '%s'", "nargs");
210		return;
211	}
212	if (*nargs < 1) {
213		gctl_error(req, "Invalid number of arguments");
214		return;
215	}
216	force = gctl_get_paraml(req, "force", sizeof *force);
217	if (force == NULL) {
218		gctl_error(req, "Error fetching argument '%s'", "force");
219		return;
220	}
221
222	g_topology_lock();
223	for (i = 0; i < *nargs; i++) {
224		char param[8];
225		const char *name;
226		struct g_virstor_softc *sc;
227		int error;
228
229		sprintf(param, "arg%d", i);
230		name = gctl_get_asciiparam(req, param);
231		if (name == NULL) {
232			gctl_error(req, "No 'arg%d' argument", i);
233			g_topology_unlock();
234			return;
235		}
236		sc = virstor_find_geom(cp, name);
237		LOG_MSG(LVL_INFO, "Stopping %s by the userland command",
238		    sc->geom->name);
239		update_metadata(sc);
240		if ((error = virstor_geom_destroy(sc, TRUE, TRUE)) != 0) {
241			LOG_MSG(LVL_ERROR, "Cannot destroy %s: %d",
242			    sc->geom->name, error);
243		}
244	}
245	g_topology_unlock();
246}
247
248/*
249 * "add" verb from userland - add new component(s) to the structure.
250 * This will be done all at once in here, without going through the
251 * .taste function for new components.
252 */
253static void
254virstor_ctl_add(struct gctl_req *req, struct g_class *cp)
255{
256	/* Note: while this is going on, I/O is being done on
257	 * the g_up and g_down threads. The idea is to make changes
258	 * to softc members in a way that can atomically activate
259	 * them all at once. */
260	struct g_virstor_softc *sc;
261	int *hardcode, *nargs;
262	const char *geom_name;	/* geom to add a component to */
263	struct g_consumer *fcp;
264	struct g_virstor_bio_q *bq;
265	u_int added;
266	int error;
267	int i;
268
269	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
270	if (nargs == NULL) {
271		gctl_error(req, "Error fetching argument '%s'", "nargs");
272		return;
273	}
274	if (*nargs < 2) {
275		gctl_error(req, "Invalid number of arguments");
276		return;
277	}
278	hardcode = gctl_get_paraml(req, "hardcode", sizeof(*hardcode));
279	if (hardcode == NULL) {
280		gctl_error(req, "Error fetching argument '%s'", "hardcode");
281		return;
282	}
283
284	/* Find "our" geom */
285	geom_name = gctl_get_asciiparam(req, "arg0");
286	if (geom_name == NULL) {
287		gctl_error(req, "Error fetching argument '%s'", "geom_name (arg0)");
288		return;
289	}
290	sc = virstor_find_geom(cp, geom_name);
291	if (sc == NULL) {
292		gctl_error(req, "Don't know anything about '%s'", geom_name);
293		return;
294	}
295
296	if (virstor_valid_components(sc) != sc->n_components) {
297		LOG_MSG(LVL_ERROR, "Cannot add components to incomplete "
298		    "virstor %s", sc->geom->name);
299		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
300		return;
301	}
302
303	fcp = sc->components[0].gcons;
304	added = 0;
305	g_topology_lock();
306	for (i = 1; i < *nargs; i++) {
307		struct g_virstor_metadata md;
308		char aname[8];
309		const char *prov_name;
310		struct g_provider *pp;
311		struct g_consumer *cp;
312		u_int nc;
313		u_int j;
314
315		snprintf(aname, sizeof aname, "arg%d", i);
316		prov_name = gctl_get_asciiparam(req, aname);
317		if (prov_name == NULL) {
318			gctl_error(req, "Error fetching argument '%s'", aname);
319			g_topology_unlock();
320			return;
321		}
322		if (strncmp(prov_name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
323			prov_name += sizeof(_PATH_DEV) - 1;
324
325		pp = g_provider_by_name(prov_name);
326		if (pp == NULL) {
327			/* This is the most common error so be verbose about it */
328			if (added != 0) {
329				gctl_error(req, "Invalid provider: '%s' (added"
330				    " %u components)", prov_name, added);
331				update_metadata(sc);
332			} else {
333				gctl_error(req, "Invalid provider: '%s'",
334				    prov_name);
335			}
336			g_topology_unlock();
337			return;
338		}
339		cp = g_new_consumer(sc->geom);
340		if (cp == NULL) {
341			gctl_error(req, "Cannot create consumer");
342			g_topology_unlock();
343			return;
344		}
345		error = g_attach(cp, pp);
346		if (error != 0) {
347			gctl_error(req, "Cannot attach a consumer to %s",
348			    pp->name);
349			g_destroy_consumer(cp);
350			g_topology_unlock();
351			return;
352		}
353		if (fcp->acr != 0 || fcp->acw != 0 || fcp->ace != 0) {
354			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
355			if (error != 0) {
356				gctl_error(req, "Access request failed for %s",
357				    pp->name);
358				g_destroy_consumer(cp);
359				g_topology_unlock();
360				return;
361			}
362		}
363		if (fcp->provider->sectorsize != pp->sectorsize) {
364			gctl_error(req, "Sector size doesn't fit for %s",
365			    pp->name);
366			g_destroy_consumer(cp);
367			g_topology_unlock();
368			return;
369		}
370		for (j = 0; j < sc->n_components; j++) {
371			if (strcmp(sc->components[j].gcons->provider->name,
372			    pp->name) == 0) {
373				gctl_error(req, "Component %s already in %s",
374				    pp->name, sc->geom->name);
375				g_destroy_consumer(cp);
376				g_topology_unlock();
377				return;
378			}
379		}
380		sc->components = realloc(sc->components,
381		    sizeof(*sc->components) * (sc->n_components + 1),
382		    M_GVIRSTOR, M_WAITOK);
383
384		nc = sc->n_components;
385		sc->components[nc].gcons = cp;
386		sc->components[nc].sc = sc;
387		sc->components[nc].index = nc;
388		sc->components[nc].chunk_count = cp->provider->mediasize /
389		    sc->chunk_size;
390		sc->components[nc].chunk_next = 0;
391		sc->components[nc].chunk_reserved = 0;
392
393		if (sc->components[nc].chunk_count < 4) {
394			gctl_error(req, "Provider too small: %s",
395			    cp->provider->name);
396			g_destroy_consumer(cp);
397			g_topology_unlock();
398			return;
399		}
400		fill_metadata(sc, &md, nc, *hardcode);
401		write_metadata(cp, &md);
402		/* The new component becomes visible when n_components is
403		 * incremented */
404		sc->n_components++;
405		added++;
406
407	}
408	/* This call to update_metadata() is critical. In case there's a
409	 * power failure in the middle of it and some components are updated
410	 * while others are not, there will be trouble on next .taste() iff
411	 * a non-updated component is detected first */
412	update_metadata(sc);
413	g_topology_unlock();
414	LOG_MSG(LVL_INFO, "Added %d component(s) to %s", added,
415	    sc->geom->name);
416	/* Fire off BIOs previously queued because there wasn't any
417	 * physical space left. If the BIOs still can't be satisfied
418	 * they will again be added to the end of the queue (during
419	 * which the mutex will be recursed) */
420	bq = malloc(sizeof(*bq), M_GVIRSTOR, M_WAITOK);
421	bq->bio = NULL;
422	mtx_lock(&sc->delayed_bio_q_mtx);
423	/* First, insert a sentinel to the queue end, so we don't
424	 * end up in an infinite loop if there's still no free
425	 * space available. */
426	STAILQ_INSERT_TAIL(&sc->delayed_bio_q, bq, linkage);
427	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
428		bq = STAILQ_FIRST(&sc->delayed_bio_q);
429		if (bq->bio != NULL) {
430			g_virstor_start(bq->bio);
431			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
432			free(bq, M_GVIRSTOR);
433		} else {
434			STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
435			free(bq, M_GVIRSTOR);
436			break;
437		}
438	}
439	mtx_unlock(&sc->delayed_bio_q_mtx);
440
441}
442
443/*
444 * Find a geom handled by the class
445 */
446static struct g_virstor_softc *
447virstor_find_geom(const struct g_class *cp, const char *name)
448{
449	struct g_geom *gp;
450
451	LIST_FOREACH(gp, &cp->geom, geom) {
452		if (strcmp(name, gp->name) == 0)
453			return (gp->softc);
454	}
455	return (NULL);
456}
457
458/*
459 * Update metadata on all components to reflect the current state
460 * of these fields:
461 *    - chunk_next
462 *    - flags
463 *    - md_count
464 * Expects things to be set up so write_metadata() can work, i.e.
465 * the topology lock must be held.
466 */
467static void
468update_metadata(struct g_virstor_softc *sc)
469{
470	struct g_virstor_metadata md;
471	int n;
472
473	if (virstor_valid_components(sc) != sc->n_components)
474		return; /* Incomplete device */
475	LOG_MSG(LVL_DEBUG, "Updating metadata on components for %s",
476	    sc->geom->name);
477	/* Update metadata on components */
478	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__,
479	    sc->geom->class->name, sc->geom->name);
480	g_topology_assert();
481	for (n = 0; n < sc->n_components; n++) {
482		read_metadata(sc->components[n].gcons, &md);
483		md.chunk_next = sc->components[n].chunk_next;
484		md.flags = sc->components[n].flags;
485		md.md_count = sc->n_components;
486		write_metadata(sc->components[n].gcons, &md);
487	}
488}
489
490/*
491 * Fills metadata (struct md) from information stored in softc and the nc'th
492 * component of virstor
493 */
494static void
495fill_metadata(struct g_virstor_softc *sc, struct g_virstor_metadata *md,
496    u_int nc, u_int hardcode)
497{
498	struct g_virstor_component *c;
499
500	bzero(md, sizeof *md);
501	c = &sc->components[nc];
502
503	strncpy(md->md_magic, G_VIRSTOR_MAGIC, sizeof md->md_magic);
504	md->md_version = G_VIRSTOR_VERSION;
505	strncpy(md->md_name, sc->geom->name, sizeof md->md_name);
506	md->md_id = sc->id;
507	md->md_virsize = sc->virsize;
508	md->md_chunk_size = sc->chunk_size;
509	md->md_count = sc->n_components;
510
511	if (hardcode) {
512		strncpy(md->provider, c->gcons->provider->name,
513		    sizeof md->provider);
514	}
515	md->no = nc;
516	md->provsize = c->gcons->provider->mediasize;
517	md->chunk_count = c->chunk_count;
518	md->chunk_next = c->chunk_next;
519	md->chunk_reserved = c->chunk_reserved;
520	md->flags = c->flags;
521}
522
523/*
524 * Remove a component from virstor device.
525 * Can only be done if the component is unallocated.
526 */
527static void
528virstor_ctl_remove(struct gctl_req *req, struct g_class *cp)
529{
530	/* As this is executed in parallel to I/O, operations on virstor
531	 * structures must be as atomic as possible. */
532	struct g_virstor_softc *sc;
533	int *nargs;
534	const char *geom_name;
535	u_int removed;
536	int i;
537
538	nargs = gctl_get_paraml(req, "nargs", sizeof(*nargs));
539	if (nargs == NULL) {
540		gctl_error(req, "Error fetching argument '%s'", "nargs");
541		return;
542	}
543	if (*nargs < 2) {
544		gctl_error(req, "Invalid number of arguments");
545		return;
546	}
547	/* Find "our" geom */
548	geom_name = gctl_get_asciiparam(req, "arg0");
549	if (geom_name == NULL) {
550		gctl_error(req, "Error fetching argument '%s'",
551		    "geom_name (arg0)");
552		return;
553	}
554	sc = virstor_find_geom(cp, geom_name);
555	if (sc == NULL) {
556		gctl_error(req, "Don't know anything about '%s'", geom_name);
557		return;
558	}
559
560	if (virstor_valid_components(sc) != sc->n_components) {
561		LOG_MSG(LVL_ERROR, "Cannot remove components from incomplete "
562		    "virstor %s", sc->geom->name);
563		gctl_error(req, "Virstor %s is incomplete", sc->geom->name);
564		return;
565	}
566
567	removed = 0;
568	for (i = 1; i < *nargs; i++) {
569		char param[8];
570		const char *prov_name;
571		int j, found;
572		struct g_virstor_component *newcomp, *compbak;
573
574		sprintf(param, "arg%d", i);
575		prov_name = gctl_get_asciiparam(req, param);
576		if (prov_name == NULL) {
577			gctl_error(req, "Error fetching argument '%s'", param);
578			return;
579		}
580		if (strncmp(prov_name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
581			prov_name += sizeof(_PATH_DEV) - 1;
582
583		found = -1;
584		for (j = 0; j < sc->n_components; j++) {
585			if (strcmp(sc->components[j].gcons->provider->name,
586			    prov_name) == 0) {
587				found = j;
588				break;
589			}
590		}
591		if (found == -1) {
592			LOG_MSG(LVL_ERROR, "No %s component in %s",
593			    prov_name, sc->geom->name);
594			continue;
595		}
596
597		compbak = sc->components;
598		newcomp = malloc(sc->n_components * sizeof(*sc->components),
599		    M_GVIRSTOR, M_WAITOK | M_ZERO);
600		bcopy(sc->components, newcomp, found * sizeof(*sc->components));
601		bcopy(&sc->components[found + 1], newcomp + found,
602		    found * sizeof(*sc->components));
603		if ((sc->components[j].flags & VIRSTOR_PROVIDER_ALLOCATED) != 0) {
604			LOG_MSG(LVL_ERROR, "Allocated provider %s cannot be "
605			    "removed from %s",
606			    prov_name, sc->geom->name);
607			free(newcomp, M_GVIRSTOR);
608			/* We'll consider this non-fatal error */
609			continue;
610		}
611		/* Renumerate unallocated components */
612		for (j = 0; j < sc->n_components-1; j++) {
613			if ((sc->components[j].flags &
614			    VIRSTOR_PROVIDER_ALLOCATED) == 0) {
615				sc->components[j].index = j;
616			}
617		}
618		/* This is the critical section. If a component allocation
619		 * event happens while both variables are not yet set,
620		 * there will be trouble. Something will panic on encountering
621		 * NULL sc->components[x].gcomp member.
622		 * Luckily, component allocation happens very rarely and
623		 * removing components is an abnormal action in any case. */
624		sc->components = newcomp;
625		sc->n_components--;
626		/* End critical section */
627
628		g_topology_lock();
629		if (clear_metadata(&compbak[found]) != 0) {
630			LOG_MSG(LVL_WARNING, "Trouble ahead: cannot clear "
631			    "metadata on %s", prov_name);
632		}
633		g_detach(compbak[found].gcons);
634		g_destroy_consumer(compbak[found].gcons);
635		g_topology_unlock();
636
637		free(compbak, M_GVIRSTOR);
638
639		removed++;
640	}
641
642	/* This call to update_metadata() is critical. In case there's a
643	 * power failure in the middle of it and some components are updated
644	 * while others are not, there will be trouble on next .taste() iff
645	 * a non-updated component is detected first */
646	g_topology_lock();
647	update_metadata(sc);
648	g_topology_unlock();
649	LOG_MSG(LVL_INFO, "Removed %d component(s) from %s", removed,
650	    sc->geom->name);
651}
652
653/*
654 * Clear metadata sector on component
655 */
656static int
657clear_metadata(struct g_virstor_component *comp)
658{
659	char *buf;
660	int error;
661
662	LOG_MSG(LVL_INFO, "Clearing metadata on %s",
663	    comp->gcons->provider->name);
664	g_topology_assert();
665	error = g_access(comp->gcons, 0, 1, 0);
666	if (error != 0)
667		return (error);
668	buf = malloc(comp->gcons->provider->sectorsize, M_GVIRSTOR,
669	    M_WAITOK | M_ZERO);
670	error = g_write_data(comp->gcons,
671	    comp->gcons->provider->mediasize -
672	    comp->gcons->provider->sectorsize,
673	    buf,
674	    comp->gcons->provider->sectorsize);
675	free(buf, M_GVIRSTOR);
676	g_access(comp->gcons, 0, -1, 0);
677	return (error);
678}
679
680/*
681 * Destroy geom forcibly.
682 */
683static int
684g_virstor_destroy_geom(struct gctl_req *req __unused, struct g_class *mp,
685    struct g_geom *gp)
686{
687	struct g_virstor_softc *sc;
688	int exitval;
689
690	sc = gp->softc;
691	KASSERT(sc != NULL, ("%s: NULL sc", __func__));
692
693	exitval = 0;
694	LOG_MSG(LVL_DEBUG, "%s called for %s, sc=%p", __func__, gp->name,
695	    gp->softc);
696
697	if (sc != NULL) {
698#ifdef INVARIANTS
699		char *buf;
700		int error;
701		off_t off;
702		int isclean, count;
703		int n;
704
705		LOG_MSG(LVL_INFO, "INVARIANTS detected");
706		LOG_MSG(LVL_INFO, "Verifying allocation "
707		    "table for %s", sc->geom->name);
708		count = 0;
709		for (n = 0; n < sc->chunk_count; n++) {
710			if (sc->map[n].flags || VIRSTOR_MAP_ALLOCATED != 0)
711				count++;
712		}
713		LOG_MSG(LVL_INFO, "Device %s has %d allocated chunks",
714		    sc->geom->name, count);
715		n = off = count = 0;
716		isclean = 1;
717		if (virstor_valid_components(sc) != sc->n_components) {
718			/* This is a incomplete virstor device (not all
719			 * components have been found) */
720			LOG_MSG(LVL_ERROR, "Device %s is incomplete",
721			    sc->geom->name);
722			goto bailout;
723		}
724		error = g_access(sc->components[0].gcons, 1, 0, 0);
725		KASSERT(error == 0, ("%s: g_access failed (%d)", __func__,
726		    error));
727		/* Compare the whole on-disk allocation table with what's
728		 * currently in memory */
729		while (n < sc->chunk_count) {
730			buf = g_read_data(sc->components[0].gcons, off,
731			    sc->sectorsize, &error);
732			KASSERT(buf != NULL, ("g_read_data returned NULL (%d) "
733			    "for read at %jd", error, off));
734			if (bcmp(buf, &sc->map[n], sc->sectorsize) != 0) {
735				LOG_MSG(LVL_ERROR, "ERROR in allocation table, "
736				    "entry %d, offset %jd", n, off);
737				isclean = 0;
738				count++;
739			}
740			n += sc->me_per_sector;
741			off += sc->sectorsize;
742			g_free(buf);
743		}
744		error = g_access(sc->components[0].gcons, -1, 0, 0);
745		KASSERT(error == 0, ("%s: g_access failed (%d) on exit",
746		    __func__, error));
747		if (isclean != 1) {
748			LOG_MSG(LVL_ERROR, "ALLOCATION TABLE CORRUPTED FOR %s "
749			    "(%d sectors don't match, max %zu allocations)",
750			    sc->geom->name, count,
751			    count * sc->me_per_sector);
752		} else {
753			LOG_MSG(LVL_INFO, "Allocation table ok for %s",
754			    sc->geom->name);
755		}
756bailout:
757#endif
758		update_metadata(sc);
759		virstor_geom_destroy(sc, FALSE, FALSE);
760		exitval = EAGAIN;
761	} else
762		exitval = 0;
763	return (exitval);
764}
765
766/*
767 * Taste event (per-class callback)
768 * Examines a provider and creates geom instances if needed
769 */
770static struct g_geom *
771g_virstor_taste(struct g_class *mp, struct g_provider *pp, int flags)
772{
773	struct g_virstor_metadata md;
774	struct g_geom *gp;
775	struct g_consumer *cp;
776	struct g_virstor_softc *sc;
777	int error;
778
779	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
780	g_topology_assert();
781	LOG_MSG(LVL_DEBUG, "Tasting %s", pp->name);
782
783	/* We need a dummy geom to attach a consumer to the given provider */
784	gp = g_new_geomf(mp, "virstor:taste.helper");
785	gp->start = (void *)invalid_call;	/* XXX: hacked up so the        */
786	gp->access = (void *)invalid_call;	/* compiler doesn't complain.   */
787	gp->orphan = (void *)invalid_call;	/* I really want these to fail. */
788
789	cp = g_new_consumer(gp);
790	g_attach(cp, pp);
791	error = read_metadata(cp, &md);
792	g_detach(cp);
793	g_destroy_consumer(cp);
794	g_destroy_geom(gp);
795
796	if (error != 0)
797		return (NULL);
798
799	if (strcmp(md.md_magic, G_VIRSTOR_MAGIC) != 0)
800		return (NULL);
801	if (md.md_version != G_VIRSTOR_VERSION) {
802		LOG_MSG(LVL_ERROR, "Kernel module version invalid "
803		    "to handle %s (%s) : %d should be %d",
804		    md.md_name, pp->name, md.md_version, G_VIRSTOR_VERSION);
805		return (NULL);
806	}
807	if (md.provsize != pp->mediasize)
808		return (NULL);
809
810	/* If the provider name is hardcoded, use the offered provider only
811	 * if it's been offered with its proper name (the one used in
812	 * the label command). */
813	if (md.provider[0] != '\0' &&
814	    !g_compare_names(md.provider, pp->name))
815		return (NULL);
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