Use lists for uevent processing
[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 <errno.h>
43
44 #include "memory.h"
45 #include "debug.h"
46 #include "list.h"
47 #include "uevent.h"
48
49 typedef int (uev_trigger)(struct uevent *, void * trigger_data);
50
51 pthread_t uevq_thr;
52 LIST_HEAD(uevq);
53 pthread_mutex_t uevq_lock, *uevq_lockp = &uevq_lock;
54 pthread_cond_t  uev_cond,  *uev_condp  = &uev_cond;
55 uev_trigger *my_uev_trigger;
56 void * my_trigger_data;
57 int servicing_uev;
58
59 int is_uevent_busy(void)
60 {
61         int empty;
62
63         pthread_mutex_lock(uevq_lockp);
64         empty = list_empty(&uevq);
65         pthread_mutex_unlock(uevq_lockp);
66         return (!empty || servicing_uev);
67 }
68
69 struct uevent * alloc_uevent (void)
70 {
71         struct uevent *uev = MALLOC(sizeof(struct uevent));
72
73         if (uev)
74                 INIT_LIST_HEAD(&uev->node);
75
76         return uev;
77 }
78
79 void
80 setup_thread_attr(pthread_attr_t *attr, size_t stacksize, int detached)
81 {
82         if (pthread_attr_init(attr)) {
83                 fprintf(stderr, "can't initialize thread attr: %s\n",
84                         strerror(errno));
85                 exit(1);
86         }
87         if (stacksize < PTHREAD_STACK_MIN)
88                 stacksize = PTHREAD_STACK_MIN;
89
90         if (pthread_attr_setstacksize(attr, stacksize)) {
91                 fprintf(stderr, "can't set thread stack size to %lu: %s\n",
92                         (unsigned long)stacksize, strerror(errno));
93                 exit(1);
94         }
95         if (detached && pthread_attr_setdetachstate(attr,
96                                                     PTHREAD_CREATE_DETACHED)) {
97                 fprintf(stderr, "can't set thread to detached: %s\n",
98                         strerror(errno));
99                 exit(1);
100         }
101 }
102
103 /*
104  * Called with uevq_lockp held
105  */
106 void
107 service_uevq(struct list_head *tmpq)
108 {
109         struct uevent *uev, *tmp;
110
111         list_for_each_entry_safe(uev, tmp, tmpq, node) {
112                 list_del_init(&uev->node);
113
114                 if (my_uev_trigger && my_uev_trigger(uev, my_trigger_data))
115                         condlog(0, "uevent trigger error");
116
117                 FREE(uev);
118         }
119 }
120
121 static void uevq_stop(void *arg)
122 {
123         condlog(3, "Stopping uev queue");
124         pthread_mutex_lock(uevq_lockp);
125         my_uev_trigger = NULL;
126         pthread_cond_signal(uev_condp);
127         pthread_mutex_unlock(uevq_lockp);
128 }
129
130 /*
131  * Service the uevent queue.
132  */
133 static void *
134 uevq_thread(void * et)
135 {
136         mlockall(MCL_CURRENT | MCL_FUTURE);
137
138         while (1) {
139                 LIST_HEAD(uevq_tmp);
140
141                 pthread_mutex_lock(uevq_lockp);
142                 servicing_uev = 0;
143                 /*
144                  * Condition signals are unreliable,
145                  * so make sure we only wait if we have to.
146                  */
147                 if (list_empty(&uevq)) {
148                         pthread_cond_wait(uev_condp, uevq_lockp);
149                 }
150                 servicing_uev = 1;
151                 list_splice_init(&uevq, &uevq_tmp);
152                 pthread_mutex_unlock(uevq_lockp);
153                 if (!my_uev_trigger)
154                         break;
155                 service_uevq(&uevq_tmp);
156         }
157         return NULL;
158 }
159
160 int uevent_listen(int (*uev_trigger)(struct uevent *, void * trigger_data),
161                   void * trigger_data)
162 {
163         int sock;
164         struct sockaddr_nl snl;
165         struct sockaddr_un sun;
166         socklen_t addrlen;
167         int retval;
168         int rcvbufsz = 128*1024;
169         int rcvsz = 0;
170         int rcvszsz = sizeof(rcvsz);
171         unsigned int *prcvszsz = (unsigned int *)&rcvszsz;
172         pthread_attr_t attr;
173         const int feature_on = 1;
174
175         my_uev_trigger = uev_trigger;
176         my_trigger_data = trigger_data;
177
178         /*
179          * Queue uevents for service by dedicated thread so that the uevent
180          * listening thread does not block on multipathd locks (vecs->lock)
181          * thereby not getting to empty the socket's receive buffer queue
182          * often enough.
183          */
184         INIT_LIST_HEAD(&uevq);
185
186         pthread_mutex_init(uevq_lockp, NULL);
187         pthread_cond_init(uev_condp, NULL);
188
189         pthread_cleanup_push(uevq_stop, NULL);
190         setup_thread_attr(&attr, 64 * 1024, 0);
191         pthread_create(&uevq_thr, &attr, uevq_thread, NULL);
192
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                         bufpos += keylen + 1;
365                 }
366                 uev->envp[i] = NULL;
367
368                 condlog(3, "uevent '%s' from '%s'", uev->action, uev->devpath);
369
370                 /* print payload environment */
371                 for (i = 0; uev->envp[i] != NULL; i++)
372                         condlog(3, "%s", uev->envp[i]);
373
374                 /*
375                  * Queue uevent and poke service pthread.
376                  */
377                 pthread_mutex_lock(uevq_lockp);
378                 list_add_tail(&uev->node, &uevq);
379                 pthread_cond_signal(uev_condp);
380                 pthread_mutex_unlock(uevq_lockp);
381         }
382
383 exit:
384         close(sock);
385
386         pthread_cleanup_pop(1);
387
388         pthread_mutex_destroy(uevq_lockp);
389         pthread_cond_destroy(uev_condp);
390
391         return 1;
392 }