Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*-
 * Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016  Spectra Logic Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * Authors: Justin T. Gibbs     (Spectra Logic Corporation)
 */

/**
 * \file zfsd.cc
 *
 * The ZFS daemon consumes kernel devdctl(4) event data via devd(8)'s
 * unix domain socket in order to react to system changes that impact
 * the function of ZFS storage pools.  The goal of this daemon is to
 * provide similar functionality to the Solaris ZFS Diagnostic Engine
 * (zfs-diagnosis), the Solaris ZFS fault handler (zfs-retire), and
 * the Solaris ZFS vdev insertion agent (zfs-mod sysevent handler).
 */

#include <sys/cdefs.h>
#include <sys/byteorder.h>
#include <sys/param.h>
#include <sys/fs/zfs.h>

#include <err.h>
#include <fcntl.h>
#include <libgeom.h>
#include <libutil.h>
#include <poll.h>
#include <syslog.h>

#include <libzfs.h>

#include <list>
#include <map>
#include <string>

#include <devdctl/guid.h>
#include <devdctl/event.h>
#include <devdctl/event_factory.h>
#include <devdctl/exception.h>
#include <devdctl/consumer.h>

#include "callout.h"
#include "vdev_iterator.h"
#include "zfsd_event.h"
#include "case_file.h"
#include "vdev.h"
#include "vdev_iterator.h"
#include "zfsd.h"
#include "zfsd_exception.h"
#include "zpool_list.h"

__FBSDID("$FreeBSD$");

/*================================== Macros ==================================*/
#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))

/*============================ Namespace Control =============================*/
using DevdCtl::Event;
using DevdCtl::EventFactory;
using DevdCtl::EventList;

/*================================ Global Data ===============================*/
int              g_debug = 0;
libzfs_handle_t *g_zfsHandle;

/*--------------------------------- ZfsDaemon --------------------------------*/
//- ZfsDaemon Static Private Data ----------------------------------------------
ZfsDaemon	    *ZfsDaemon::s_theZfsDaemon;
bool		     ZfsDaemon::s_logCaseFiles;
bool		     ZfsDaemon::s_terminateEventLoop;
char		     ZfsDaemon::s_pidFilePath[] = "/var/run/zfsd.pid";
pidfh		    *ZfsDaemon::s_pidFH;
int		     ZfsDaemon::s_signalPipeFD[2];
bool		     ZfsDaemon::s_systemRescanRequested(false);
EventFactory::Record ZfsDaemon::s_registryEntries[] =
{
	{ Event::NOTIFY, "GEOM",  &GeomEvent::Builder },
	{ Event::NOTIFY, "ZFS",   &ZfsEvent::Builder }
};

//- ZfsDaemon Static Public Methods --------------------------------------------
ZfsDaemon &
ZfsDaemon::Get()
{
	return (*s_theZfsDaemon);
}

void
ZfsDaemon::WakeEventLoop()
{
	write(s_signalPipeFD[1], "+", 1);
}

void
ZfsDaemon::RequestSystemRescan()
{
	s_systemRescanRequested = true;
	ZfsDaemon::WakeEventLoop();
}

void
ZfsDaemon::Run()
{
	ZfsDaemon daemon;

	while (s_terminateEventLoop == false) {

		try {
			daemon.DisconnectFromDevd();

			if (daemon.ConnectToDevd() == false) {
				sleep(30);
				continue;
			}

			daemon.DetectMissedEvents();

			daemon.EventLoop();

		} catch (const DevdCtl::Exception &exp) {
			exp.Log();
		}
	}

	daemon.DisconnectFromDevd();
}

//- ZfsDaemon Private Methods --------------------------------------------------
ZfsDaemon::ZfsDaemon()
 : Consumer(/*defBuilder*/NULL, s_registryEntries,
	    NUM_ELEMENTS(s_registryEntries))
{
	if (s_theZfsDaemon != NULL)
		errx(1, "Multiple ZfsDaemon instances created. Exiting");

	s_theZfsDaemon = this;

	if (pipe(s_signalPipeFD) != 0)
		errx(1, "Unable to allocate signal pipe. Exiting");

	if (fcntl(s_signalPipeFD[0], F_SETFL, O_NONBLOCK) == -1)
		errx(1, "Unable to set pipe as non-blocking. Exiting");

	if (fcntl(s_signalPipeFD[1], F_SETFL, O_NONBLOCK) == -1)
		errx(1, "Unable to set pipe as non-blocking. Exiting");

	signal(SIGHUP,  ZfsDaemon::RescanSignalHandler);
	signal(SIGINFO, ZfsDaemon::InfoSignalHandler);
	signal(SIGINT,  ZfsDaemon::QuitSignalHandler);
	signal(SIGTERM, ZfsDaemon::QuitSignalHandler);
	signal(SIGUSR1, ZfsDaemon::RescanSignalHandler);

	g_zfsHandle = libzfs_init();
	if (g_zfsHandle == NULL)
		errx(1, "Unable to initialize ZFS library. Exiting");

	Callout::Init();
	InitializeSyslog();
	OpenPIDFile();

	if (g_debug == 0)
		daemon(0, 0);

	UpdatePIDFile();
}

ZfsDaemon::~ZfsDaemon()
{
	PurgeCaseFiles();
	ClosePIDFile();
}

void
ZfsDaemon::PurgeCaseFiles()
{
	CaseFile::PurgeAll();
}

bool
ZfsDaemon::VdevAddCaseFile(Vdev &vdev, void *cbArg)
{
	if (vdev.State() != VDEV_STATE_HEALTHY)
		CaseFile::Create(vdev);

	return (/*break early*/false);
}

void
ZfsDaemon::BuildCaseFiles()
{
	ZpoolList zpl;
	ZpoolList::iterator pool;

	/* Add CaseFiles for vdevs with issues. */
	for (pool = zpl.begin(); pool != zpl.end(); pool++)
		VdevIterator(*pool).Each(VdevAddCaseFile, NULL);

	/* De-serialize any saved cases. */
	CaseFile::DeSerialize();

	/* Simulate config_sync events to force CaseFile reevaluation */
	for (pool = zpl.begin(); pool != zpl.end(); pool++) {
		char evString[160];
		Event *event;
		nvlist_t *config;
		uint64_t poolGUID;
		const char *poolname;

		poolname = zpool_get_name(*pool);
		config = zpool_get_config(*pool, NULL);
		if (config == NULL) {
			syslog(LOG_ERR, "ZFSDaemon::BuildCaseFiles: Could not "
			    "find pool config for pool %s", poolname);
			continue;
		}
		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
				     &poolGUID) != 0) {
			syslog(LOG_ERR, "ZFSDaemon::BuildCaseFiles: Could not "
			    "find pool guid for pool %s", poolname);
			continue;
		}

		
		snprintf(evString, 160, "!system=ZFS subsystem=ZFS "
		    "type=misc.fs.zfs.config_sync sub_type=synthesized "
		    "pool_name=%s pool_guid=%" PRIu64 "\n", poolname, poolGUID);
		event = Event::CreateEvent(GetFactory(), string(evString));
		if (event != NULL) {
			event->Process();
			delete event;
		}
	}
}

void
ZfsDaemon::RescanSystem()
{
        struct gmesh	  mesh;
        struct gclass	 *mp;
        struct ggeom	 *gp;
        struct gprovider *pp;
	int		  result;

        /*
	 * The devdctl system doesn't replay events for new consumers
	 * of the interface.  Emit manufactured DEVFS arrival events
	 * for any devices that already before we started or during
	 * periods where we've lost our connection to devd.
         */
	result = geom_gettree(&mesh);
	if (result != 0) {
		syslog(LOG_ERR, "ZfsDaemon::RescanSystem: "
		       "geom_gettree faild with error %d\n", result);
		return;
	}

	const string evStart("!system=DEVFS subsystem=CDEV type=CREATE "
			     "sub_type=synthesized cdev=");
        LIST_FOREACH(mp, &mesh.lg_class, lg_class) {
                LIST_FOREACH(gp, &mp->lg_geom, lg_geom) {
                        LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
				Event *event;

				string evString(evStart + pp->lg_name + "\n");
				event = Event::CreateEvent(GetFactory(),
							   evString);
				if (event != NULL) {
					if (event->Process())
						SaveEvent(*event);
					delete event;
				}
                        }
                }
	}
	geom_deletetree(&mesh);
}

void
ZfsDaemon::DetectMissedEvents()
{
	do {
		PurgeCaseFiles();

		/*
		 * Discard any events waiting for us.  We don't know
		 * if they still apply to the current state of the
		 * system.
		 */
		FlushEvents();

		BuildCaseFiles();

		/*
		 * If the system state has changed during our
		 * interrogation, start over.
		 */
	} while (s_terminateEventLoop == false && EventsPending());

	RescanSystem();
}

void
ZfsDaemon::EventLoop()
{
	while (s_terminateEventLoop == false) {
		struct pollfd fds[2];
		int	      result;

		if (s_logCaseFiles == true) {
			EventList::iterator event(m_unconsumedEvents.begin());
			s_logCaseFiles = false;
			CaseFile::LogAll();
			while (event != m_unconsumedEvents.end())
				(*event++)->Log(LOG_INFO);
		}

		Callout::ExpireCallouts();

		/* Wait for data. */
		fds[0].fd      = m_devdSockFD;
		fds[0].events  = POLLIN;
		fds[0].revents = 0;
		fds[1].fd      = s_signalPipeFD[0];
		fds[1].events  = POLLIN;
		fds[1].revents = 0;
		result = poll(fds, NUM_ELEMENTS(fds), /*timeout*/INFTIM);
		if (result == -1) {
			if (errno == EINTR)
				continue;
			else
				err(1, "Polling for devd events failed");
		} else if (result == 0) {
			errx(1, "Unexpected result of 0 from poll. Exiting");
		}

		if ((fds[0].revents & POLLIN) != 0)
			ProcessEvents();

		if ((fds[1].revents & POLLIN) != 0) {
			static char discardBuf[128];

			/*
			 * This pipe exists just to close the signal
			 * race.  Its contents are of no interest to
			 * us, but we must ensure that future signals
			 * have space in the pipe to write.
			 */
			while (read(s_signalPipeFD[0], discardBuf,
				    sizeof(discardBuf)) > 0)
				;
		}

		if (s_systemRescanRequested == true) {
			s_systemRescanRequested = false;
			syslog(LOG_INFO, "System Rescan request processed.");
			RescanSystem();
		}

		if ((fds[0].revents & POLLERR) != 0) {
			syslog(LOG_INFO, "POLLERROR detected on devd socket.");
			break;
		}

		if ((fds[0].revents & POLLHUP) != 0) {
			syslog(LOG_INFO, "POLLHUP detected on devd socket.");
			break;
		}
	}
}
//- ZfsDaemon staic Private Methods --------------------------------------------
void
ZfsDaemon::InfoSignalHandler(int)
{
	s_logCaseFiles = true;
	ZfsDaemon::WakeEventLoop();
}

void
ZfsDaemon::RescanSignalHandler(int)
{
	RequestSystemRescan();
}

void
ZfsDaemon::QuitSignalHandler(int)
{
	s_terminateEventLoop = true;
	ZfsDaemon::WakeEventLoop();
}

void
ZfsDaemon::OpenPIDFile()
{
	pid_t otherPID;

	s_pidFH = pidfile_open(s_pidFilePath, 0600, &otherPID);
	if (s_pidFH == NULL) {
		if (errno == EEXIST)
			errx(1, "already running as PID %d. Exiting", otherPID);
		warn("cannot open PID file");
	}
}

void
ZfsDaemon::UpdatePIDFile()
{
	if (s_pidFH != NULL)
		pidfile_write(s_pidFH);
}

void
ZfsDaemon::ClosePIDFile()
{
	if (s_pidFH != NULL)
		pidfile_remove(s_pidFH);
}

void
ZfsDaemon::InitializeSyslog()
{
	openlog("zfsd", LOG_NDELAY, LOG_DAEMON);
}