g_virstor.c revision 221101
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 221101 2011-04-27 00:10:26Z mav $");
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	    !g_compare_names(md.provider, pp->name))
814		return (NULL);
815
816	/* Iterate all geoms this class already knows about to see if a new
817	 * geom instance of this class needs to be created (in case the provider
818	 * is first from a (possibly) multi-consumer geom) or it just needs
819	 * to be added to an existing instance. */
820	sc = NULL;
821	gp = NULL;
822	LIST_FOREACH(gp, &mp->geom, geom) {
823		sc = gp->softc;
824		if (sc == NULL)
825			continue;
826		if (strcmp(md.md_name, sc->geom->name) != 0)
827			continue;
828		if (md.md_id != sc->id)
829			continue;
830		break;
831	}
832	if (gp != NULL) { /* We found an existing geom instance; add to it */
833		LOG_MSG(LVL_INFO, "Adding %s to %s", pp->name, md.md_name);
834		error = add_provider_to_geom(sc, pp, &md);
835		if (error != 0) {
836			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
837			    pp->name, md.md_name, error);
838			return (NULL);
839		}
840	} else { /* New geom instance needs to be created */
841		gp = create_virstor_geom(mp, &md);
842		if (gp == NULL) {
843			LOG_MSG(LVL_ERROR, "Error creating new instance of "
844			    "class %s: %s", mp->name, md.md_name);
845			LOG_MSG(LVL_DEBUG, "Error creating %s at %s",
846			    md.md_name, pp->name);
847			return (NULL);
848		}
849		sc = gp->softc;
850		LOG_MSG(LVL_INFO, "Adding %s to %s (first found)", pp->name,
851		    md.md_name);
852		error = add_provider_to_geom(sc, pp, &md);
853		if (error != 0) {
854			LOG_MSG(LVL_ERROR, "Error adding %s to %s (error %d)",
855			    pp->name, md.md_name, error);
856			virstor_geom_destroy(sc, TRUE, FALSE);
857			return (NULL);
858		}
859	}
860
861	return (gp);
862}
863
864/*
865 * Destroyes consumer passed to it in arguments. Used as a callback
866 * on g_event queue.
867 */
868static void
869delay_destroy_consumer(void *arg, int flags __unused)
870{
871	struct g_consumer *c = arg;
872	KASSERT(c != NULL, ("%s: invalid consumer", __func__));
873	LOG_MSG(LVL_DEBUG, "Consumer %s destroyed with delay",
874	    c->provider->name);
875	g_detach(c);
876	g_destroy_consumer(c);
877}
878
879/*
880 * Remove a component (consumer) from geom instance; If it's the first
881 * component being removed, orphan the provider to announce geom's being
882 * dismantled
883 */
884static void
885remove_component(struct g_virstor_softc *sc, struct g_virstor_component *comp,
886    boolean_t delay)
887{
888	struct g_consumer *c;
889
890	KASSERT(comp->gcons != NULL, ("Component with no consumer in %s",
891	    sc->geom->name));
892	c = comp->gcons;
893
894	comp->gcons = NULL;
895	KASSERT(c->provider != NULL, ("%s: no provider", __func__));
896	LOG_MSG(LVL_DEBUG, "Component %s removed from %s", c->provider->name,
897	    sc->geom->name);
898	if (sc->provider != NULL) {
899		/* Whither, GEOM? */
900		sc->provider->flags |= G_PF_WITHER;
901		g_orphan_provider(sc->provider, ENXIO);
902		sc->provider = NULL;
903		LOG_MSG(LVL_INFO, "Removing provider %s", sc->geom->name);
904	}
905
906	if (c->acr > 0 || c->acw > 0 || c->ace > 0)
907		g_access(c, -c->acr, -c->acw, -c->ace);
908	if (delay) {
909		/* Destroy consumer after it's tasted */
910		g_post_event(delay_destroy_consumer, c, M_WAITOK, NULL);
911	} else {
912		g_detach(c);
913		g_destroy_consumer(c);
914	}
915}
916
917/*
918 * Destroy geom - called internally
919 * See g_virstor_destroy_geom for the other one
920 */
921static int
922virstor_geom_destroy(struct g_virstor_softc *sc, boolean_t force,
923    boolean_t delay)
924{
925	struct g_provider *pp;
926	struct g_geom *gp;
927	int n;
928
929	g_topology_assert();
930
931	if (sc == NULL)
932		return (ENXIO);
933
934	pp = sc->provider;
935	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
936		LOG_MSG(force ? LVL_WARNING : LVL_ERROR,
937		    "Device %s is still open.", pp->name);
938		if (!force)
939			return (EBUSY);
940	}
941
942	for (n = 0; n < sc->n_components; n++) {
943		if (sc->components[n].gcons != NULL)
944			remove_component(sc, &sc->components[n], delay);
945	}
946
947	gp = sc->geom;
948	gp->softc = NULL;
949
950	KASSERT(sc->provider == NULL, ("Provider still exists for %s",
951	    gp->name));
952
953	/* XXX: This might or might not work, since we're called with
954	 * the topology lock held. Also, it might panic the kernel if
955	 * the error'd BIO is in softupdates code. */
956	mtx_lock(&sc->delayed_bio_q_mtx);
957	while (!STAILQ_EMPTY(&sc->delayed_bio_q)) {
958		struct g_virstor_bio_q *bq;
959		bq = STAILQ_FIRST(&sc->delayed_bio_q);
960		bq->bio->bio_error = ENOSPC;
961		g_io_deliver(bq->bio, EIO);
962		STAILQ_REMOVE_HEAD(&sc->delayed_bio_q, linkage);
963		free(bq, M_GVIRSTOR);
964	}
965	mtx_unlock(&sc->delayed_bio_q_mtx);
966	mtx_destroy(&sc->delayed_bio_q_mtx);
967
968	free(sc->map, M_GVIRSTOR);
969	free(sc->components, M_GVIRSTOR);
970	bzero(sc, sizeof *sc);
971	free(sc, M_GVIRSTOR);
972
973	pp = LIST_FIRST(&gp->provider); /* We only offer one provider */
974	if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
975		LOG_MSG(LVL_DEBUG, "Device %s destroyed", gp->name);
976
977	g_wither_geom(gp, ENXIO);
978
979	return (0);
980}
981
982/*
983 * Utility function: read metadata & decode. Wants topology lock to be
984 * held.
985 */
986static int
987read_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
988{
989	struct g_provider *pp;
990	char *buf;
991	int error;
992
993	g_topology_assert();
994	error = g_access(cp, 1, 0, 0);
995	if (error != 0)
996		return (error);
997	pp = cp->provider;
998	g_topology_unlock();
999	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
1000	    &error);
1001	g_topology_lock();
1002	g_access(cp, -1, 0, 0);
1003	if (buf == NULL)
1004		return (error);
1005
1006	virstor_metadata_decode(buf, md);
1007	g_free(buf);
1008
1009	return (0);
1010}
1011
1012/**
1013 * Utility function: encode & write metadata. Assumes topology lock is
1014 * held.
1015 *
1016 * There is no useful way of recovering from errors in this function,
1017 * not involving panicking the kernel. If the metadata cannot be written
1018 * the most we can do is notify the operator and hope he spots it and
1019 * replaces the broken drive.
1020 */
1021static void
1022write_metadata(struct g_consumer *cp, struct g_virstor_metadata *md)
1023{
1024	struct g_provider *pp;
1025	char *buf;
1026	int error;
1027
1028	KASSERT(cp != NULL && md != NULL && cp->provider != NULL,
1029	    ("Something's fishy in %s", __func__));
1030	LOG_MSG(LVL_DEBUG, "Writing metadata on %s", cp->provider->name);
1031	g_topology_assert();
1032	error = g_access(cp, 0, 1, 0);
1033	if (error != 0) {
1034		LOG_MSG(LVL_ERROR, "g_access(0,1,0) failed for %s: %d",
1035		    cp->provider->name, error);
1036		return;
1037	}
1038	pp = cp->provider;
1039
1040	buf = malloc(pp->sectorsize, M_GVIRSTOR, M_WAITOK);
1041	virstor_metadata_encode(md, buf);
1042	g_topology_unlock();
1043	error = g_write_data(cp, pp->mediasize - pp->sectorsize, buf,
1044	    pp->sectorsize);
1045	g_topology_lock();
1046	g_access(cp, 0, -1, 0);
1047	free(buf, M_GVIRSTOR);
1048
1049	if (error != 0)
1050		LOG_MSG(LVL_ERROR, "Error %d writing metadata to %s",
1051		    error, cp->provider->name);
1052}
1053
1054/*
1055 * Creates a new instance of this GEOM class, initialise softc
1056 */
1057static struct g_geom *
1058create_virstor_geom(struct g_class *mp, struct g_virstor_metadata *md)
1059{
1060	struct g_geom *gp;
1061	struct g_virstor_softc *sc;
1062
1063	LOG_MSG(LVL_DEBUG, "Creating geom instance for %s (id=%u)",
1064	    md->md_name, md->md_id);
1065
1066	if (md->md_count < 1 || md->md_chunk_size < 1 ||
1067	    md->md_virsize < md->md_chunk_size) {
1068		/* This is bogus configuration, and probably means data is
1069		 * somehow corrupted. Panic, maybe? */
1070		LOG_MSG(LVL_ERROR, "Nonsensical metadata information for %s",
1071		    md->md_name);
1072		return (NULL);
1073	}
1074
1075	/* Check if it's already created */
1076	LIST_FOREACH(gp, &mp->geom, geom) {
1077		sc = gp->softc;
1078		if (sc != NULL && strcmp(sc->geom->name, md->md_name) == 0) {
1079			LOG_MSG(LVL_WARNING, "Geom %s already exists",
1080			    md->md_name);
1081			if (sc->id != md->md_id) {
1082				LOG_MSG(LVL_ERROR,
1083				    "Some stale or invalid components "
1084				    "exist for virstor device named %s. "
1085				    "You will need to <CLEAR> all stale "
1086				    "components and maybe reconfigure "
1087				    "the virstor device. Tune "
1088				    "kern.geom.virstor.debug sysctl up "
1089				    "for more information.",
1090				    sc->geom->name);
1091			}
1092			return (NULL);
1093		}
1094	}
1095	gp = g_new_geomf(mp, "%s", md->md_name);
1096	gp->softc = NULL; /* to circumevent races that test softc */
1097
1098	gp->start = g_virstor_start;
1099	gp->spoiled = g_virstor_orphan;
1100	gp->orphan = g_virstor_orphan;
1101	gp->access = g_virstor_access;
1102	gp->dumpconf = g_virstor_dumpconf;
1103
1104	sc = malloc(sizeof(*sc), M_GVIRSTOR, M_WAITOK | M_ZERO);
1105	sc->id = md->md_id;
1106	sc->n_components = md->md_count;
1107	sc->components = malloc(sizeof(struct g_virstor_component) * md->md_count,
1108	    M_GVIRSTOR, M_WAITOK | M_ZERO);
1109	sc->chunk_size = md->md_chunk_size;
1110	sc->virsize = md->md_virsize;
1111	STAILQ_INIT(&sc->delayed_bio_q);
1112	mtx_init(&sc->delayed_bio_q_mtx, "gvirstor_delayed_bio_q_mtx",
1113	    "gvirstor", MTX_DEF | MTX_RECURSE);
1114
1115	sc->geom = gp;
1116	sc->provider = NULL; /* virstor_check_and_run will create it */
1117	gp->softc = sc;
1118
1119	LOG_MSG(LVL_ANNOUNCE, "Device %s created", sc->geom->name);
1120
1121	return (gp);
1122}
1123
1124/*
1125 * Add provider to a GEOM class instance
1126 */
1127static int
1128add_provider_to_geom(struct g_virstor_softc *sc, struct g_provider *pp,
1129    struct g_virstor_metadata *md)
1130{
1131	struct g_virstor_component *component;
1132	struct g_consumer *cp, *fcp;
1133	struct g_geom *gp;
1134	int error;
1135
1136	if (md->no >= sc->n_components)
1137		return (EINVAL);
1138
1139	/* "Current" compontent */
1140	component = &(sc->components[md->no]);
1141	if (component->gcons != NULL)
1142		return (EEXIST);
1143
1144	gp = sc->geom;
1145	fcp = LIST_FIRST(&gp->consumer);
1146
1147	cp = g_new_consumer(gp);
1148	error = g_attach(cp, pp);
1149
1150	if (error != 0) {
1151		g_destroy_consumer(cp);
1152		return (error);
1153	}
1154
1155	if (fcp != NULL) {
1156		if (fcp->provider->sectorsize != pp->sectorsize) {
1157			/* TODO: this can be made to work */
1158			LOG_MSG(LVL_ERROR, "Provider %s of %s has invalid "
1159			    "sector size (%d)", pp->name, sc->geom->name,
1160			    pp->sectorsize);
1161			return (EINVAL);
1162		}
1163		if (fcp->acr > 0 || fcp->acw || fcp->ace > 0) {
1164			/* Replicate access permissions from first "live" consumer
1165			 * to the new one */
1166			error = g_access(cp, fcp->acr, fcp->acw, fcp->ace);
1167			if (error != 0) {
1168				g_detach(cp);
1169				g_destroy_consumer(cp);
1170				return (error);
1171			}
1172		}
1173	}
1174
1175	/* Bring up a new component */
1176	cp->private = component;
1177	component->gcons = cp;
1178	component->sc = sc;
1179	component->index = md->no;
1180	component->chunk_count = md->chunk_count;
1181	component->chunk_next = md->chunk_next;
1182	component->chunk_reserved = md->chunk_reserved;
1183	component->flags = md->flags;
1184
1185	LOG_MSG(LVL_DEBUG, "%s attached to %s", pp->name, sc->geom->name);
1186
1187	virstor_check_and_run(sc);
1188	return (0);
1189}
1190
1191/*
1192 * Check if everything's ready to create the geom provider & device entry,
1193 * create and start provider.
1194 * Called ultimately by .taste, from g_event thread
1195 */
1196static void
1197virstor_check_and_run(struct g_virstor_softc *sc)
1198{
1199	off_t off;
1200	size_t n, count;
1201	int index;
1202	int error;
1203
1204	if (virstor_valid_components(sc) != sc->n_components)
1205		return;
1206
1207	if (virstor_valid_components(sc) == 0) {
1208		/* This is actually a candidate for panic() */
1209		LOG_MSG(LVL_ERROR, "No valid components for %s?",
1210		    sc->provider->name);
1211		return;
1212	}
1213
1214	sc->sectorsize = sc->components[0].gcons->provider->sectorsize;
1215
1216	/* Initialise allocation map from the first consumer */
1217	sc->chunk_count = sc->virsize / sc->chunk_size;
1218	if (sc->chunk_count * (off_t)sc->chunk_size != sc->virsize) {
1219		LOG_MSG(LVL_WARNING, "Device %s truncated to %ju bytes",
1220		    sc->provider->name,
1221		    sc->chunk_count * (off_t)sc->chunk_size);
1222	}
1223	sc->map_size = sc->chunk_count * sizeof *(sc->map);
1224	/* The following allocation is in order of 4MB - 8MB */
1225	sc->map = malloc(sc->map_size, M_GVIRSTOR, M_WAITOK);
1226	KASSERT(sc->map != NULL, ("%s: Memory allocation error (%zu bytes) for %s",
1227	    __func__, sc->map_size, sc->provider->name));
1228	sc->map_sectors = sc->map_size / sc->sectorsize;
1229
1230	count = 0;
1231	for (n = 0; n < sc->n_components; n++)
1232		count += sc->components[n].chunk_count;
1233	LOG_MSG(LVL_INFO, "Device %s has %zu physical chunks and %zu virtual "
1234	    "(%zu KB chunks)",
1235	    sc->geom->name, count, sc->chunk_count, sc->chunk_size / 1024);
1236
1237	error = g_access(sc->components[0].gcons, 1, 0, 0);
1238	if (error != 0) {
1239		LOG_MSG(LVL_ERROR, "Cannot acquire read access for %s to "
1240		    "read allocation map for %s",
1241		    sc->components[0].gcons->provider->name,
1242		    sc->geom->name);
1243		return;
1244	}
1245	/* Read in the allocation map */
1246	LOG_MSG(LVL_DEBUG, "Reading map for %s from %s", sc->geom->name,
1247	    sc->components[0].gcons->provider->name);
1248	off = count = n = 0;
1249	while (count < sc->map_size) {
1250		struct g_virstor_map_entry *mapbuf;
1251		size_t bs;
1252
1253		bs = MIN(MAXPHYS, sc->map_size - count);
1254		if (bs % sc->sectorsize != 0) {
1255			/* Check for alignment errors */
1256			bs = (bs / sc->sectorsize) * sc->sectorsize;
1257			if (bs == 0)
1258				break;
1259			LOG_MSG(LVL_ERROR, "Trouble: map is not sector-aligned "
1260			    "for %s on %s", sc->geom->name,
1261			    sc->components[0].gcons->provider->name);
1262		}
1263		mapbuf = g_read_data(sc->components[0].gcons, off, bs, &error);
1264		if (mapbuf == NULL) {
1265			free(sc->map, M_GVIRSTOR);
1266			LOG_MSG(LVL_ERROR, "Error reading allocation map "
1267			    "for %s from %s (offset %ju) (error %d)",
1268			    sc->geom->name,
1269			    sc->components[0].gcons->provider->name,
1270			    off, error);
1271			return;
1272		}
1273
1274		bcopy(mapbuf, &sc->map[n], bs);
1275		off += bs;
1276		count += bs;
1277		n += bs / sizeof *(sc->map);
1278		g_free(mapbuf);
1279	}
1280	g_access(sc->components[0].gcons, -1, 0, 0);
1281	LOG_MSG(LVL_DEBUG, "Read map for %s", sc->geom->name);
1282
1283	/* find first component with allocatable chunks */
1284	index = -1;
1285	for (n = 0; n < sc->n_components; n++) {
1286		if (sc->components[n].chunk_next <
1287		    sc->components[n].chunk_count) {
1288			index = n;
1289			break;
1290		}
1291	}
1292	if (index == -1)
1293		/* not found? set it to the last component and handle it
1294		 * later */
1295		index = sc->n_components - 1;
1296
1297	if (index >= sc->n_components - g_virstor_component_watermark - 1) {
1298		LOG_MSG(LVL_WARNING, "Device %s running out of components "
1299		    "(%d/%u: %s)", sc->geom->name,
1300		    index+1,
1301		    sc->n_components,
1302		    sc->components[index].gcons->provider->name);
1303	}
1304	sc->curr_component = index;
1305
1306	if (sc->components[index].chunk_next >=
1307	    sc->components[index].chunk_count - g_virstor_chunk_watermark) {
1308		LOG_MSG(LVL_WARNING,
1309		    "Component %s of %s is running out of free space "
1310		    "(%u chunks left)",
1311		    sc->components[index].gcons->provider->name,
1312		    sc->geom->name, sc->components[index].chunk_count -
1313		    sc->components[index].chunk_next);
1314	}
1315
1316	sc->me_per_sector = sc->sectorsize / sizeof *(sc->map);
1317	if (sc->sectorsize % sizeof *(sc->map) != 0) {
1318		LOG_MSG(LVL_ERROR,
1319		    "%s: Map entries don't fit exactly in a sector (%s)",
1320		    __func__, sc->geom->name);
1321		return;
1322	}
1323
1324	/* Recalculate allocated chunks in components & at the same time
1325	 * verify map data is sane. We could trust metadata on this, but
1326	 * we want to make sure. */
1327	for (n = 0; n < sc->n_components; n++)
1328		sc->components[n].chunk_next = sc->components[n].chunk_reserved;
1329
1330	for (n = 0; n < sc->chunk_count; n++) {
1331		if (sc->map[n].provider_no >= sc->n_components ||
1332			sc->map[n].provider_chunk >=
1333			sc->components[sc->map[n].provider_no].chunk_count) {
1334			LOG_MSG(LVL_ERROR, "%s: Invalid entry %u in map for %s",
1335			    __func__, (u_int)n, sc->geom->name);
1336			LOG_MSG(LVL_ERROR, "%s: provider_no: %u, n_components: %u"
1337			    " provider_chunk: %u, chunk_count: %u", __func__,
1338			    sc->map[n].provider_no, sc->n_components,
1339			    sc->map[n].provider_chunk,
1340			    sc->components[sc->map[n].provider_no].chunk_count);
1341			return;
1342		}
1343		if (sc->map[n].flags & VIRSTOR_MAP_ALLOCATED)
1344			sc->components[sc->map[n].provider_no].chunk_next++;
1345	}
1346
1347	sc->provider = g_new_providerf(sc->geom, "virstor/%s",
1348	    sc->geom->name);
1349
1350	sc->provider->sectorsize = sc->sectorsize;
1351	sc->provider->mediasize = sc->virsize;
1352	g_error_provider(sc->provider, 0);
1353
1354	LOG_MSG(LVL_INFO, "%s activated", sc->provider->name);
1355	LOG_MSG(LVL_DEBUG, "%s starting with current component %u, starting "
1356	    "chunk %u", sc->provider->name, sc->curr_component,
1357	    sc->components[sc->curr_component].chunk_next);
1358}
1359
1360/*
1361 * Returns count of active providers in this geom instance
1362 */
1363static u_int
1364virstor_valid_components(struct g_virstor_softc *sc)
1365{
1366	unsigned int nc, i;
1367
1368	nc = 0;
1369	KASSERT(sc != NULL, ("%s: softc is NULL", __func__));
1370	KASSERT(sc->components != NULL, ("%s: sc->components is NULL", __func__));
1371	for (i = 0; i < sc->n_components; i++)
1372		if (sc->components[i].gcons != NULL)
1373			nc++;
1374	return (nc);
1375}
1376
1377/*
1378 * Called when the consumer gets orphaned (?)
1379 */
1380static void
1381g_virstor_orphan(struct g_consumer *cp)
1382{
1383	struct g_virstor_softc *sc;
1384	struct g_virstor_component *comp;
1385	struct g_geom *gp;
1386
1387	g_topology_assert();
1388	gp = cp->geom;
1389	sc = gp->softc;
1390	if (sc == NULL)
1391		return;
1392
1393	comp = cp->private;
1394	KASSERT(comp != NULL, ("%s: No component in private part of consumer",
1395	    __func__));
1396	remove_component(sc, comp, FALSE);
1397	if (virstor_valid_components(sc) == 0)
1398		virstor_geom_destroy(sc, TRUE, FALSE);
1399}
1400
1401/*
1402 * Called to notify geom when it's been opened, and for what intent
1403 */
1404static int
1405g_virstor_access(struct g_provider *pp, int dr, int dw, int de)
1406{
1407	struct g_consumer *c;
1408	struct g_virstor_softc *sc;
1409	struct g_geom *gp;
1410	int error;
1411
1412	KASSERT(pp != NULL, ("%s: NULL provider", __func__));
1413	gp = pp->geom;
1414	KASSERT(gp != NULL, ("%s: NULL geom", __func__));
1415	sc = gp->softc;
1416
1417	if (sc == NULL) {
1418		/* It seems that .access can be called with negative dr,dw,dx
1419		 * in this case but I want to check for myself */
1420		LOG_MSG(LVL_WARNING, "access(%d, %d, %d) for %s",
1421		    dr, dw, de, pp->name);
1422		/* This should only happen when geom is withered so
1423		 * allow only negative requests */
1424		KASSERT(dr <= 0 && dw <= 0 && de <= 0,
1425		    ("%s: Positive access for %s", __func__, pp->name));
1426		if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0)
1427			LOG_MSG(LVL_DEBUG, "Device %s definitely destroyed",
1428			    pp->name);
1429		return (0);
1430	}
1431
1432	/* Grab an exclusive bit to propagate on our consumers on first open */
1433	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0)
1434		de++;
1435	/* ... drop it on close */
1436	if (pp->acr + dr == 0 && pp->acw + dw == 0 && pp->ace + de == 0) {
1437		de--;
1438		update_metadata(sc);	/* Writes statistical information */
1439	}
1440
1441	error = ENXIO;
1442	LIST_FOREACH(c, &gp->consumer, consumer) {
1443		KASSERT(c != NULL, ("%s: consumer is NULL", __func__));
1444		error = g_access(c, dr, dw, de);
1445		if (error != 0) {
1446			struct g_consumer *c2;
1447
1448			/* Backout earlier changes */
1449			LIST_FOREACH(c2, &gp->consumer, consumer) {
1450				if (c2 == c) /* all eariler components fixed */
1451					return (error);
1452				g_access(c2, -dr, -dw, -de);
1453			}
1454		}
1455	}
1456
1457	return (error);
1458}
1459
1460/*
1461 * Generate XML dump of current state
1462 */
1463static void
1464g_virstor_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1465    struct g_consumer *cp, struct g_provider *pp)
1466{
1467	struct g_virstor_softc *sc;
1468
1469	g_topology_assert();
1470	sc = gp->softc;
1471
1472	if (sc == NULL || pp != NULL)
1473		return;
1474
1475	if (cp != NULL) {
1476		/* For each component */
1477		struct g_virstor_component *comp;
1478
1479		comp = cp->private;
1480		if (comp == NULL)
1481			return;
1482		sbuf_printf(sb, "%s<ComponentIndex>%u</ComponentIndex>\n",
1483		    indent, comp->index);
1484		sbuf_printf(sb, "%s<ChunkCount>%u</ChunkCount>\n",
1485		    indent, comp->chunk_count);
1486		sbuf_printf(sb, "%s<ChunksUsed>%u</ChunksUsed>\n",
1487		    indent, comp->chunk_next);
1488		sbuf_printf(sb, "%s<ChunksReserved>%u</ChunksReserved>\n",
1489		    indent, comp->chunk_reserved);
1490		sbuf_printf(sb, "%s<StorageFree>%u%%</StorageFree>\n",
1491		    indent,
1492		    comp->chunk_next > 0 ? 100 -
1493		    ((comp->chunk_next + comp->chunk_reserved) * 100) /
1494		    comp->chunk_count : 100);
1495	} else {
1496		/* For the whole thing */
1497		u_int count, used, i;
1498		off_t size;
1499
1500		count = used = size = 0;
1501		for (i = 0; i < sc->n_components; i++) {
1502			if (sc->components[i].gcons != NULL) {
1503				count += sc->components[i].chunk_count;
1504				used += sc->components[i].chunk_next +
1505				    sc->components[i].chunk_reserved;
1506				size += sc->components[i].gcons->
1507				    provider->mediasize;
1508			}
1509		}
1510
1511		sbuf_printf(sb, "%s<Status>"
1512		    "Components=%u, Online=%u</Status>\n", indent,
1513		    sc->n_components, virstor_valid_components(sc));
1514		sbuf_printf(sb, "%s<State>%u%% physical free</State>\n",
1515		    indent, 100-(used * 100) / count);
1516		sbuf_printf(sb, "%s<ChunkSize>%zu</ChunkSize>\n", indent,
1517		    sc->chunk_size);
1518		sbuf_printf(sb, "%s<PhysicalFree>%u%%</PhysicalFree>\n",
1519		    indent, used > 0 ? 100 - (used * 100) / count : 100);
1520		sbuf_printf(sb, "%s<ChunkPhysicalCount>%u</ChunkPhysicalCount>\n",
1521		    indent, count);
1522		sbuf_printf(sb, "%s<ChunkVirtualCount>%zu</ChunkVirtualCount>\n",
1523		    indent, sc->chunk_count);
1524		sbuf_printf(sb, "%s<PhysicalBacking>%zu%%</PhysicalBacking>\n",
1525		    indent,
1526		    (count * 100) / sc->chunk_count);
1527		sbuf_printf(sb, "%s<PhysicalBackingSize>%jd</PhysicalBackingSize>\n",
1528		    indent, size);
1529		sbuf_printf(sb, "%s<VirtualSize>%jd</VirtualSize>\n", indent,
1530		    sc->virsize);
1531	}
1532}
1533
1534/*
1535 * GEOM .done handler
1536 * Can't use standard handler because one requested IO may
1537 * fork into additional data IOs
1538 */
1539static void
1540g_virstor_done(struct bio *b)
1541{
1542	struct g_virstor_softc *sc;
1543	struct bio *parent_b;
1544
1545	parent_b = b->bio_parent;
1546	sc = parent_b->bio_to->geom->softc;
1547
1548	if (b->bio_error != 0) {
1549		LOG_MSG(LVL_ERROR, "Error %d for offset=%ju, length=%ju, %s",
1550		    b->bio_error, b->bio_offset, b->bio_length,
1551		    b->bio_to->name);
1552		if (parent_b->bio_error == 0)
1553			parent_b->bio_error = b->bio_error;
1554	}
1555
1556	parent_b->bio_inbed++;
1557	parent_b->bio_completed += b->bio_completed;
1558
1559	if (parent_b->bio_children == parent_b->bio_inbed) {
1560		parent_b->bio_completed = parent_b->bio_length;
1561		g_io_deliver(parent_b, parent_b->bio_error);
1562	}
1563	g_destroy_bio(b);
1564}
1565
1566/*
1567 * I/O starts here
1568 * Called in g_down thread
1569 */
1570static void
1571g_virstor_start(struct bio *b)
1572{
1573	struct g_virstor_softc *sc;
1574	struct g_virstor_component *comp;
1575	struct bio *cb;
1576	struct g_provider *pp;
1577	char *addr;
1578	off_t offset, length;
1579	struct bio_queue_head bq;
1580	size_t chunk_size;	/* cached for convenience */
1581	u_int count;
1582
1583	pp = b->bio_to;
1584	sc = pp->geom->softc;
1585	KASSERT(sc != NULL, ("%s: no softc (error=%d, device=%s)", __func__,
1586	    b->bio_to->error, b->bio_to->name));
1587
1588	LOG_REQ(LVL_MOREDEBUG, b, "%s", __func__);
1589
1590	switch (b->bio_cmd) {
1591	case BIO_READ:
1592	case BIO_WRITE:
1593	case BIO_DELETE:
1594		break;
1595	default:
1596		g_io_deliver(b, EOPNOTSUPP);
1597		return;
1598	}
1599
1600	LOG_MSG(LVL_DEBUG2, "BIO arrived, size=%ju", b->bio_length);
1601	bioq_init(&bq);
1602
1603	chunk_size = sc->chunk_size;
1604	addr = b->bio_data;
1605	offset = b->bio_offset;	/* virtual offset and length */
1606	length = b->bio_length;
1607
1608	while (length > 0) {
1609		size_t chunk_index, in_chunk_offset, in_chunk_length;
1610		struct virstor_map_entry *me;
1611
1612		chunk_index = offset / chunk_size; /* round downwards */
1613		in_chunk_offset = offset % chunk_size;
1614		in_chunk_length = min(length, chunk_size - in_chunk_offset);
1615		LOG_MSG(LVL_DEBUG, "Mapped %s(%ju, %ju) to (%zu,%zu,%zu)",
1616		    b->bio_cmd == BIO_READ ? "R" : "W",
1617		    offset, length,
1618		    chunk_index, in_chunk_offset, in_chunk_length);
1619		me = &sc->map[chunk_index];
1620
1621		if (b->bio_cmd == BIO_READ || b->bio_cmd == BIO_DELETE) {
1622			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1623				/* Reads from unallocated chunks return zeroed
1624				 * buffers */
1625				if (b->bio_cmd == BIO_READ)
1626					bzero(addr, in_chunk_length);
1627			} else {
1628				comp = &sc->components[me->provider_no];
1629
1630				cb = g_clone_bio(b);
1631				if (cb == NULL) {
1632					bioq_dismantle(&bq);
1633					if (b->bio_error == 0)
1634						b->bio_error = ENOMEM;
1635					g_io_deliver(b, b->bio_error);
1636					return;
1637				}
1638				cb->bio_to = comp->gcons->provider;
1639				cb->bio_done = g_virstor_done;
1640				cb->bio_offset =
1641				    (off_t)me->provider_chunk * (off_t)chunk_size
1642				    + in_chunk_offset;
1643				cb->bio_length = in_chunk_length;
1644				cb->bio_data = addr;
1645				cb->bio_caller1 = comp;
1646				bioq_disksort(&bq, cb);
1647			}
1648		} else { /* handle BIO_WRITE */
1649			KASSERT(b->bio_cmd == BIO_WRITE,
1650			    ("%s: Unknown command %d", __func__,
1651			    b->bio_cmd));
1652
1653			if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0) {
1654				/* We have a virtual chunk, represented by
1655				 * the "me" entry, but it's not yet allocated
1656				 * (tied to) a physical chunk. So do it now. */
1657				struct virstor_map_entry *data_me;
1658				u_int phys_chunk, comp_no;
1659				off_t s_offset;
1660				int error;
1661
1662				error = allocate_chunk(sc, &comp, &comp_no,
1663				    &phys_chunk);
1664				if (error != 0) {
1665					/* We cannot allocate a physical chunk
1666					 * to satisfy this request, so we'll
1667					 * delay it to when we can...
1668					 * XXX: this will prevent the fs from
1669					 * being umounted! */
1670					struct g_virstor_bio_q *biq;
1671					biq = malloc(sizeof *biq, M_GVIRSTOR,
1672					    M_NOWAIT);
1673					if (biq == NULL) {
1674						bioq_dismantle(&bq);
1675						if (b->bio_error == 0)
1676							b->bio_error = ENOMEM;
1677						g_io_deliver(b, b->bio_error);
1678						return;
1679					}
1680					biq->bio = b;
1681					mtx_lock(&sc->delayed_bio_q_mtx);
1682					STAILQ_INSERT_TAIL(&sc->delayed_bio_q,
1683					    biq, linkage);
1684					mtx_unlock(&sc->delayed_bio_q_mtx);
1685					LOG_MSG(LVL_WARNING, "Delaying BIO "
1686					    "(size=%ju) until free physical "
1687					    "space can be found on %s",
1688					    b->bio_length,
1689					    sc->provider->name);
1690					return;
1691				}
1692				LOG_MSG(LVL_DEBUG, "Allocated chunk %u on %s "
1693				    "for %s",
1694				    phys_chunk,
1695				    comp->gcons->provider->name,
1696				    sc->provider->name);
1697
1698				me->provider_no = comp_no;
1699				me->provider_chunk = phys_chunk;
1700				me->flags |= VIRSTOR_MAP_ALLOCATED;
1701
1702				cb = g_clone_bio(b);
1703				if (cb == NULL) {
1704					me->flags &= ~VIRSTOR_MAP_ALLOCATED;
1705					me->provider_no = 0;
1706					me->provider_chunk = 0;
1707					bioq_dismantle(&bq);
1708					if (b->bio_error == 0)
1709						b->bio_error = ENOMEM;
1710					g_io_deliver(b, b->bio_error);
1711					return;
1712				}
1713
1714				/* The allocation table is stored continuously
1715				 * at the start of the drive. We need to
1716				 * calculate the offset of the sector that holds
1717				 * this map entry both on the drive and in the
1718				 * map array.
1719				 * sc_offset will end up pointing to the drive
1720				 * sector. */
1721				s_offset = chunk_index * sizeof *me;
1722				s_offset = (s_offset / sc->sectorsize) *
1723				    sc->sectorsize;
1724
1725				/* data_me points to map entry sector
1726				 * in memory (analoguos to offset) */
1727				data_me = &sc->map[(chunk_index /
1728				    sc->me_per_sector) * sc->me_per_sector];
1729
1730				/* Commit sector with map entry to storage */
1731				cb->bio_to = sc->components[0].gcons->provider;
1732				cb->bio_done = g_virstor_done;
1733				cb->bio_offset = s_offset;
1734				cb->bio_data = (char *)data_me;
1735				cb->bio_length = sc->sectorsize;
1736				cb->bio_caller1 = &sc->components[0];
1737				bioq_disksort(&bq, cb);
1738			}
1739
1740			comp = &sc->components[me->provider_no];
1741			cb = g_clone_bio(b);
1742			if (cb == NULL) {
1743				bioq_dismantle(&bq);
1744				if (b->bio_error == 0)
1745					b->bio_error = ENOMEM;
1746				g_io_deliver(b, b->bio_error);
1747				return;
1748			}
1749			/* Finally, handle the data */
1750			cb->bio_to = comp->gcons->provider;
1751			cb->bio_done = g_virstor_done;
1752			cb->bio_offset = (off_t)me->provider_chunk*(off_t)chunk_size +
1753			    in_chunk_offset;
1754			cb->bio_length = in_chunk_length;
1755			cb->bio_data = addr;
1756			cb->bio_caller1 = comp;
1757			bioq_disksort(&bq, cb);
1758		}
1759		addr += in_chunk_length;
1760		length -= in_chunk_length;
1761		offset += in_chunk_length;
1762	}
1763
1764	/* Fire off bio's here */
1765	count = 0;
1766	for (cb = bioq_first(&bq); cb != NULL; cb = bioq_first(&bq)) {
1767		bioq_remove(&bq, cb);
1768		LOG_REQ(LVL_MOREDEBUG, cb, "Firing request");
1769		comp = cb->bio_caller1;
1770		cb->bio_caller1 = NULL;
1771		LOG_MSG(LVL_DEBUG, " firing bio, offset=%ju, length=%ju",
1772		    cb->bio_offset, cb->bio_length);
1773		g_io_request(cb, comp->gcons);
1774		count++;
1775	}
1776	if (count == 0) { /* We handled everything locally */
1777		b->bio_completed = b->bio_length;
1778		g_io_deliver(b, 0);
1779	}
1780
1781}
1782
1783/*
1784 * Allocate a chunk from a physical provider. Returns physical component,
1785 * chunk index relative to the component and the component's index.
1786 */
1787static int
1788allocate_chunk(struct g_virstor_softc *sc, struct g_virstor_component **comp,
1789    u_int *comp_no_p, u_int *chunk)
1790{
1791	u_int comp_no;
1792
1793	KASSERT(sc->curr_component < sc->n_components,
1794	    ("%s: Invalid curr_component: %u",  __func__, sc->curr_component));
1795
1796	comp_no = sc->curr_component;
1797	*comp = &sc->components[comp_no];
1798	dump_component(*comp);
1799	if ((*comp)->chunk_next >= (*comp)->chunk_count) {
1800		/* This component is full. Allocate next component */
1801		if (comp_no >= sc->n_components-1) {
1802			LOG_MSG(LVL_ERROR, "All physical space allocated for %s",
1803			    sc->geom->name);
1804			return (-1);
1805		}
1806		(*comp)->flags &= ~VIRSTOR_PROVIDER_CURRENT;
1807		sc->curr_component = ++comp_no;
1808
1809		*comp = &sc->components[comp_no];
1810		if (comp_no >= sc->n_components - g_virstor_component_watermark-1)
1811			LOG_MSG(LVL_WARNING, "Device %s running out of components "
1812			    "(switching to %u/%u: %s)", sc->geom->name,
1813			    comp_no+1, sc->n_components,
1814			    (*comp)->gcons->provider->name);
1815		/* Take care not to overwrite reserved chunks */
1816		if ( (*comp)->chunk_reserved > 0 &&
1817		    (*comp)->chunk_next < (*comp)->chunk_reserved)
1818			(*comp)->chunk_next = (*comp)->chunk_reserved;
1819
1820		(*comp)->flags |=
1821		    VIRSTOR_PROVIDER_ALLOCATED | VIRSTOR_PROVIDER_CURRENT;
1822		dump_component(*comp);
1823		*comp_no_p = comp_no;
1824		*chunk = (*comp)->chunk_next++;
1825	} else {
1826		*comp_no_p = comp_no;
1827		*chunk = (*comp)->chunk_next++;
1828	}
1829	return (0);
1830}
1831
1832/* Dump a component */
1833static void
1834dump_component(struct g_virstor_component *comp)
1835{
1836
1837	if (g_virstor_debug < LVL_DEBUG2)
1838		return;
1839	printf("Component %d: %s\n", comp->index, comp->gcons->provider->name);
1840	printf("  chunk_count: %u\n", comp->chunk_count);
1841	printf("   chunk_next: %u\n", comp->chunk_next);
1842	printf("        flags: %u\n", comp->flags);
1843}
1844
1845#if 0
1846/* Dump a map entry */
1847static void
1848dump_me(struct virstor_map_entry *me, unsigned int nr)
1849{
1850	if (g_virstor_debug < LVL_DEBUG)
1851		return;
1852	printf("VIRT. CHUNK #%d: ", nr);
1853	if ((me->flags & VIRSTOR_MAP_ALLOCATED) == 0)
1854		printf("(unallocated)\n");
1855	else
1856		printf("allocated at provider %u, provider_chunk %u\n",
1857		    me->provider_no, me->provider_chunk);
1858}
1859#endif
1860
1861/*
1862 * Dismantle bio_queue and destroy its components
1863 */
1864static void
1865bioq_dismantle(struct bio_queue_head *bq)
1866{
1867	struct bio *b;
1868
1869	for (b = bioq_first(bq); b != NULL; b = bioq_first(bq)) {
1870		bioq_remove(bq, b);
1871		g_destroy_bio(b);
1872	}
1873}
1874
1875/*
1876 * The function that shouldn't be called.
1877 * When this is called, the stack is already garbled because of
1878 * argument mismatch. There's nothing to do now but panic, which is
1879 * accidentally the whole purpose of this function.
1880 * Motivation: to guard from accidentally calling geom methods when
1881 * they shouldn't be called. (see g_..._taste)
1882 */
1883static void
1884invalid_call(void)
1885{
1886	panic("invalid_call() has just been called. Something's fishy here.");
1887}
1888
1889DECLARE_GEOM_CLASS(g_virstor_class, g_virstor); /* Let there be light */
1890