2 * Copyright (c) 2011, 2012, 2013, 2014, 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 * We keep case files for any leaf vdev that is not in the optimal state.
37 * However, we only serialize to disk those events that need to be preserved
38 * across reboots. For now, this is just a log of soft errors which we
39 * accumulate in order to mark a device as degraded.
41 #include <sys/cdefs.h>
44 #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"
72 #include "zfsd_exception.h"
73 #include "zpool_list.h"
75 __FBSDID("$FreeBSD$");
77 /*============================ Namespace Control =============================*/
81 using std::stringstream;
86 using DevdCtl::EventFactory;
87 using DevdCtl::EventList;
89 using DevdCtl::ParseException;
91 /*--------------------------------- CaseFile ---------------------------------*/
92 //- CaseFile Static Data -------------------------------------------------------
94 CaseFileList CaseFile::s_activeCases;
95 const string CaseFile::s_caseFilePath = "/var/db/zfsd/cases";
96 const timeval CaseFile::s_removeGracePeriod = { 60 /*sec*/, 0 /*usec*/};
98 //- CaseFile Static Public Methods ---------------------------------------------
100 CaseFile::Find(Guid poolGUID, Guid vdevGUID)
102 for (CaseFileList::iterator curCase = s_activeCases.begin();
103 curCase != s_activeCases.end(); curCase++) {
105 if (((*curCase)->PoolGUID() != poolGUID
106 && Guid::InvalidGuid() != poolGUID)
107 || (*curCase)->VdevGUID() != vdevGUID)
111 * We only carry one active case per-vdev.
119 CaseFile::Find(const string &physPath)
121 CaseFile *result = NULL;
123 for (CaseFileList::iterator curCase = s_activeCases.begin();
124 curCase != s_activeCases.end(); curCase++) {
126 if ((*curCase)->PhysicalPath() != physPath)
129 if (result != NULL) {
130 syslog(LOG_WARNING, "Multiple casefiles found for "
132 "This is most likely a bug in zfsd",
142 CaseFile::ReEvaluateByGuid(Guid poolGUID, const ZfsEvent &event)
144 CaseFileList::iterator casefile;
145 for (casefile = s_activeCases.begin(); casefile != s_activeCases.end();){
146 CaseFileList::iterator next = casefile;
148 if (poolGUID == (*casefile)->PoolGUID())
149 (*casefile)->ReEvaluate(event);
155 CaseFile::Create(Vdev &vdev)
157 CaseFile *activeCase;
159 activeCase = Find(vdev.PoolGUID(), vdev.GUID());
160 if (activeCase == NULL)
161 activeCase = new CaseFile(vdev);
163 return (*activeCase);
167 CaseFile::DeSerialize()
169 struct dirent **caseFiles;
171 int numCaseFiles(scandir(s_caseFilePath.c_str(), &caseFiles,
172 DeSerializeSelector, /*compar*/NULL));
174 if (numCaseFiles == -1)
176 if (numCaseFiles == 0) {
181 for (int i = 0; i < numCaseFiles; i++) {
183 DeSerializeFile(caseFiles[i]->d_name);
192 return (s_activeCases.empty());
198 for (CaseFileList::iterator curCase = s_activeCases.begin();
199 curCase != s_activeCases.end(); curCase++)
207 * Serialize casefiles before deleting them so that they can be reread
208 * and revalidated during BuildCaseFiles.
209 * CaseFiles remove themselves from this list on destruction.
211 while (s_activeCases.size() != 0) {
212 CaseFile *casefile = s_activeCases.front();
213 casefile->Serialize();
219 //- CaseFile Public Methods ----------------------------------------------------
221 CaseFile::RefreshVdevState()
223 ZpoolList zpl(ZpoolList::ZpoolByGUID, &m_poolGUID);
224 zpool_handle_t *casePool(zpl.empty() ? NULL : zpl.front());
225 if (casePool == NULL)
228 Vdev vd(casePool, CaseVdev(casePool));
229 if (vd.DoesNotExist())
232 m_vdevState = vd.State();
233 m_vdevPhysPath = vd.PhysicalPath();
238 CaseFile::ReEvaluate(const string &devPath, const string &physPath, Vdev *vdev)
240 ZpoolList zpl(ZpoolList::ZpoolByGUID, &m_poolGUID);
241 zpool_handle_t *pool(zpl.empty() ? NULL : zpl.front());
243 if (pool == NULL || !RefreshVdevState()) {
245 * The pool or vdev for this case file is no longer
246 * part of the configuration. This can happen
247 * if we process a device arrival notification
248 * before seeing the ZFS configuration change
252 "CaseFile::ReEvaluate(%s,%s) Pool/Vdev unconfigured. "
254 PoolGUIDString().c_str(),
255 VdevGUIDString().c_str());
259 * Since this event was not used to close this
260 * case, do not report it as consumed.
262 return (/*consumed*/false);
265 if (VdevState() > VDEV_STATE_CANT_OPEN) {
267 * For now, newly discovered devices only help for
268 * devices that are missing. In the future, we might
269 * use a newly inserted spare to replace a degraded
272 syslog(LOG_INFO, "CaseFile::ReEvaluate(%s,%s): Pool/Vdev ignored",
273 PoolGUIDString().c_str(), VdevGUIDString().c_str());
274 return (/*consumed*/false);
278 && ( vdev->PoolGUID() == m_poolGUID
279 || vdev->PoolGUID() == Guid::InvalidGuid())
280 && vdev->GUID() == m_vdevGUID) {
282 zpool_vdev_online(pool, vdev->GUIDString().c_str(),
283 ZFS_ONLINE_CHECKREMOVE | ZFS_ONLINE_UNSPARE,
285 syslog(LOG_INFO, "Onlined vdev(%s/%s:%s). State now %s.\n",
286 zpool_get_name(pool), vdev->GUIDString().c_str(),
288 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
291 * Check the vdev state post the online action to see
292 * if we can retire this case.
296 return (/*consumed*/true);
300 * If the auto-replace policy is enabled, and we have physical
301 * path information, try a physical path replacement.
303 if (zpool_get_prop_int(pool, ZPOOL_PROP_AUTOREPLACE, NULL) == 0) {
305 "CaseFile(%s:%s:%s): AutoReplace not set. "
306 "Ignoring device insertion.\n",
307 PoolGUIDString().c_str(),
308 VdevGUIDString().c_str(),
309 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
310 return (/*consumed*/false);
313 if (PhysicalPath().empty()) {
315 "CaseFile(%s:%s:%s): No physical path information. "
316 "Ignoring device insertion.\n",
317 PoolGUIDString().c_str(),
318 VdevGUIDString().c_str(),
319 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
320 return (/*consumed*/false);
323 if (physPath != PhysicalPath()) {
325 "CaseFile(%s:%s:%s): Physical path mismatch. "
326 "Ignoring device insertion.\n",
327 PoolGUIDString().c_str(),
328 VdevGUIDString().c_str(),
329 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
330 return (/*consumed*/false);
333 /* Write a label on the newly inserted disk. */
334 if (zpool_label_disk(g_zfsHandle, pool, devPath.c_str()) != 0) {
336 "Replace vdev(%s/%s) by physical path (label): %s: %s\n",
337 zpool_get_name(pool), VdevGUIDString().c_str(),
338 libzfs_error_action(g_zfsHandle),
339 libzfs_error_description(g_zfsHandle));
340 return (/*consumed*/false);
343 syslog(LOG_INFO, "CaseFile::ReEvaluate(%s/%s): Replacing with %s",
344 PoolGUIDString().c_str(), VdevGUIDString().c_str(),
346 return (Replace(VDEV_TYPE_DISK, devPath.c_str(), /*isspare*/false));
350 CaseFile::ReEvaluate(const ZfsEvent &event)
352 bool consumed(false);
354 if (event.Value("type") == "misc.fs.zfs.vdev_remove") {
356 * The Vdev we represent has been removed from the
357 * configuration. This case is no longer of value.
361 return (/*consumed*/true);
362 } else if (event.Value("type") == "misc.fs.zfs.pool_destroy") {
363 /* This Pool has been destroyed. Discard the case */
366 return (/*consumed*/true);
367 } else if (event.Value("type") == "misc.fs.zfs.config_sync") {
369 if (VdevState() < VDEV_STATE_HEALTHY)
370 consumed = ActivateSpare();
374 if (event.Value("class") == "resource.fs.zfs.removed") {
375 bool spare_activated;
377 if (!RefreshVdevState()) {
379 * The pool or vdev for this case file is no longer
380 * part of the configuration. This can happen
381 * if we process a device arrival notification
382 * before seeing the ZFS configuration change
386 "CaseFile::ReEvaluate(%s,%s) Pool/Vdev "
387 "unconfigured. Closing\n",
388 PoolGUIDString().c_str(),
389 VdevGUIDString().c_str());
391 * Close the case now so we won't waste cycles in the
397 * Since this event was not used to close this
398 * case, do not report it as consumed.
400 return (/*consumed*/false);
404 * Discard any tentative I/O error events for
405 * this case. They were most likely caused by the
406 * hot-unplug of this device.
408 PurgeTentativeEvents();
410 /* Try to activate spares if they are available */
411 spare_activated = ActivateSpare();
414 * Rescan the drives in the system to see if a recent
415 * drive arrival can be used to solve this case.
417 ZfsDaemon::RequestSystemRescan();
420 * Consume the event if we successfully activated a spare.
421 * Otherwise, leave it in the unconsumed events list so that the
422 * future addition of a spare to this pool might be able to
425 consumed = spare_activated;
426 } else if (event.Value("class") == "resource.fs.zfs.statechange") {
429 * If this vdev is DEGRADED, FAULTED, or UNAVAIL, try to
430 * activate a hotspare. Otherwise, ignore the event
432 if (VdevState() == VDEV_STATE_FAULTED ||
433 VdevState() == VDEV_STATE_DEGRADED ||
434 VdevState() == VDEV_STATE_CANT_OPEN)
435 (void) ActivateSpare();
438 else if (event.Value("class") == "ereport.fs.zfs.io" ||
439 event.Value("class") == "ereport.fs.zfs.checksum") {
441 m_tentativeEvents.push_front(event.DeepCopy());
442 RegisterCallout(event);
446 bool closed(CloseIfSolved());
448 return (consumed || closed);
451 /* Find a Vdev containing the vdev with the given GUID */
453 find_parent(nvlist_t *pool_config, nvlist_t *config, DevdCtl::Guid child_guid)
455 nvlist_t **vdevChildren;
457 unsigned ch, numChildren;
459 error = nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
460 &vdevChildren, &numChildren);
462 if (error != 0 || numChildren == 0)
465 for (ch = 0; ch < numChildren; ch++) {
467 Vdev vdev(pool_config, vdevChildren[ch]);
469 if (vdev.GUID() == child_guid)
472 result = find_parent(pool_config, vdevChildren[ch], child_guid);
481 CaseFile::ActivateSpare() {
482 nvlist_t *config, *nvroot, *parent_config;
484 char *devPath, *vdev_type;
485 const char *poolname;
489 ZpoolList zpl(ZpoolList::ZpoolByGUID, &m_poolGUID);
490 zpool_handle_t *zhp(zpl.empty() ? NULL : zpl.front());
492 syslog(LOG_ERR, "CaseFile::ActivateSpare: Could not find pool "
493 "for pool_guid %" PRIu64".", (uint64_t)m_poolGUID);
496 poolname = zpool_get_name(zhp);
497 config = zpool_get_config(zhp, NULL);
498 if (config == NULL) {
499 syslog(LOG_ERR, "CaseFile::ActivateSpare: Could not find pool "
500 "config for pool %s", poolname);
503 error = nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot);
505 syslog(LOG_ERR, "CaseFile::ActivateSpare: Could not find vdev "
506 "tree for pool %s", poolname);
510 parent_config = find_parent(config, nvroot, m_vdevGUID);
511 if (parent_config != NULL) {
515 * Don't activate spares for members of a "replacing" vdev.
516 * They're already dealt with. Sparing them will just drag out
517 * the resilver process.
519 error = nvlist_lookup_string(parent_config,
520 ZPOOL_CONFIG_TYPE, &parent_type);
521 if (error == 0 && strcmp(parent_type, VDEV_TYPE_REPLACING) == 0)
526 nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
529 /* The pool has no spares configured */
530 syslog(LOG_INFO, "CaseFile::ActivateSpare: "
531 "No spares available for pool %s", poolname);
534 for (i = 0; i < nspares; i++) {
535 uint64_t *nvlist_array;
539 if (nvlist_lookup_uint64_array(spares[i],
540 ZPOOL_CONFIG_VDEV_STATS, &nvlist_array, &nstats) != 0) {
541 syslog(LOG_ERR, "CaseFile::ActivateSpare: Could not "
542 "find vdev stats for pool %s, spare %d",
546 vs = reinterpret_cast<vdev_stat_t *>(nvlist_array);
548 if ((vs->vs_aux != VDEV_AUX_SPARED)
549 && (vs->vs_state == VDEV_STATE_HEALTHY)) {
550 /* We found a usable spare */
556 /* No available spares were found */
560 error = nvlist_lookup_string(spares[i], ZPOOL_CONFIG_PATH, &devPath);
562 syslog(LOG_ERR, "CaseFile::ActivateSpare: Cannot determine "
563 "the path of pool %s, spare %d. Error %d",
568 error = nvlist_lookup_string(spares[i], ZPOOL_CONFIG_TYPE, &vdev_type);
570 syslog(LOG_ERR, "CaseFile::ActivateSpare: Cannot determine "
571 "the vdev type of pool %s, spare %d. Error %d",
576 return (Replace(vdev_type, devPath, /*isspare*/true));
580 CaseFile::RegisterCallout(const Event &event)
582 timeval now, countdown, elapsed, timestamp, zero, remaining;
584 gettimeofday(&now, 0);
585 timestamp = event.GetTimestamp();
586 timersub(&now, ×tamp, &elapsed);
587 timersub(&s_removeGracePeriod, &elapsed, &countdown);
589 * If countdown is <= zero, Reset the timer to the
590 * smallest positive time value instead
593 if (timercmp(&countdown, &zero, <=)) {
594 timerclear(&countdown);
595 countdown.tv_usec = 1;
598 remaining = m_tentativeTimer.TimeRemaining();
600 if (!m_tentativeTimer.IsPending()
601 || timercmp(&countdown, &remaining, <))
602 m_tentativeTimer.Reset(countdown, OnGracePeriodEnded, this);
607 CaseFile::CloseIfSolved()
610 && m_tentativeEvents.empty()) {
613 * We currently do not track or take actions on
614 * devices in the degraded or faulted state.
615 * Once we have support for spare pools, we'll
616 * retain these cases so that any spares added in
617 * the future can be applied to them.
619 switch (VdevState()) {
620 case VDEV_STATE_HEALTHY:
621 /* No need to keep cases for healthy vdevs */
624 case VDEV_STATE_REMOVED:
625 case VDEV_STATE_CANT_OPEN:
627 * Keep open. We may solve it with a newly inserted
630 case VDEV_STATE_FAULTED:
631 case VDEV_STATE_DEGRADED:
633 * Keep open. We may solve it with the future
634 * addition of a spare to the pool
636 case VDEV_STATE_UNKNOWN:
637 case VDEV_STATE_CLOSED:
638 case VDEV_STATE_OFFLINE:
640 * Keep open? This may not be the correct behavior,
641 * but it's what we've always done
647 * Re-serialize the case in order to remove any
648 * previous event data.
659 syslog(LOG_INFO, "CaseFile(%s,%s,%s)\n", PoolGUIDString().c_str(),
660 VdevGUIDString().c_str(), PhysicalPath().c_str());
661 syslog(LOG_INFO, "\tVdev State = %s\n",
662 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
663 if (m_tentativeEvents.size() != 0) {
664 syslog(LOG_INFO, "\t=== Tentative Events ===\n");
665 for (EventList::iterator event(m_tentativeEvents.begin());
666 event != m_tentativeEvents.end(); event++)
667 (*event)->Log(LOG_INFO);
669 if (m_events.size() != 0) {
670 syslog(LOG_INFO, "\t=== Events ===\n");
671 for (EventList::iterator event(m_events.begin());
672 event != m_events.end(); event++)
673 (*event)->Log(LOG_INFO);
677 //- CaseFile Static Protected Methods ------------------------------------------
679 CaseFile::OnGracePeriodEnded(void *arg)
681 CaseFile &casefile(*static_cast<CaseFile *>(arg));
683 casefile.OnGracePeriodEnded();
687 CaseFile::DeSerializeSelector(const struct dirent *dirEntry)
692 if (dirEntry->d_type == DT_REG
693 && sscanf(dirEntry->d_name, "pool_%" PRIu64 "_vdev_%" PRIu64 ".case",
694 &poolGUID, &vdevGUID) == 2)
700 CaseFile::DeSerializeFile(const char *fileName)
702 string fullName(s_caseFilePath + '/' + fileName);
703 CaseFile *existingCaseFile(NULL);
704 CaseFile *caseFile(NULL);
711 if (sscanf(fileName, "pool_%" PRIu64 "_vdev_%" PRIu64 ".case",
712 &poolGUID, &vdevGUID) != 2) {
713 throw ZfsdException("CaseFile::DeSerialize: "
714 "Unintelligible CaseFile filename %s.\n", fileName);
716 existingCaseFile = Find(Guid(poolGUID), Guid(vdevGUID));
717 if (existingCaseFile != NULL) {
719 * If the vdev is already degraded or faulted,
720 * there's no point in keeping the state around
721 * that we use to put a drive into the degraded
722 * state. However, if the vdev is simply missing,
723 * preserve the case data in the hopes that it will
726 caseFile = existingCaseFile;
727 vdev_state curState(caseFile->VdevState());
728 if (curState > VDEV_STATE_CANT_OPEN
729 && curState < VDEV_STATE_HEALTHY) {
734 ZpoolList zpl(ZpoolList::ZpoolByGUID, &poolGUID);
736 || (vdevConf = VdevIterator(zpl.front())
737 .Find(vdevGUID)) == NULL) {
739 * Either the pool no longer exists
740 * or this vdev is no longer a member of
743 unlink(fullName.c_str());
748 * Any vdev we find that does not have a case file
749 * must be in the healthy state and thus worthy of
750 * continued SERD data tracking.
752 caseFile = new CaseFile(Vdev(zpl.front(), vdevConf));
755 ifstream caseStream(fullName.c_str());
757 throw ZfsdException("CaseFile::DeSerialize: Unable to "
758 "read %s.\n", fileName);
760 caseFile->DeSerialize(caseStream);
761 } catch (const ParseException &exp) {
764 if (caseFile != existingCaseFile)
768 * Since we can't parse the file, unlink it so we don't
769 * trip over it again.
772 } catch (const ZfsdException &zfsException) {
775 if (caseFile != existingCaseFile)
780 //- CaseFile Protected Methods -------------------------------------------------
781 CaseFile::CaseFile(const Vdev &vdev)
782 : m_poolGUID(vdev.PoolGUID()),
783 m_vdevGUID(vdev.GUID()),
784 m_vdevState(vdev.State()),
785 m_vdevPhysPath(vdev.PhysicalPath())
787 stringstream guidString;
789 guidString << m_vdevGUID;
790 m_vdevGUIDString = guidString.str();
792 guidString << m_poolGUID;
793 m_poolGUIDString = guidString.str();
795 s_activeCases.push_back(this);
797 syslog(LOG_INFO, "Creating new CaseFile:\n");
801 CaseFile::~CaseFile()
804 PurgeTentativeEvents();
805 m_tentativeTimer.Stop();
806 s_activeCases.remove(this);
810 CaseFile::PurgeEvents()
812 for (EventList::iterator event(m_events.begin());
813 event != m_events.end(); event++)
820 CaseFile::PurgeTentativeEvents()
822 for (EventList::iterator event(m_tentativeEvents.begin());
823 event != m_tentativeEvents.end(); event++)
826 m_tentativeEvents.clear();
830 CaseFile::SerializeEvList(const EventList events, int fd,
831 const char* prefix) const
835 for (EventList::const_iterator curEvent = events.begin();
836 curEvent != events.end(); curEvent++) {
837 const string &eventString((*curEvent)->GetEventString());
839 // TODO: replace many write(2) calls with a single writev(2)
841 write(fd, prefix, strlen(prefix));
842 write(fd, eventString.c_str(), eventString.length());
847 CaseFile::Serialize()
849 stringstream saveFile;
851 saveFile << setfill('0')
852 << s_caseFilePath << "/"
853 << "pool_" << PoolGUIDString()
854 << "_vdev_" << VdevGUIDString()
857 if (m_events.empty() && m_tentativeEvents.empty()) {
858 unlink(saveFile.str().c_str());
862 int fd(open(saveFile.str().c_str(), O_CREAT|O_TRUNC|O_WRONLY, 0644));
864 syslog(LOG_ERR, "CaseFile::Serialize: Unable to open %s.\n",
865 saveFile.str().c_str());
868 SerializeEvList(m_events, fd);
869 SerializeEvList(m_tentativeEvents, fd, "tentative ");
874 * XXX: This method assumes that events may not contain embedded newlines. If
875 * ever events can contain embedded newlines, then CaseFile must switch
876 * serialization formats
879 CaseFile::DeSerialize(ifstream &caseStream)
882 const EventFactory &factory(ZfsDaemon::Get().GetFactory());
884 caseStream >> std::noskipws >> std::ws;
885 while (caseStream.good()) {
888 * read the beginning of a line and check it for
889 * "tentative". If found, discard "tentative".
893 EventList* destEvents;
894 const string tentFlag("tentative ");
896 std::stringbuf lineBuf;
898 caseStream.get(lineBuf);
899 caseStream.ignore(); /*discard the newline character*/
900 line = lineBuf.str();
901 if (line.compare(0, tentFlag.size(), tentFlag) == 0) {
902 /* Discard "tentative" */
903 line.erase(0, tentFlag.size());
904 destEvents = &m_tentativeEvents;
906 destEvents = &m_events;
908 Event *event(Event::CreateEvent(factory, line));
910 destEvents->push_back(event);
911 RegisterCallout(*event);
920 * This case is no longer relevant. Clean up our
921 * serialization file, and delete the case.
923 syslog(LOG_INFO, "CaseFile(%s,%s) closed - State %s\n",
924 PoolGUIDString().c_str(), VdevGUIDString().c_str(),
925 zpool_state_to_name(VdevState(), VDEV_AUX_NONE));
928 * Serialization of a Case with no event data, clears the
929 * Serialization data for that event.
938 CaseFile::OnGracePeriodEnded()
940 bool should_fault, should_degrade;
941 ZpoolList zpl(ZpoolList::ZpoolByGUID, &m_poolGUID);
942 zpool_handle_t *zhp(zpl.empty() ? NULL : zpl.front());
944 m_events.splice(m_events.begin(), m_tentativeEvents);
945 should_fault = ShouldFault();
946 should_degrade = ShouldDegrade();
948 if (should_fault || should_degrade) {
950 || (VdevIterator(zhp).Find(m_vdevGUID)) == NULL) {
952 * Either the pool no longer exists
953 * or this vdev is no longer a member of
962 /* A fault condition has priority over a degrade condition */
964 /* Fault the vdev and close the case. */
965 if (zpool_vdev_fault(zhp, (uint64_t)m_vdevGUID,
966 VDEV_AUX_ERR_EXCEEDED) == 0) {
967 syslog(LOG_INFO, "Faulting vdev(%s/%s)",
968 PoolGUIDString().c_str(),
969 VdevGUIDString().c_str());
974 syslog(LOG_ERR, "Fault vdev(%s/%s): %s: %s\n",
975 PoolGUIDString().c_str(),
976 VdevGUIDString().c_str(),
977 libzfs_error_action(g_zfsHandle),
978 libzfs_error_description(g_zfsHandle));
981 else if (ShouldDegrade()) {
982 /* Degrade the vdev and close the case. */
983 if (zpool_vdev_degrade(zhp, (uint64_t)m_vdevGUID,
984 VDEV_AUX_ERR_EXCEEDED) == 0) {
985 syslog(LOG_INFO, "Degrading vdev(%s/%s)",
986 PoolGUIDString().c_str(),
987 VdevGUIDString().c_str());
992 syslog(LOG_ERR, "Degrade vdev(%s/%s): %s: %s\n",
993 PoolGUIDString().c_str(),
994 VdevGUIDString().c_str(),
995 libzfs_error_action(g_zfsHandle),
996 libzfs_error_description(g_zfsHandle));
1003 CaseFile::BeingReplacedBy(zpool_handle_t *zhp) {
1004 Vdev vd(zhp, CaseVdev(zhp));
1005 std::list<Vdev> children;
1006 std::list<Vdev>::iterator children_it;
1008 Vdev parent(vd.Parent());
1009 Vdev replacing(NonexistentVdev);
1012 * To determine whether we are being replaced by another spare that
1013 * is still working, then make sure that it is currently spared and
1014 * that the spare is either resilvering or healthy. If any of these
1015 * conditions fail, then we are not being replaced by a spare.
1017 * If the spare is healthy, then the case file should be closed very
1018 * soon after this check.
1020 if (parent.DoesNotExist()
1021 || parent.Name(zhp, /*verbose*/false) != "spare")
1022 return (NonexistentVdev);
1024 children = parent.Children();
1025 children_it = children.begin();
1026 for (;children_it != children.end(); children_it++) {
1027 Vdev child = *children_it;
1029 /* Skip our vdev. */
1030 if (child.GUID() == VdevGUID())
1033 * Accept the first child that doesn't match our GUID, or
1034 * any resilvering/healthy device if one exists.
1036 if (replacing.DoesNotExist() || child.IsResilvering()
1037 || child.State() == VDEV_STATE_HEALTHY)
1045 CaseFile::Replace(const char* vdev_type, const char* path, bool isspare) {
1046 nvlist_t *nvroot, *newvd;
1047 const char *poolname;
1048 string oldstr(VdevGUIDString());
1051 /* Figure out what pool we're working on */
1052 ZpoolList zpl(ZpoolList::ZpoolByGUID, &m_poolGUID);
1053 zpool_handle_t *zhp(zpl.empty() ? NULL : zpl.front());
1055 syslog(LOG_ERR, "CaseFile::Replace: could not find pool for "
1056 "pool_guid %" PRIu64 ".", (uint64_t)m_poolGUID);
1059 poolname = zpool_get_name(zhp);
1060 Vdev vd(zhp, CaseVdev(zhp));
1061 Vdev replaced(BeingReplacedBy(zhp));
1063 if (isspare && !vd.IsSpare() && !replaced.DoesNotExist()) {
1064 /* If we are already being replaced by a working spare, pass. */
1065 if (replaced.IsResilvering()
1066 || replaced.State() == VDEV_STATE_HEALTHY) {
1067 syslog(LOG_INFO, "CaseFile::Replace(%s->%s): already "
1068 "replaced", VdevGUIDString().c_str(), path);
1069 return (/*consumed*/false);
1072 * If we have already been replaced by a spare, but that spare
1073 * is broken, we must spare the spare, not the original device.
1075 oldstr = replaced.GUIDString();
1076 syslog(LOG_INFO, "CaseFile::Replace(%s->%s): sparing "
1077 "broken spare %s instead", VdevGUIDString().c_str(),
1078 path, oldstr.c_str());
1082 * Build a root vdev/leaf vdev configuration suitable for
1083 * zpool_vdev_attach. Only enough data for the kernel to find
1084 * the device (i.e. type and disk device node path) are needed.
1089 if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0
1090 || nvlist_alloc(&newvd, NV_UNIQUE_NAME, 0) != 0) {
1091 syslog(LOG_ERR, "Replace vdev(%s/%s): Unable to allocate "
1092 "configuration data.", poolname, oldstr.c_str());
1094 nvlist_free(nvroot);
1097 if (nvlist_add_string(newvd, ZPOOL_CONFIG_TYPE, vdev_type) != 0
1098 || nvlist_add_string(newvd, ZPOOL_CONFIG_PATH, path) != 0
1099 || nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) != 0
1100 || nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1102 syslog(LOG_ERR, "Replace vdev(%s/%s): Unable to initialize "
1103 "configuration data.", poolname, oldstr.c_str());
1105 nvlist_free(nvroot);
1109 /* Data was copied when added to the root vdev. */
1112 retval = (zpool_vdev_attach(zhp, oldstr.c_str(), path, nvroot,
1113 /*replace*/B_TRUE) == 0);
1115 syslog(LOG_INFO, "Replacing vdev(%s/%s) with %s\n",
1116 poolname, oldstr.c_str(), path);
1118 syslog(LOG_ERR, "Replace vdev(%s/%s): %s: %s\n",
1119 poolname, oldstr.c_str(), libzfs_error_action(g_zfsHandle),
1120 libzfs_error_description(g_zfsHandle));
1121 nvlist_free(nvroot);
1126 /* Does the argument event refer to a checksum error? */
1128 IsChecksumEvent(const Event* const event)
1130 return ("ereport.fs.zfs.checksum" == event->Value("type"));
1133 /* Does the argument event refer to an IO error? */
1135 IsIOEvent(const Event* const event)
1137 return ("ereport.fs.zfs.io" == event->Value("type"));
1141 CaseFile::ShouldDegrade() const
1143 return (std::count_if(m_events.begin(), m_events.end(),
1144 IsChecksumEvent) > ZFS_DEGRADE_IO_COUNT);
1148 CaseFile::ShouldFault() const
1150 return (std::count_if(m_events.begin(), m_events.end(),
1151 IsIOEvent) > ZFS_DEGRADE_IO_COUNT);
1155 CaseFile::CaseVdev(zpool_handle_t *zhp) const
1157 return (VdevIterator(zhp).Find(VdevGUID()));