Add global udev reference pointer to config
[platform/upstream/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                 FREE(uev);
121         }
122 }
123
124 static void uevq_stop(void *arg)
125 {
126         condlog(3, "Stopping uev queue");
127         pthread_mutex_lock(uevq_lockp);
128         my_uev_trigger = NULL;
129         pthread_cond_signal(uev_condp);
130         pthread_mutex_unlock(uevq_lockp);
131 }
132
133 /*
134  * Service the uevent queue.
135  */
136 int uevent_dispatch(int (*uev_trigger)(struct uevent *, void * trigger_data),
137                     void * trigger_data)
138 {
139         my_uev_trigger = uev_trigger;
140         my_trigger_data = trigger_data;
141
142         mlockall(MCL_CURRENT | MCL_FUTURE);
143
144         while (1) {
145                 LIST_HEAD(uevq_tmp);
146
147                 pthread_mutex_lock(uevq_lockp);
148                 servicing_uev = 0;
149                 /*
150                  * Condition signals are unreliable,
151                  * so make sure we only wait if we have to.
152                  */
153                 if (list_empty(&uevq)) {
154                         pthread_cond_wait(uev_condp, uevq_lockp);
155                 }
156                 servicing_uev = 1;
157                 list_splice_init(&uevq, &uevq_tmp);
158                 pthread_mutex_unlock(uevq_lockp);
159                 if (!my_uev_trigger)
160                         break;
161                 service_uevq(&uevq_tmp);
162         }
163         condlog(3, "Terminating uev service queue");
164         return 0;
165 }
166
167 int failback_listen(void)
168 {
169         int sock;
170         struct sockaddr_nl snl;
171         struct sockaddr_un sun;
172         socklen_t addrlen;
173         int retval;
174         int rcvbufsz = 128*1024;
175         int rcvsz = 0;
176         int rcvszsz = sizeof(rcvsz);
177         unsigned int *prcvszsz = (unsigned int *)&rcvszsz;
178         const int feature_on = 1;
179         /*
180          * First check whether we have a udev socket
181          */
182         memset(&sun, 0x00, sizeof(struct sockaddr_un));
183         sun.sun_family = AF_LOCAL;
184         strcpy(&sun.sun_path[1], "/org/kernel/dm/multipath_event");
185         addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(sun.sun_path+1) + 1;
186
187         sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
188         if (sock >= 0) {
189
190                 condlog(3, "reading events from udev socket.");
191
192                 /* the bind takes care of ensuring only one copy running */
193                 retval = bind(sock, (struct sockaddr *) &sun, addrlen);
194                 if (retval < 0) {
195                         condlog(0, "bind failed, exit");
196                         goto exit;
197                 }
198
199                 /* enable receiving of the sender credentials */
200                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
201                            &feature_on, sizeof(feature_on));
202
203         } else {
204                 /* Fallback to read kernel netlink events */
205                 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
206                 snl.nl_family = AF_NETLINK;
207                 snl.nl_pid = getpid();
208                 snl.nl_groups = 0x01;
209
210                 sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
211                 if (sock == -1) {
212                         condlog(0, "error getting socket, exit");
213                         return 1;
214                 }
215
216                 condlog(3, "reading events from kernel.");
217
218                 /*
219                  * try to avoid dropping uevents, even so, this is not a guarantee,
220                  * but it does help to change the netlink uevent socket's
221                  * receive buffer threshold from the default value of 106,496 to
222                  * the maximum value of 262,142.
223                  */
224                 retval = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbufsz,
225                                     sizeof(rcvbufsz));
226
227                 if (retval < 0) {
228                         condlog(0, "error setting receive buffer size for socket, exit");
229                         exit(1);
230                 }
231                 retval = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvsz, prcvszsz);
232                 if (retval < 0) {
233                         condlog(0, "error setting receive buffer size for socket, exit");
234                         exit(1);
235                 }
236                 condlog(3, "receive buffer size for socket is %u.", rcvsz);
237
238                 /* enable receiving of the sender credentials */
239                 setsockopt(sock, SOL_SOCKET, SO_PASSCRED,
240                            &feature_on, sizeof(feature_on));
241
242                 retval = bind(sock, (struct sockaddr *) &snl,
243                               sizeof(struct sockaddr_nl));
244                 if (retval < 0) {
245                         condlog(0, "bind failed, exit");
246                         goto exit;
247                 }
248         }
249
250         while (1) {
251                 int i;
252                 char *pos;
253                 size_t bufpos;
254                 ssize_t buflen;
255                 struct uevent *uev;
256                 char *buffer;
257                 struct msghdr smsg;
258                 struct iovec iov;
259                 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
260                 struct cmsghdr *cmsg;
261                 struct ucred *cred;
262                 static char buf[HOTPLUG_BUFFER_SIZE + OBJECT_SIZE];
263
264                 memset(buf, 0x00, sizeof(buf));
265                 iov.iov_base = &buf;
266                 iov.iov_len = sizeof(buf);
267                 memset (&smsg, 0x00, sizeof(struct msghdr));
268                 smsg.msg_iov = &iov;
269                 smsg.msg_iovlen = 1;
270                 smsg.msg_control = cred_msg;
271                 smsg.msg_controllen = sizeof(cred_msg);
272
273                 buflen = recvmsg(sock, &smsg, 0);
274                 if (buflen < 0) {
275                         if (errno != EINTR)
276                                 condlog(0, "error receiving message, errno %d", errno);
277                         continue;
278                 }
279
280                 cmsg = CMSG_FIRSTHDR(&smsg);
281                 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
282                         condlog(3, "no sender credentials received, message ignored");
283                         continue;
284                 }
285
286                 cred = (struct ucred *)CMSG_DATA(cmsg);
287                 if (cred->uid != 0) {
288                         condlog(3, "sender uid=%d, message ignored", cred->uid);
289                         continue;
290                 }
291
292                 /* skip header */
293                 bufpos = strlen(buf) + 1;
294                 if (bufpos < sizeof("a@/d") || bufpos >= sizeof(buf)) {
295                         condlog(3, "invalid message length");
296                         continue;
297                 }
298
299                 /* check message header */
300                 if (strstr(buf, "@/") == NULL) {
301                         condlog(3, "unrecognized message header");
302                         continue;
303                 }
304                 if ((size_t)buflen > sizeof(buf)-1) {
305                         condlog(2, "buffer overflow for received uevent");
306                         buflen = sizeof(buf)-1;
307                 }
308
309                 uev = alloc_uevent();
310
311                 if (!uev) {
312                         condlog(1, "lost uevent, oom");
313                         continue;
314                 }
315
316                 if ((size_t)buflen > sizeof(buf)-1)
317                         buflen = sizeof(buf)-1;
318
319                 /*
320                  * Copy the shared receive buffer contents to buffer private
321                  * to this uevent so we can immediately reuse the shared buffer.
322                  */
323                 memcpy(uev->buffer, buf, HOTPLUG_BUFFER_SIZE + OBJECT_SIZE);
324                 buffer = uev->buffer;
325                 buffer[buflen] = '\0';
326
327                 /* save start of payload */
328                 bufpos = strlen(buffer) + 1;
329
330                 /* action string */
331                 uev->action = buffer;
332                 pos = strchr(buffer, '@');
333                 if (!pos) {
334                         condlog(3, "bad action string '%s'", buffer);
335                         continue;
336                 }
337                 pos[0] = '\0';
338
339                 /* sysfs path */
340                 uev->devpath = &pos[1];
341
342                 /* hotplug events have the environment attached - reconstruct envp[] */
343                 for (i = 0; (bufpos < (size_t)buflen) && (i < HOTPLUG_NUM_ENVP-1); i++) {
344                         int keylen;
345                         char *key;
346
347                         key = &buffer[bufpos];
348                         keylen = strlen(key);
349                         uev->envp[i] = key;
350                         bufpos += keylen + 1;
351                 }
352                 uev->envp[i] = NULL;
353
354                 condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
355                 uev->kernel = strrchr(uev->devpath, '/');
356                 if (uev->kernel)
357                         uev->kernel++;
358
359                 /* print payload environment */
360                 for (i = 0; uev->envp[i] != NULL; i++)
361                         condlog(5, "%s", uev->envp[i]);
362
363                 /*
364                  * Queue uevent and poke service pthread.
365                  */
366                 pthread_mutex_lock(uevq_lockp);
367                 list_add_tail(&uev->node, &uevq);
368                 pthread_cond_signal(uev_condp);
369                 pthread_mutex_unlock(uevq_lockp);
370         }
371
372 exit:
373         close(sock);
374         return 1;
375 }
376
377 int uevent_listen(void)
378 {
379         int err;
380         struct udev_monitor *monitor = NULL;
381         int fd, socket_flags;
382         int need_failback = 1;
383         /*
384          * Queue uevents for service by dedicated thread so that the uevent
385          * listening thread does not block on multipathd locks (vecs->lock)
386          * thereby not getting to empty the socket's receive buffer queue
387          * often enough.
388          */
389         INIT_LIST_HEAD(&uevq);
390
391         pthread_mutex_init(uevq_lockp, NULL);
392         pthread_cond_init(uev_condp, NULL);
393         pthread_cleanup_push(uevq_stop, NULL);
394
395         monitor = udev_monitor_new_from_netlink(conf->udev, "udev");
396         if (!monitor) {
397                 condlog(2, "failed to create udev monitor");
398                 goto out;
399         }
400         if (udev_monitor_set_receive_buffer_size(monitor, 128 * 1024 * 1024))
401                 condlog(2, "failed to increase buffer size");
402         fd = udev_monitor_get_fd(monitor);
403         if (fd < 0) {
404                 condlog(2, "failed to get monitor fd");
405                 goto out;
406         }
407         socket_flags = fcntl(fd, F_GETFL);
408         if (socket_flags < 0) {
409                 condlog(2, "failed to get monitor socket flags : %s",
410                         strerror(errno));
411                 goto out;
412         }
413         if (fcntl(fd, F_SETFL, socket_flags & ~O_NONBLOCK) < 0) {
414                 condlog(2, "failed to set monitor socket flags : %s",
415                         strerror(errno));
416                 goto out;
417         }
418         err = udev_monitor_filter_add_match_subsystem_devtype(monitor, "block",
419                                                               NULL);
420         if (err)
421                 condlog(2, "failed to create filter : %s\n", strerror(-err));
422         err = udev_monitor_enable_receiving(monitor);
423         if (err) {
424                 condlog(2, "failed to enable receiving : %s\n", strerror(-err));
425                 goto out;
426         }
427         while (1) {
428                 int i = 0;
429                 char *pos, *end;
430                 struct uevent *uev;
431                 struct udev_device *dev;
432                 struct udev_list_entry *list_entry;
433
434                 dev = udev_monitor_receive_device(monitor);
435                 if (!dev) {
436                         condlog(0, "failed getting udev device");
437                         continue;
438                 }
439
440                 uev = alloc_uevent();
441                 if (!uev) {
442                         condlog(1, "lost uevent, oom");
443                         continue;
444                 }
445                 pos = uev->buffer;
446                 end = pos + HOTPLUG_BUFFER_SIZE + OBJECT_SIZE - 1;
447                 udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(dev)) {
448                         const char *name, *value;
449                         int bytes;
450
451                         name = udev_list_entry_get_name(list_entry);
452                         if (!name)
453                                 name = "(null)";
454                         value = udev_list_entry_get_value(list_entry);
455                         if (!value)
456                                 value = "(null)";
457                         bytes = snprintf(pos, end - pos, "%s=%s", name,
458                                         value);
459                         if (pos + bytes >= end) {
460                                 condlog(2, "buffer overflow for uevent");
461                                 break;
462                         }
463                         uev->envp[i] = pos;
464                         pos += bytes;
465                         *pos = '\0';
466                         pos++;
467                         if (strcmp(name, "DEVPATH") == 0)
468                                 uev->devpath = uev->envp[i] + 8;
469                         if (strcmp(name, "ACTION") == 0)
470                                 uev->action = uev->envp[i] + 7;
471                         i++;
472                         if (i == HOTPLUG_NUM_ENVP - 1)
473                                 break;
474                 }
475                 udev_device_unref(dev);
476                 uev->envp[i] = NULL;
477
478                 condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
479                 uev->kernel = strrchr(uev->devpath, '/');
480                 if (uev->kernel)
481                         uev->kernel++;
482
483                 /* print payload environment */
484                 for (i = 0; uev->envp[i] != NULL; i++)
485                         condlog(5, "%s", uev->envp[i]);
486
487                 /*
488                  * Queue uevent and poke service pthread.
489                  */
490                 pthread_mutex_lock(uevq_lockp);
491                 list_add_tail(&uev->node, &uevq);
492                 pthread_cond_signal(uev_condp);
493                 pthread_mutex_unlock(uevq_lockp);
494         }
495         need_failback = 0;
496 out:
497         if (monitor)
498                 udev_monitor_unref(monitor);
499         if (need_failback)
500                 err = failback_listen();
501         pthread_cleanup_pop(1);
502         pthread_mutex_destroy(uevq_lockp);
503         pthread_cond_destroy(uev_condp);
504         return err;
505 }
506
507 extern int
508 uevent_get_major(struct uevent *uev)
509 {
510         char *p, *q;
511         int i, major = -1;
512
513         for (i = 0; uev->envp[i] != NULL; i++) {
514                 if (!strncmp(uev->envp[i], "MAJOR", 5) && strlen(uev->envp[i]) > 6) {
515                         p = uev->envp[i] + 6;
516                         major = strtoul(p, &q, 10);
517                         if (p == q) {
518                                 condlog(2, "invalid major '%s'", p);
519                                 major = -1;
520                         }
521                         break;
522                 }
523         }
524         return major;
525 }
526
527 extern int
528 uevent_get_minor(struct uevent *uev)
529 {
530         char *p, *q;
531         int i, minor = -1;
532
533         for (i = 0; uev->envp[i] != NULL; i++) {
534                 if (!strncmp(uev->envp[i], "MINOR", 5) && strlen(uev->envp[i]) > 6) {
535                         p = uev->envp[i] + 6;
536                         minor = strtoul(p, &q, 10);
537                         if (p == q) {
538                                 condlog(2, "invalid minor '%s'", p);
539                                 minor = -1;
540                         }
541                         break;
542                 }
543         }
544         return minor;
545 }
546
547 extern int
548 uevent_get_disk_ro(struct uevent *uev)
549 {
550         char *p, *q;
551         int i, ro = -1;
552
553         for (i = 0; uev->envp[i] != NULL; i++) {
554                 if (!strncmp(uev->envp[i], "DISK_RO", 6) && strlen(uev->envp[i]) > 7) {
555                         p = uev->envp[i] + 8;
556                         ro = strtoul(p, &q, 10);
557                         if (p == q) {
558                                 condlog(2, "invalid read_only setting '%s'", p);
559                                 ro = -1;
560                         }
561                         break;
562                 }
563         }
564         return ro;
565 }
566
567 extern char *
568 uevent_get_dm_name(struct uevent *uev)
569 {
570         char *p = NULL;
571         int i;
572
573         for (i = 0; uev->envp[i] != NULL; i++) {
574                 if (!strncmp(uev->envp[i], "DM_NAME", 6) &&
575                     strlen(uev->envp[i]) > 7) {
576                         p = MALLOC(strlen(uev->envp[i] + 8) + 1);
577                         strcpy(p, uev->envp[i] + 8);
578                         break;
579                 }
580         }
581         return p;
582 }