0f32dbc02384fc2a4668e88bcebe039c67e1c78a
[multipath-tools/.git] / libmultipath / uevent.c
1 /*
2  * uevent.c - trigger upon netlink uevents from the kernel
3  *
4  *      Only kernels from version 2.6.10* on provide the uevent netlink socket.
5  *      Until the libc-kernel-headers are updated, you need to compile with:
6  *
7  *        gcc -I /lib/modules/`uname -r`/build/include -o uevent_listen uevent_listen.c
8  *
9  * Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
10  *
11  *      This program is free software; you can redistribute it and/or modify it
12  *      under the terms of the GNU General Public License as published by the
13  *      Free Software Foundation version 2 of the License.
14  *
15  *      This program is distributed in the hope that it will be useful, but
16  *      WITHOUT ANY WARRANTY; without even the implied warranty of
17  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *      General Public License for more details.
19  *
20  *      You should have received a copy of the GNU General Public License along
21  *      with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #include <stdlib.h>
29 #include <stddef.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <sys/socket.h>
34 #include <sys/user.h>
35 #include <sys/un.h>
36 #include <poll.h>
37 #include <linux/types.h>
38 #include <linux/netlink.h>
39 #include <pthread.h>
40 #include <limits.h>
41 #include <sys/mman.h>
42 #include <libudev.h>
43 #include <errno.h>
44
45 #include "memory.h"
46 #include "debug.h"
47 #include "list.h"
48 #include "uevent.h"
49 #include "vector.h"
50
51 typedef int (uev_trigger)(struct uevent *, void * trigger_data);
52
53 pthread_t uevq_thr;
54 LIST_HEAD(uevq);
55 pthread_mutex_t uevq_lock = PTHREAD_MUTEX_INITIALIZER;
56 pthread_mutex_t *uevq_lockp = &uevq_lock;
57 pthread_cond_t uev_cond = PTHREAD_COND_INITIALIZER;
58 pthread_cond_t *uev_condp = &uev_cond;
59 uev_trigger *my_uev_trigger;
60 void * my_trigger_data;
61 int servicing_uev;
62
63 int is_uevent_busy(void)
64 {
65         int empty;
66
67         pthread_mutex_lock(uevq_lockp);
68         empty = list_empty(&uevq);
69         pthread_mutex_unlock(uevq_lockp);
70         return (!empty || servicing_uev);
71 }
72
73 struct uevent * alloc_uevent (void)
74 {
75         struct uevent *uev = MALLOC(sizeof(struct uevent));
76
77         if (uev)
78                 INIT_LIST_HEAD(&uev->node);
79
80         return uev;
81 }
82
83 void
84 setup_thread_attr(pthread_attr_t *attr, size_t stacksize, int detached)
85 {
86         if (pthread_attr_init(attr)) {
87                 fprintf(stderr, "can't initialize thread attr: %s\n",
88                         strerror(errno));
89                 exit(1);
90         }
91         if (stacksize < PTHREAD_STACK_MIN)
92                 stacksize = PTHREAD_STACK_MIN;
93
94         if (pthread_attr_setstacksize(attr, stacksize)) {
95                 fprintf(stderr, "can't set thread stack size to %lu: %s\n",
96                         (unsigned long)stacksize, strerror(errno));
97                 exit(1);
98         }
99         if (detached && pthread_attr_setdetachstate(attr,
100                                                     PTHREAD_CREATE_DETACHED)) {
101                 fprintf(stderr, "can't set thread to detached: %s\n",
102                         strerror(errno));
103                 exit(1);
104         }
105 }
106
107 /*
108  * Called with uevq_lockp held
109  */
110 void
111 service_uevq(struct list_head *tmpq)
112 {
113         struct uevent *uev, *tmp;
114
115         list_for_each_entry_safe(uev, tmp, tmpq, node) {
116                 list_del_init(&uev->node);
117
118                 if (my_uev_trigger && my_uev_trigger(uev, my_trigger_data))
119                         condlog(0, "uevent trigger error");
120
121                 if (uev->udev)
122                         udev_device_unref(uev->udev);
123                 FREE(uev);
124         }
125 }
126
127 static void uevent_cleanup(void *arg)
128 {
129         struct udev *udev = arg;
130
131         condlog(3, "Releasing uevent_listen() resources");
132         udev_unref(udev);
133 }
134
135 void
136 uevq_cleanup(struct list_head *tmpq)
137 {
138         struct uevent *uev, *tmp;
139
140         list_for_each_entry_safe(uev, tmp, tmpq, node) {
141                 list_del_init(&uev->node);
142                 FREE(uev);
143         }
144 }
145
146 /*
147  * Service the uevent queue.
148  */
149 int uevent_dispatch(int (*uev_trigger)(struct uevent *, void * trigger_data),
150                     void * trigger_data)
151 {
152         my_uev_trigger = uev_trigger;
153         my_trigger_data = trigger_data;
154
155         mlockall(MCL_CURRENT | MCL_FUTURE);
156
157         while (1) {
158                 LIST_HEAD(uevq_tmp);
159
160                 pthread_mutex_lock(uevq_lockp);
161                 servicing_uev = 0;
162                 /*
163                  * Condition signals are unreliable,
164                  * so make sure we only wait if we have to.
165                  */
166                 if (list_empty(&uevq)) {
167                         pthread_cond_wait(uev_condp, uevq_lockp);
168                 }
169                 servicing_uev = 1;
170                 list_splice_init(&uevq, &uevq_tmp);
171                 pthread_mutex_unlock(uevq_lockp);
172                 if (!my_uev_trigger)
173                         break;
174                 service_uevq(&uevq_tmp);
175         }
176         condlog(3, "Terminating uev service queue");
177         uevq_cleanup(&uevq);
178         return 0;
179 }
180
181 struct uevent *uevent_from_buffer(char *buf, ssize_t buflen)
182 {
183         struct uevent *uev;
184         char *buffer;
185         size_t bufpos;
186         int i;
187         char *pos;
188
189         uev = alloc_uevent();
190         if (!uev) {
191                 condlog(1, "lost uevent, oom");
192                 return NULL;
193         }
194
195         if ((size_t)buflen > sizeof(buf)-1)
196                 buflen = sizeof(buf)-1;
197
198         /*
199          * Copy the shared receive buffer contents to buffer private
200          * to this uevent so we can immediately reuse the shared buffer.
201          */
202         memcpy(uev->buffer, buf, HOTPLUG_BUFFER_SIZE + OBJECT_SIZE);
203         buffer = uev->buffer;
204         buffer[buflen] = '\0';
205
206         /* save start of payload */
207         bufpos = strlen(buffer) + 1;
208
209         /* action string */
210         uev->action = buffer;
211         pos = strchr(buffer, '@');
212         if (!pos) {
213                 condlog(3, "bad action string '%s'", buffer);
214                 FREE(uev);
215                 return NULL;
216         }
217         pos[0] = '\0';
218
219         /* sysfs path */
220         uev->devpath = &pos[1];
221
222         /* hotplug events have the environment attached - reconstruct envp[] */
223         for (i = 0; (bufpos < (size_t)buflen) && (i < HOTPLUG_NUM_ENVP-1); i++) {
224                 int keylen;
225                 char *key;
226
227                 key = &buffer[bufpos];
228                 keylen = strlen(key);
229                 uev->envp[i] = key;
230                 /* Filter out sequence number */
231                 if (strncmp(key, "SEQNUM=", 7) == 0) {
232                         char *eptr;
233
234                         uev->seqnum = strtoul(key + 7, &eptr, 10);
235                         if (eptr == key + 7)
236                                 uev->seqnum = -1;
237                 }
238                 bufpos += keylen + 1;
239         }
240         uev->envp[i] = NULL;
241
242         condlog(3, "uevent %ld '%s' from '%s'", uev->seqnum,
243                 uev->action, uev->devpath);
244         uev->kernel = strrchr(uev->devpath, '/');
245         if (uev->kernel)
246                 uev->kernel++;
247
248         /* print payload environment */
249         for (i = 0; uev->envp[i] != NULL; i++)
250                 condlog(5, "%s", uev->envp[i]);
251
252         return uev;
253 }
254
255 int failback_listen(void)
256 {
257         int sock;
258         struct sockaddr_nl snl;
259         struct sockaddr_un sun;
260         socklen_t addrlen;
261         int retval;
262         int rcvbufsz = 128*1024;
263         int rcvsz = 0;
264         int rcvszsz = sizeof(rcvsz);
265         unsigned int *prcvszsz = (unsigned int *)&rcvszsz;
266         const int feature_on = 1;
267         /*
268          * First check whether we have a udev socket
269          */
270         memset(&sun, 0x00, sizeof(struct sockaddr_un));
271         sun.sun_family = AF_LOCAL;
272         strcpy(&sun.sun_path[1], "/org/kernel/dm/multipath_event");
273         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(sun.sun_path+1) + 1;
274
275         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
276         if (sock >= 0) {
277
278                 condlog(3, "reading events from udev socket.");
279
280                 /* the bind takes care of ensuring only one copy running */
281                 retval = bind(sock, (struct sockaddr *) &sun, addrlen);
282                 if (retval < 0) {
283                         condlog(0, "bind failed, exit");
284                         goto exit;
285                 }
286
287                 /* enable receiving of the sender credentials */
288                 retval = setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
289                                     &feature_on, sizeof(feature_on));
290                 if (retval < 0) {
291                         condlog(0, "failed to enable credential passing, exit");
292                         goto exit;
293                 }
294
295         } else {
296                 /* Fallback to read kernel netlink events */
297                 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
298                 snl.nl_family = AF_NETLINK;
299                 snl.nl_pid = getpid();
300                 snl.nl_groups = 0x01;
301
302                 sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
303                 if (sock == -1) {
304                         condlog(0, "error getting socket, exit");
305                         return 1;
306                 }
307
308                 condlog(3, "reading events from kernel.");
309
310                 /*
311                  * try to avoid dropping uevents, even so, this is not a guarantee,
312                  * but it does help to change the netlink uevent socket's
313                  * receive buffer threshold from the default value of 106,496 to
314                  * the maximum value of 262,142.
315                  */
316                 retval = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbufsz,
317                                     sizeof(rcvbufsz));
318
319                 if (retval < 0) {
320                         condlog(0, "error setting receive buffer size for socket, exit");
321                         exit(1);
322                 }
323                 retval = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvsz, prcvszsz);
324                 if (retval < 0) {
325                         condlog(0, "error setting receive buffer size for socket, exit");
326                         exit(1);
327                 }
328                 condlog(3, "receive buffer size for socket is %u.", rcvsz);
329
330                 /* enable receiving of the sender credentials */
331                 if (setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
332                                &feature_on, sizeof(feature_on)) < 0) {
333                         condlog(0, "error on enabling credential passing for socket");
334                         exit(1);
335                 }
336
337                 retval = bind(sock, (struct sockaddr *) &snl,
338                               sizeof(struct sockaddr_nl));
339                 if (retval < 0) {
340                         condlog(0, "bind failed, exit");
341                         goto exit;
342                 }
343         }
344
345         while (1) {
346                 size_t bufpos;
347                 ssize_t buflen;
348                 struct uevent *uev;
349                 struct msghdr smsg;
350                 struct iovec iov;
351                 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
352                 struct cmsghdr *cmsg;
353                 struct ucred *cred;
354                 static char buf[HOTPLUG_BUFFER_SIZE + OBJECT_SIZE];
355
356                 memset(buf, 0x00, sizeof(buf));
357                 iov.iov_base = &buf;
358                 iov.iov_len = sizeof(buf);
359                 memset (&smsg, 0x00, sizeof(struct msghdr));
360                 smsg.msg_iov = &iov;
361                 smsg.msg_iovlen = 1;
362                 smsg.msg_control = cred_msg;
363                 smsg.msg_controllen = sizeof(cred_msg);
364
365                 buflen = recvmsg(sock, &smsg, 0);
366                 if (buflen < 0) {
367                         if (errno != EINTR)
368                                 condlog(0, "error receiving message, errno %d", errno);
369                         continue;
370                 }
371
372                 cmsg = CMSG_FIRSTHDR(&smsg);
373                 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
374                         condlog(3, "no sender credentials received, message ignored");
375                         continue;
376                 }
377
378                 cred = (struct ucred *)CMSG_DATA(cmsg);
379                 if (cred->uid != 0) {
380                         condlog(3, "sender uid=%d, message ignored", cred->uid);
381                         continue;
382                 }
383
384                 /* skip header */
385                 bufpos = strlen(buf) + 1;
386                 if (bufpos < sizeof("a@/d") || bufpos >= sizeof(buf)) {
387                         condlog(3, "invalid message length");
388                         continue;
389                 }
390
391                 /* check message header */
392                 if (strstr(buf, "@/") == NULL) {
393                         condlog(3, "unrecognized message header");
394                         continue;
395                 }
396                 if ((size_t)buflen > sizeof(buf)-1) {
397                         condlog(2, "buffer overflow for received uevent");
398                         buflen = sizeof(buf)-1;
399                 }
400
401                 uev = uevent_from_buffer(buf, buflen);
402                 if (!uev)
403                         continue;
404                 /*
405                  * Queue uevent and poke service pthread.
406                  */
407                 pthread_mutex_lock(uevq_lockp);
408                 list_add_tail(&uev->node, &uevq);
409                 pthread_cond_signal(uev_condp);
410                 pthread_mutex_unlock(uevq_lockp);
411         }
412
413 exit:
414         close(sock);
415         return 1;
416 }
417
418 struct uevent *uevent_from_udev_device(struct udev_device *dev)
419 {
420         struct uevent *uev;
421         int i = 0;
422         char *pos, *end;
423         struct udev_list_entry *list_entry;
424
425         uev = alloc_uevent();
426         if (!uev) {
427                 udev_device_unref(dev);
428                 condlog(1, "lost uevent, oom");
429                 return NULL;
430         }
431         pos = uev->buffer;
432         end = pos + HOTPLUG_BUFFER_SIZE + OBJECT_SIZE - 1;
433         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev)) {
434                 const char *name, *value;
435                 int bytes;
436
437                 name = udev_list_entry_get_name(list_entry);
438                 if (!name)
439                         name = "(null)";
440                 value = udev_list_entry_get_value(list_entry);
441                 if (!value)
442                         value = "(null)";
443                 bytes = snprintf(pos, end - pos, "%s=%s", name, value);
444                 if (pos + bytes >= end) {
445                         condlog(2, "buffer overflow for uevent");
446                         break;
447                 }
448                 uev->envp[i] = pos;
449                 pos += bytes;
450                 *pos = '\0';
451                 pos++;
452                 if (strcmp(name, "DEVPATH") == 0)
453                         uev->devpath = uev->envp[i] + 8;
454                 if (strcmp(name, "ACTION") == 0)
455                         uev->action = uev->envp[i] + 7;
456                 i++;
457                 if (i == HOTPLUG_NUM_ENVP - 1)
458                         break;
459         }
460         uev->udev = dev;
461         uev->envp[i] = NULL;
462
463         condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
464         uev->kernel = strrchr(uev->devpath, '/');
465         if (uev->kernel)
466                 uev->kernel++;
467
468         /* print payload environment */
469         for (i = 0; uev->envp[i] != NULL; i++)
470                 condlog(5, "%s", uev->envp[i]);
471         return uev;
472 }
473
474 int uevent_listen(struct udev *udev)
475 {
476         int err = 2;
477         struct udev_monitor *monitor = NULL;
478         int fd, socket_flags, events;
479         int need_failback = 1;
480         int timeout = 30;
481         LIST_HEAD(uevlisten_tmp);
482
483         /*
484          * Queue uevents for service by dedicated thread so that the uevent
485          * listening thread does not block on multipathd locks (vecs->lock)
486          * thereby not getting to empty the socket's receive buffer queue
487          * often enough.
488          */
489         if (!udev) {
490                 condlog(1, "no udev context");
491                 return 1;
492         }
493         udev_ref(udev);
494         pthread_cleanup_push(uevent_cleanup, udev);
495
496         monitor = udev_monitor_new_from_netlink(udev, "udev");
497         if (!monitor) {
498                 condlog(2, "failed to create udev monitor");
499                 goto out;
500         }
501 #ifdef LIBUDEV_API_RECVBUF
502         if (udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024))
503                 condlog(2, "failed to increase buffer size");
504 #endif
505         fd = udev_monitor_get_fd(monitor);
506         if (fd < 0) {
507                 condlog(2, "failed to get monitor fd");
508                 goto out;
509         }
510         socket_flags = fcntl(fd, F_GETFL);
511         if (socket_flags < 0) {
512                 condlog(2, "failed to get monitor socket flags : %s",
513                         strerror(errno));
514                 goto out;
515         }
516         if (fcntl(fd, F_SETFL, socket_flags & ~O_NONBLOCK) < 0) {
517                 condlog(2, "failed to set monitor socket flags : %s",
518                         strerror(errno));
519                 goto out;
520         }
521         err = udev_monitor_filter_add_match_subsystem_devtype(monitor, "block",
522                                                               NULL);
523         if (err)
524                 condlog(2, "failed to create filter : %s", strerror(-err));
525         err = udev_monitor_enable_receiving(monitor);
526         if (err) {
527                 condlog(2, "failed to enable receiving : %s", strerror(-err));
528                 goto out;
529         }
530
531         events = 0;
532         while (1) {
533                 struct uevent *uev;
534                 struct udev_device *dev;
535                 struct pollfd ev_poll;
536                 int poll_timeout;
537                 int fdcount;
538
539                 memset(&ev_poll, 0, sizeof(struct pollfd));
540                 ev_poll.fd = fd;
541                 ev_poll.events = POLLIN;
542                 poll_timeout = timeout * 1000;
543                 errno = 0;
544                 fdcount = poll(&ev_poll, 1, poll_timeout);
545                 if (fdcount && ev_poll.revents & POLLIN) {
546                         timeout = 0;
547                         dev = udev_monitor_receive_device(monitor);
548                         if (!dev) {
549                                 condlog(0, "failed getting udev device");
550                                 continue;
551                         }
552                         uev = uevent_from_udev_device(dev);
553                         if (!uev)
554                                 continue;
555                         list_add_tail(&uev->node, &uevlisten_tmp);
556                         events++;
557                         continue;
558                 }
559                 if (fdcount < 0) {
560                         if (errno == EINTR)
561                                 continue;
562
563                         condlog(0, "error receiving "
564                                 "uevent message: %m");
565                         err = -errno;
566                         break;
567                 }
568                 if (!list_empty(&uevlisten_tmp)) {
569                         /*
570                          * Queue uevents and poke service pthread.
571                          */
572                         condlog(3, "Forwarding %d uevents", events);
573                         pthread_mutex_lock(uevq_lockp);
574                         list_splice_tail_init(&uevlisten_tmp, &uevq);
575                         pthread_cond_signal(uev_condp);
576                         pthread_mutex_unlock(uevq_lockp);
577                         events = 0;
578                 }
579                 timeout = 30;
580         }
581         need_failback = 0;
582 out:
583         if (monitor)
584                 udev_monitor_unref(monitor);
585         if (need_failback)
586                 err = failback_listen();
587         pthread_cleanup_pop(1);
588         return err;
589 }
590
591 extern int
592 uevent_get_major(struct uevent *uev)
593 {
594         char *p, *q;
595         int i, major = -1;
596
597         for (i = 0; uev->envp[i] != NULL; i++) {
598                 if (!strncmp(uev->envp[i], "MAJOR", 5) && strlen(uev->envp[i]) > 6) {
599                         p = uev->envp[i] + 6;
600                         major = strtoul(p, &q, 10);
601                         if (p == q) {
602                                 condlog(2, "invalid major '%s'", p);
603                                 major = -1;
604                         }
605                         break;
606                 }
607         }
608         return major;
609 }
610
611 extern int
612 uevent_get_minor(struct uevent *uev)
613 {
614         char *p, *q;
615         int i, minor = -1;
616
617         for (i = 0; uev->envp[i] != NULL; i++) {
618                 if (!strncmp(uev->envp[i], "MINOR", 5) && strlen(uev->envp[i]) > 6) {
619                         p = uev->envp[i] + 6;
620                         minor = strtoul(p, &q, 10);
621                         if (p == q) {
622                                 condlog(2, "invalid minor '%s'", p);
623                                 minor = -1;
624                         }
625                         break;
626                 }
627         }
628         return minor;
629 }
630
631 extern int
632 uevent_get_disk_ro(struct uevent *uev)
633 {
634         char *p, *q;
635         int i, ro = -1;
636
637         for (i = 0; uev->envp[i] != NULL; i++) {
638                 if (!strncmp(uev->envp[i], "DISK_RO", 6) && strlen(uev->envp[i]) > 7) {
639                         p = uev->envp[i] + 8;
640                         ro = strtoul(p, &q, 10);
641                         if (p == q) {
642                                 condlog(2, "invalid read_only setting '%s'", p);
643                                 ro = -1;
644                         }
645                         break;
646                 }
647         }
648         return ro;
649 }
650
651 extern char *
652 uevent_get_dm_name(struct uevent *uev)
653 {
654         char *p = NULL;
655         int i;
656
657         for (i = 0; uev->envp[i] != NULL; i++) {
658                 if (!strncmp(uev->envp[i], "DM_NAME", 6) &&
659                     strlen(uev->envp[i]) > 7) {
660                         p = MALLOC(strlen(uev->envp[i] + 8) + 1);
661                         strcpy(p, uev->envp[i] + 8);
662                         break;
663                 }
664         }
665         return p;
666 }