libmultipath: Print out uevent sequence number
[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, write to the Free Software Foundation, Inc.,
22  *      675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  */
25
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32 #include <fcntl.h>
33 #include <time.h>
34 #include <sys/socket.h>
35 #include <sys/user.h>
36 #include <sys/un.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 #include "config.h"
51
52 typedef int (uev_trigger)(struct uevent *, void * trigger_data);
53
54 pthread_t uevq_thr;
55 LIST_HEAD(uevq);
56 pthread_mutex_t uevq_lock, *uevq_lockp = &uevq_lock;
57 pthread_cond_t  uev_cond,  *uev_condp  = &uev_cond;
58 uev_trigger *my_uev_trigger;
59 void * my_trigger_data;
60 int servicing_uev;
61
62 int is_uevent_busy(void)
63 {
64         int empty;
65
66         pthread_mutex_lock(uevq_lockp);
67         empty = list_empty(&uevq);
68         pthread_mutex_unlock(uevq_lockp);
69         return (!empty || servicing_uev);
70 }
71
72 struct uevent * alloc_uevent (void)
73 {
74         struct uevent *uev = MALLOC(sizeof(struct uevent));
75
76         if (uev)
77                 INIT_LIST_HEAD(&uev->node);
78
79         return uev;
80 }
81
82 void
83 setup_thread_attr(pthread_attr_t *attr, size_t stacksize, int detached)
84 {
85         if (pthread_attr_init(attr)) {
86                 fprintf(stderr, "can't initialize thread attr: %s\n",
87                         strerror(errno));
88                 exit(1);
89         }
90         if (stacksize < PTHREAD_STACK_MIN)
91                 stacksize = PTHREAD_STACK_MIN;
92
93         if (pthread_attr_setstacksize(attr, stacksize)) {
94                 fprintf(stderr, "can't set thread stack size to %lu: %s\n",
95                         (unsigned long)stacksize, strerror(errno));
96                 exit(1);
97         }
98         if (detached && pthread_attr_setdetachstate(attr,
99                                                     PTHREAD_CREATE_DETACHED)) {
100                 fprintf(stderr, "can't set thread to detached: %s\n",
101                         strerror(errno));
102                 exit(1);
103         }
104 }
105
106 /*
107  * Called with uevq_lockp held
108  */
109 void
110 service_uevq(struct list_head *tmpq)
111 {
112         struct uevent *uev, *tmp;
113
114         list_for_each_entry_safe(uev, tmp, tmpq, node) {
115                 list_del_init(&uev->node);
116
117                 if (my_uev_trigger && my_uev_trigger(uev, my_trigger_data))
118                         condlog(0, "uevent trigger error");
119
120                 if (uev->udev)
121                         udev_device_unref(uev->udev);
122                 FREE(uev);
123         }
124 }
125
126 static void uevq_stop(void *arg)
127 {
128         condlog(3, "Stopping uev queue");
129         pthread_mutex_lock(uevq_lockp);
130         my_uev_trigger = NULL;
131         pthread_cond_signal(uev_condp);
132         pthread_mutex_unlock(uevq_lockp);
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 int failback_listen(void)
182 {
183         int sock;
184         struct sockaddr_nl snl;
185         struct sockaddr_un sun;
186         socklen_t addrlen;
187         int retval;
188         int rcvbufsz = 128*1024;
189         int rcvsz = 0;
190         int rcvszsz = sizeof(rcvsz);
191         unsigned int *prcvszsz = (unsigned int *)&rcvszsz;
192         const int feature_on = 1;
193         /*
194          * First check whether we have a udev socket
195          */
196         memset(&sun, 0x00, sizeof(struct sockaddr_un));
197         sun.sun_family = AF_LOCAL;
198         strcpy(&sun.sun_path[1], "/org/kernel/dm/multipath_event");
199         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(sun.sun_path+1) + 1;
200
201         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
202         if (sock >= 0) {
203
204                 condlog(3, "reading events from udev socket.");
205
206                 /* the bind takes care of ensuring only one copy running */
207                 retval = bind(sock, (struct sockaddr *) &sun, addrlen);
208                 if (retval < 0) {
209                         condlog(0, "bind failed, exit");
210                         goto exit;
211                 }
212
213                 /* enable receiving of the sender credentials */
214                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
215                            &feature_on, sizeof(feature_on));
216
217         } else {
218                 /* Fallback to read kernel netlink events */
219                 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
220                 snl.nl_family = AF_NETLINK;
221                 snl.nl_pid = getpid();
222                 snl.nl_groups = 0x01;
223
224                 sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
225                 if (sock == -1) {
226                         condlog(0, "error getting socket, exit");
227                         return 1;
228                 }
229
230                 condlog(3, "reading events from kernel.");
231
232                 /*
233                  * try to avoid dropping uevents, even so, this is not a guarantee,
234                  * but it does help to change the netlink uevent socket's
235                  * receive buffer threshold from the default value of 106,496 to
236                  * the maximum value of 262,142.
237                  */
238                 retval = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbufsz,
239                                     sizeof(rcvbufsz));
240
241                 if (retval < 0) {
242                         condlog(0, "error setting receive buffer size for socket, exit");
243                         exit(1);
244                 }
245                 retval = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvsz, prcvszsz);
246                 if (retval < 0) {
247                         condlog(0, "error setting receive buffer size for socket, exit");
248                         exit(1);
249                 }
250                 condlog(3, "receive buffer size for socket is %u.", rcvsz);
251
252                 /* enable receiving of the sender credentials */
253                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
254                            &feature_on, sizeof(feature_on));
255
256                 retval = bind(sock, (struct sockaddr *) &snl,
257                               sizeof(struct sockaddr_nl));
258                 if (retval < 0) {
259                         condlog(0, "bind failed, exit");
260                         goto exit;
261                 }
262         }
263
264         while (1) {
265                 int i;
266                 char *pos;
267                 size_t bufpos;
268                 ssize_t buflen;
269                 struct uevent *uev;
270                 char *buffer;
271                 struct msghdr smsg;
272                 struct iovec iov;
273                 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
274                 struct cmsghdr *cmsg;
275                 struct ucred *cred;
276                 static char buf[HOTPLUG_BUFFER_SIZE + OBJECT_SIZE];
277
278                 memset(buf, 0x00, sizeof(buf));
279                 iov.iov_base = &buf;
280                 iov.iov_len = sizeof(buf);
281                 memset (&smsg, 0x00, sizeof(struct msghdr));
282                 smsg.msg_iov = &iov;
283                 smsg.msg_iovlen = 1;
284                 smsg.msg_control = cred_msg;
285                 smsg.msg_controllen = sizeof(cred_msg);
286
287                 buflen = recvmsg(sock, &smsg, 0);
288                 if (buflen < 0) {
289                         if (errno != EINTR)
290                                 condlog(0, "error receiving message, errno %d", errno);
291                         continue;
292                 }
293
294                 cmsg = CMSG_FIRSTHDR(&smsg);
295                 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
296                         condlog(3, "no sender credentials received, message ignored");
297                         continue;
298                 }
299
300                 cred = (struct ucred *)CMSG_DATA(cmsg);
301                 if (cred->uid != 0) {
302                         condlog(3, "sender uid=%d, message ignored", cred->uid);
303                         continue;
304                 }
305
306                 /* skip header */
307                 bufpos = strlen(buf) + 1;
308                 if (bufpos < sizeof("a@/d") || bufpos >= sizeof(buf)) {
309                         condlog(3, "invalid message length");
310                         continue;
311                 }
312
313                 /* check message header */
314                 if (strstr(buf, "@/") == NULL) {
315                         condlog(3, "unrecognized message header");
316                         continue;
317                 }
318                 if ((size_t)buflen > sizeof(buf)-1) {
319                         condlog(2, "buffer overflow for received uevent");
320                         buflen = sizeof(buf)-1;
321                 }
322
323                 uev = alloc_uevent();
324
325                 if (!uev) {
326                         condlog(1, "lost uevent, oom");
327                         continue;
328                 }
329
330                 if ((size_t)buflen > sizeof(buf)-1)
331                         buflen = sizeof(buf)-1;
332
333                 /*
334                  * Copy the shared receive buffer contents to buffer private
335                  * to this uevent so we can immediately reuse the shared buffer.
336                  */
337                 memcpy(uev->buffer, buf, HOTPLUG_BUFFER_SIZE + OBJECT_SIZE);
338                 buffer = uev->buffer;
339                 buffer[buflen] = '\0';
340
341                 /* save start of payload */
342                 bufpos = strlen(buffer) + 1;
343
344                 /* action string */
345                 uev->action = buffer;
346                 pos = strchr(buffer, '@');
347                 if (!pos) {
348                         condlog(3, "bad action string '%s'", buffer);
349                         continue;
350                 }
351                 pos[0] = '\0';
352
353                 /* sysfs path */
354                 uev->devpath = &pos[1];
355
356                 /* hotplug events have the environment attached - reconstruct envp[] */
357                 for (i = 0; (bufpos < (size_t)buflen) && (i < HOTPLUG_NUM_ENVP-1); i++) {
358                         int keylen;
359                         char *key;
360
361                         key = &buffer[bufpos];
362                         keylen = strlen(key);
363                         uev->envp[i] = key;
364                         /* Filter out sequence number */
365                         if (strncmp(key, "SEQNUM=", 7) == 0) {
366                                 char *eptr;
367
368                                 uev->seqnum = strtoul(key + 7, &eptr, 10);
369                                 if (eptr == key + 7)
370                                         uev->seqnum = -1;
371                         }
372                         bufpos += keylen + 1;
373                 }
374                 uev->envp[i] = NULL;
375
376                 condlog(3, "uevent %ld '%s' from '%s'", uev->seqnum,
377                         uev->action, uev->devpath);
378                 uev->kernel = strrchr(uev->devpath, '/');
379                 if (uev->kernel)
380                         uev->kernel++;
381
382                 /* print payload environment */
383                 for (i = 0; uev->envp[i] != NULL; i++)
384                         condlog(5, "%s", uev->envp[i]);
385
386                 /*
387                  * Queue uevent and poke service pthread.
388                  */
389                 pthread_mutex_lock(uevq_lockp);
390                 list_add_tail(&uev->node, &uevq);
391                 pthread_cond_signal(uev_condp);
392                 pthread_mutex_unlock(uevq_lockp);
393         }
394
395 exit:
396         close(sock);
397         return 1;
398 }
399
400 int uevent_listen(void)
401 {
402         int err;
403         struct udev_monitor *monitor = NULL;
404         int fd, socket_flags;
405         int need_failback = 1;
406         /*
407          * Queue uevents for service by dedicated thread so that the uevent
408          * listening thread does not block on multipathd locks (vecs->lock)
409          * thereby not getting to empty the socket's receive buffer queue
410          * often enough.
411          */
412         INIT_LIST_HEAD(&uevq);
413
414         pthread_mutex_init(uevq_lockp, NULL);
415         pthread_cond_init(uev_condp, NULL);
416         pthread_cleanup_push(uevq_stop, NULL);
417
418         monitor = udev_monitor_new_from_netlink(conf->udev, "udev");
419         if (!monitor) {
420                 condlog(2, "failed to create udev monitor");
421                 goto out;
422         }
423 #ifdef LIBUDEV_API_RECVBUF
424         if (udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024))
425                 condlog(2, "failed to increase buffer size");
426 #endif
427         fd = udev_monitor_get_fd(monitor);
428         if (fd < 0) {
429                 condlog(2, "failed to get monitor fd");
430                 goto out;
431         }
432         socket_flags = fcntl(fd, F_GETFL);
433         if (socket_flags < 0) {
434                 condlog(2, "failed to get monitor socket flags : %s",
435                         strerror(errno));
436                 goto out;
437         }
438         if (fcntl(fd, F_SETFL, socket_flags & ~O_NONBLOCK) < 0) {
439                 condlog(2, "failed to set monitor socket flags : %s",
440                         strerror(errno));
441                 goto out;
442         }
443         err = udev_monitor_filter_add_match_subsystem_devtype(monitor, "block",
444                                                               NULL);
445         if (err)
446                 condlog(2, "failed to create filter : %s", strerror(-err));
447         err = udev_monitor_enable_receiving(monitor);
448         if (err) {
449                 condlog(2, "failed to enable receiving : %s", strerror(-err));
450                 goto out;
451         }
452         while (1) {
453                 int i = 0;
454                 char *pos, *end;
455                 struct uevent *uev;
456                 struct udev_device *dev;
457                 struct udev_list_entry *list_entry;
458
459                 dev = udev_monitor_receive_device(monitor);
460                 if (!dev) {
461                         condlog(0, "failed getting udev device");
462                         continue;
463                 }
464
465                 uev = alloc_uevent();
466                 if (!uev) {
467                         udev_device_unref(dev);
468                         condlog(1, "lost uevent, oom");
469                         continue;
470                 }
471                 pos = uev->buffer;
472                 end = pos + HOTPLUG_BUFFER_SIZE + OBJECT_SIZE - 1;
473                 udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev)) {
474                         const char *name, *value;
475                         int bytes;
476
477                         name = udev_list_entry_get_name(list_entry);
478                         if (!name)
479                                 name = "(null)";
480                         value = udev_list_entry_get_value(list_entry);
481                         if (!value)
482                                 value = "(null)";
483                         bytes = snprintf(pos, end - pos, "%s=%s", name,
484                                         value);
485                         if (pos + bytes >= end) {
486                                 condlog(2, "buffer overflow for uevent");
487                                 break;
488                         }
489                         uev->envp[i] = pos;
490                         pos += bytes;
491                         *pos = '\0';
492                         pos++;
493                         if (strcmp(name, "DEVPATH") == 0)
494                                 uev->devpath = uev->envp[i] + 8;
495                         if (strcmp(name, "ACTION") == 0)
496                                 uev->action = uev->envp[i] + 7;
497                         i++;
498                         if (i == HOTPLUG_NUM_ENVP - 1)
499                                 break;
500                 }
501                 uev->udev = dev;
502                 uev->envp[i] = NULL;
503
504                 condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
505                 uev->kernel = strrchr(uev->devpath, '/');
506                 if (uev->kernel)
507                         uev->kernel++;
508
509                 /* print payload environment */
510                 for (i = 0; uev->envp[i] != NULL; i++)
511                         condlog(5, "%s", uev->envp[i]);
512
513                 /*
514                  * Queue uevent and poke service pthread.
515                  */
516                 pthread_mutex_lock(uevq_lockp);
517                 list_add_tail(&uev->node, &uevq);
518                 pthread_cond_signal(uev_condp);
519                 pthread_mutex_unlock(uevq_lockp);
520         }
521         need_failback = 0;
522 out:
523         if (monitor)
524                 udev_monitor_unref(monitor);
525         if (need_failback)
526                 err = failback_listen();
527         pthread_cleanup_pop(1);
528         pthread_mutex_destroy(uevq_lockp);
529         pthread_cond_destroy(uev_condp);
530         return err;
531 }
532
533 extern int
534 uevent_get_major(struct uevent *uev)
535 {
536         char *p, *q;
537         int i, major = -1;
538
539         for (i = 0; uev->envp[i] != NULL; i++) {
540                 if (!strncmp(uev->envp[i], "MAJOR", 5) && strlen(uev->envp[i]) > 6) {
541                         p = uev->envp[i] + 6;
542                         major = strtoul(p, &q, 10);
543                         if (p == q) {
544                                 condlog(2, "invalid major '%s'", p);
545                                 major = -1;
546                         }
547                         break;
548                 }
549         }
550         return major;
551 }
552
553 extern int
554 uevent_get_minor(struct uevent *uev)
555 {
556         char *p, *q;
557         int i, minor = -1;
558
559         for (i = 0; uev->envp[i] != NULL; i++) {
560                 if (!strncmp(uev->envp[i], "MINOR", 5) && strlen(uev->envp[i]) > 6) {
561                         p = uev->envp[i] + 6;
562                         minor = strtoul(p, &q, 10);
563                         if (p == q) {
564                                 condlog(2, "invalid minor '%s'", p);
565                                 minor = -1;
566                         }
567                         break;
568                 }
569         }
570         return minor;
571 }
572
573 extern int
574 uevent_get_disk_ro(struct uevent *uev)
575 {
576         char *p, *q;
577         int i, ro = -1;
578
579         for (i = 0; uev->envp[i] != NULL; i++) {
580                 if (!strncmp(uev->envp[i], "DISK_RO", 6) && strlen(uev->envp[i]) > 7) {
581                         p = uev->envp[i] + 8;
582                         ro = strtoul(p, &q, 10);
583                         if (p == q) {
584                                 condlog(2, "invalid read_only setting '%s'", p);
585                                 ro = -1;
586                         }
587                         break;
588                 }
589         }
590         return ro;
591 }
592
593 extern char *
594 uevent_get_dm_name(struct uevent *uev)
595 {
596         char *p = NULL;
597         int i;
598
599         for (i = 0; uev->envp[i] != NULL; i++) {
600                 if (!strncmp(uev->envp[i], "DM_NAME", 6) &&
601                     strlen(uev->envp[i]) > 7) {
602                         p = MALLOC(strlen(uev->envp[i] + 8) + 1);
603                         strcpy(p, uev->envp[i] + 8);
604                         break;
605                 }
606         }
607         return p;
608 }