2 * Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016 Spectra Logic Corporation
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions, and the following disclaimer,
10 * without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 * substantially similar to the "NO WARRANTY" disclaimer below
13 * ("Disclaimer") and any redistribution must be conditioned upon
14 * including a substantially similar Disclaimer requirement for further
15 * binary redistribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGES.
30 * Authors: Justin T. Gibbs (Spectra Logic Corporation)
36 * The ZFS daemon consumes kernel devdctl(4) event data via devd(8)'s
37 * unix domain socket in order to react to system changes that impact
38 * the function of ZFS storage pools. The goal of this daemon is to
39 * provide similar functionality to the Solaris ZFS Diagnostic Engine
40 * (zfs-diagnosis), the Solaris ZFS fault handler (zfs-retire), and
41 * the Solaris ZFS vdev insertion agent (zfs-mod sysevent handler).
44 #include <sys/cdefs.h>
45 #include <sys/param.h>
46 #include <sys/fs/zfs.h>
60 #include <devdctl/guid.h>
61 #include <devdctl/event.h>
62 #include <devdctl/event_factory.h>
63 #include <devdctl/exception.h>
64 #include <devdctl/consumer.h>
67 #include "vdev_iterator.h"
68 #include "zfsd_event.h"
69 #include "case_file.h"
71 #include "vdev_iterator.h"
73 #include "zfsd_exception.h"
74 #include "zpool_list.h"
76 __FBSDID("$FreeBSD$");
78 /*================================== Macros ==================================*/
79 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
81 /*============================ Namespace Control =============================*/
83 using DevdCtl::EventFactory;
84 using DevdCtl::EventList;
86 /*================================ Global Data ===============================*/
88 libzfs_handle_t *g_zfsHandle;
90 /*--------------------------------- ZfsDaemon --------------------------------*/
91 //- ZfsDaemon Static Private Data ----------------------------------------------
92 ZfsDaemon *ZfsDaemon::s_theZfsDaemon;
93 bool ZfsDaemon::s_logCaseFiles;
94 bool ZfsDaemon::s_terminateEventLoop;
95 char ZfsDaemon::s_pidFilePath[] = "/var/run/zfsd.pid";
96 pidfh *ZfsDaemon::s_pidFH;
97 int ZfsDaemon::s_signalPipeFD[2];
98 bool ZfsDaemon::s_systemRescanRequested(false);
99 EventFactory::Record ZfsDaemon::s_registryEntries[] =
101 { Event::NOTIFY, "GEOM", &GeomEvent::Builder },
102 { Event::NOTIFY, "ZFS", &ZfsEvent::Builder }
105 //- ZfsDaemon Static Public Methods --------------------------------------------
109 return (*s_theZfsDaemon);
113 ZfsDaemon::WakeEventLoop()
115 write(s_signalPipeFD[1], "+", 1);
119 ZfsDaemon::RequestSystemRescan()
121 s_systemRescanRequested = true;
122 ZfsDaemon::WakeEventLoop();
130 while (s_terminateEventLoop == false) {
133 daemon.DisconnectFromDevd();
135 if (daemon.ConnectToDevd() == false) {
140 daemon.DetectMissedEvents();
144 } catch (const DevdCtl::Exception &exp) {
149 daemon.DisconnectFromDevd();
152 //- ZfsDaemon Private Methods --------------------------------------------------
153 ZfsDaemon::ZfsDaemon()
154 : Consumer(/*defBuilder*/NULL, s_registryEntries,
155 NUM_ELEMENTS(s_registryEntries))
157 if (s_theZfsDaemon != NULL)
158 errx(1, "Multiple ZfsDaemon instances created. Exiting");
160 s_theZfsDaemon = this;
162 if (pipe(s_signalPipeFD) != 0)
163 errx(1, "Unable to allocate signal pipe. Exiting");
165 if (fcntl(s_signalPipeFD[0], F_SETFL, O_NONBLOCK) == -1)
166 errx(1, "Unable to set pipe as non-blocking. Exiting");
168 if (fcntl(s_signalPipeFD[1], F_SETFL, O_NONBLOCK) == -1)
169 errx(1, "Unable to set pipe as non-blocking. Exiting");
171 signal(SIGHUP, ZfsDaemon::RescanSignalHandler);
172 signal(SIGINFO, ZfsDaemon::InfoSignalHandler);
173 signal(SIGINT, ZfsDaemon::QuitSignalHandler);
174 signal(SIGTERM, ZfsDaemon::QuitSignalHandler);
175 signal(SIGUSR1, ZfsDaemon::RescanSignalHandler);
177 g_zfsHandle = libzfs_init();
178 if (g_zfsHandle == NULL)
179 errx(1, "Unable to initialize ZFS library. Exiting");
191 ZfsDaemon::~ZfsDaemon()
198 ZfsDaemon::PurgeCaseFiles()
200 CaseFile::PurgeAll();
204 ZfsDaemon::VdevAddCaseFile(Vdev &vdev, void *cbArg)
206 if (vdev.State() != VDEV_STATE_HEALTHY)
207 CaseFile::Create(vdev);
209 return (/*break early*/false);
213 ZfsDaemon::BuildCaseFiles()
216 ZpoolList::iterator pool;
218 /* Add CaseFiles for vdevs with issues. */
219 for (pool = zpl.begin(); pool != zpl.end(); pool++)
220 VdevIterator(*pool).Each(VdevAddCaseFile, NULL);
222 /* De-serialize any saved cases. */
223 CaseFile::DeSerialize();
225 /* Simulate config_sync events to force CaseFile reevaluation */
226 for (pool = zpl.begin(); pool != zpl.end(); pool++) {
231 const char *poolname;
233 poolname = zpool_get_name(*pool);
234 config = zpool_get_config(*pool, NULL);
235 if (config == NULL) {
236 syslog(LOG_ERR, "ZFSDaemon::BuildCaseFiles: Could not "
237 "find pool config for pool %s", poolname);
240 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
242 syslog(LOG_ERR, "ZFSDaemon::BuildCaseFiles: Could not "
243 "find pool guid for pool %s", poolname);
248 snprintf(evString, 160, "!system=ZFS subsystem=ZFS "
249 "type=misc.fs.zfs.config_sync sub_type=synthesized "
250 "pool_name=%s pool_guid=%" PRIu64 "\n", poolname, poolGUID);
251 event = Event::CreateEvent(GetFactory(), string(evString));
260 ZfsDaemon::RescanSystem()
265 struct gprovider *pp;
269 * The devdctl system doesn't replay events for new consumers
270 * of the interface. Emit manufactured DEVFS arrival events
271 * for any devices that already before we started or during
272 * periods where we've lost our connection to devd.
274 result = geom_gettree(&mesh);
276 syslog(LOG_ERR, "ZfsDaemon::RescanSystem: "
277 "geom_gettree faild with error %d\n", result);
281 const string evStart("!system=DEVFS subsystem=CDEV type=CREATE "
282 "sub_type=synthesized cdev=");
283 LIST_FOREACH(mp, &mesh.lg_class, lg_class) {
284 LIST_FOREACH(gp, &mp->lg_geom, lg_geom) {
285 LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
288 string evString(evStart + pp->lg_name + "\n");
289 event = Event::CreateEvent(GetFactory(),
292 if (event->Process())
299 geom_deletetree(&mesh);
303 ZfsDaemon::DetectMissedEvents()
309 * Discard any events waiting for us. We don't know
310 * if they still apply to the current state of the
318 * If the system state has changed during our
319 * interrogation, start over.
321 } while (s_terminateEventLoop == false && EventsPending());
327 ZfsDaemon::EventLoop()
329 while (s_terminateEventLoop == false) {
330 struct pollfd fds[2];
333 if (s_logCaseFiles == true) {
334 EventList::iterator event(m_unconsumedEvents.begin());
335 s_logCaseFiles = false;
337 while (event != m_unconsumedEvents.end())
338 (*event++)->Log(LOG_INFO);
341 Callout::ExpireCallouts();
344 fds[0].fd = m_devdSockFD;
345 fds[0].events = POLLIN;
347 fds[1].fd = s_signalPipeFD[0];
348 fds[1].events = POLLIN;
350 result = poll(fds, NUM_ELEMENTS(fds), /*timeout*/INFTIM);
355 err(1, "Polling for devd events failed");
356 } else if (result == 0) {
357 errx(1, "Unexpected result of 0 from poll. Exiting");
360 if ((fds[0].revents & POLLIN) != 0)
363 if ((fds[1].revents & POLLIN) != 0) {
364 static char discardBuf[128];
367 * This pipe exists just to close the signal
368 * race. Its contents are of no interest to
369 * us, but we must ensure that future signals
370 * have space in the pipe to write.
372 while (read(s_signalPipeFD[0], discardBuf,
373 sizeof(discardBuf)) > 0)
377 if (s_systemRescanRequested == true) {
378 s_systemRescanRequested = false;
379 syslog(LOG_INFO, "System Rescan request processed.");
383 if ((fds[0].revents & POLLERR) != 0) {
384 syslog(LOG_INFO, "POLLERROR detected on devd socket.");
388 if ((fds[0].revents & POLLHUP) != 0) {
389 syslog(LOG_INFO, "POLLHUP detected on devd socket.");
394 //- ZfsDaemon staic Private Methods --------------------------------------------
396 ZfsDaemon::InfoSignalHandler(int)
398 s_logCaseFiles = true;
399 ZfsDaemon::WakeEventLoop();
403 ZfsDaemon::RescanSignalHandler(int)
405 RequestSystemRescan();
409 ZfsDaemon::QuitSignalHandler(int)
411 s_terminateEventLoop = true;
412 ZfsDaemon::WakeEventLoop();
416 ZfsDaemon::OpenPIDFile()
420 s_pidFH = pidfile_open(s_pidFilePath, 0600, &otherPID);
421 if (s_pidFH == NULL) {
423 errx(1, "already running as PID %d. Exiting", otherPID);
424 warn("cannot open PID file");
429 ZfsDaemon::UpdatePIDFile()
432 pidfile_write(s_pidFH);
436 ZfsDaemon::ClosePIDFile()
439 pidfile_remove(s_pidFH);
443 ZfsDaemon::InitializeSyslog()
445 openlog("zfsd", LOG_NDELAY, LOG_DAEMON);