]> git.ipfire.org Git - thirdparty/glibc.git/blob - sysdeps/pthread/aio_misc.c
Update copyright dates with scripts/update-copyrights.
[thirdparty/glibc.git] / sysdeps / pthread / aio_misc.c
1 /* Handle general operations.
2 Copyright (C) 1997-2015 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
5
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <http://www.gnu.org/licenses/>. */
19
20 #include <aio.h>
21 #include <assert.h>
22 #include <errno.h>
23 #include <limits.h>
24 #include <pthread.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <sys/param.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30 #include <aio_misc.h>
31
32 #ifndef aio_create_helper_thread
33 # define aio_create_helper_thread __aio_create_helper_thread
34
35 extern inline int
36 __aio_create_helper_thread (pthread_t *threadp, void *(*tf) (void *), void *arg)
37 {
38 pthread_attr_t attr;
39
40 /* Make sure the thread is created detached. */
41 pthread_attr_init (&attr);
42 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
43
44 int ret = pthread_create (threadp, &attr, tf, arg);
45
46 (void) pthread_attr_destroy (&attr);
47 return ret;
48 }
49 #endif
50
51 static void add_request_to_runlist (struct requestlist *newrequest);
52
53 /* Pool of request list entries. */
54 static struct requestlist **pool;
55
56 /* Number of total and allocated pool entries. */
57 static size_t pool_max_size;
58 static size_t pool_size;
59
60 /* We implement a two dimensional array but allocate each row separately.
61 The macro below determines how many entries should be used per row.
62 It should better be a power of two. */
63 #define ENTRIES_PER_ROW 32
64
65 /* How many rows we allocate at once. */
66 #define ROWS_STEP 8
67
68 /* List of available entries. */
69 static struct requestlist *freelist;
70
71 /* List of request waiting to be processed. */
72 static struct requestlist *runlist;
73
74 /* Structure list of all currently processed requests. */
75 static struct requestlist *requests;
76
77 /* Number of threads currently running. */
78 static int nthreads;
79
80 /* Number of threads waiting for work to arrive. */
81 static int idle_thread_count;
82
83
84 /* These are the values used to optimize the use of AIO. The user can
85 overwrite them by using the `aio_init' function. */
86 static struct aioinit optim =
87 {
88 20, /* int aio_threads; Maximal number of threads. */
89 64, /* int aio_num; Number of expected simultaneous requests. */
90 0,
91 0,
92 0,
93 0,
94 1,
95 0
96 };
97
98
99 /* Since the list is global we need a mutex protecting it. */
100 pthread_mutex_t __aio_requests_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
101
102 /* When you add a request to the list and there are idle threads present,
103 you signal this condition variable. When a thread finishes work, it waits
104 on this condition variable for a time before it actually exits. */
105 pthread_cond_t __aio_new_request_notification = PTHREAD_COND_INITIALIZER;
106
107
108 /* Functions to handle request list pool. */
109 static struct requestlist *
110 get_elem (void)
111 {
112 struct requestlist *result;
113
114 if (freelist == NULL)
115 {
116 struct requestlist *new_row;
117 int cnt;
118
119 assert (sizeof (struct aiocb) == sizeof (struct aiocb64));
120
121 if (pool_size + 1 >= pool_max_size)
122 {
123 size_t new_max_size = pool_max_size + ROWS_STEP;
124 struct requestlist **new_tab;
125
126 new_tab = (struct requestlist **)
127 realloc (pool, new_max_size * sizeof (struct requestlist *));
128
129 if (new_tab == NULL)
130 return NULL;
131
132 pool_max_size = new_max_size;
133 pool = new_tab;
134 }
135
136 /* Allocate the new row. */
137 cnt = pool_size == 0 ? optim.aio_num : ENTRIES_PER_ROW;
138 new_row = (struct requestlist *) calloc (cnt,
139 sizeof (struct requestlist));
140 if (new_row == NULL)
141 return NULL;
142
143 pool[pool_size++] = new_row;
144
145 /* Put all the new entries in the freelist. */
146 do
147 {
148 new_row->next_prio = freelist;
149 freelist = new_row++;
150 }
151 while (--cnt > 0);
152 }
153
154 result = freelist;
155 freelist = freelist->next_prio;
156
157 return result;
158 }
159
160
161 void
162 internal_function
163 __aio_free_request (struct requestlist *elem)
164 {
165 elem->running = no;
166 elem->next_prio = freelist;
167 freelist = elem;
168 }
169
170
171 struct requestlist *
172 internal_function
173 __aio_find_req (aiocb_union *elem)
174 {
175 struct requestlist *runp = requests;
176 int fildes = elem->aiocb.aio_fildes;
177
178 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
179 runp = runp->next_fd;
180
181 if (runp != NULL)
182 {
183 if (runp->aiocbp->aiocb.aio_fildes != fildes)
184 runp = NULL;
185 else
186 while (runp != NULL && runp->aiocbp != elem)
187 runp = runp->next_prio;
188 }
189
190 return runp;
191 }
192
193
194 struct requestlist *
195 internal_function
196 __aio_find_req_fd (int fildes)
197 {
198 struct requestlist *runp = requests;
199
200 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
201 runp = runp->next_fd;
202
203 return (runp != NULL && runp->aiocbp->aiocb.aio_fildes == fildes
204 ? runp : NULL);
205 }
206
207
208 void
209 internal_function
210 __aio_remove_request (struct requestlist *last, struct requestlist *req,
211 int all)
212 {
213 assert (req->running == yes || req->running == queued
214 || req->running == done);
215
216 if (last != NULL)
217 last->next_prio = all ? NULL : req->next_prio;
218 else
219 {
220 if (all || req->next_prio == NULL)
221 {
222 if (req->last_fd != NULL)
223 req->last_fd->next_fd = req->next_fd;
224 else
225 requests = req->next_fd;
226 if (req->next_fd != NULL)
227 req->next_fd->last_fd = req->last_fd;
228 }
229 else
230 {
231 if (req->last_fd != NULL)
232 req->last_fd->next_fd = req->next_prio;
233 else
234 requests = req->next_prio;
235
236 if (req->next_fd != NULL)
237 req->next_fd->last_fd = req->next_prio;
238
239 req->next_prio->last_fd = req->last_fd;
240 req->next_prio->next_fd = req->next_fd;
241
242 /* Mark this entry as runnable. */
243 req->next_prio->running = yes;
244 }
245
246 if (req->running == yes)
247 {
248 struct requestlist *runp = runlist;
249
250 last = NULL;
251 while (runp != NULL)
252 {
253 if (runp == req)
254 {
255 if (last == NULL)
256 runlist = runp->next_run;
257 else
258 last->next_run = runp->next_run;
259 break;
260 }
261 last = runp;
262 runp = runp->next_run;
263 }
264 }
265 }
266 }
267
268
269 /* The thread handler. */
270 static void *handle_fildes_io (void *arg);
271
272
273 /* User optimization. */
274 void
275 __aio_init (const struct aioinit *init)
276 {
277 /* Get the mutex. */
278 pthread_mutex_lock (&__aio_requests_mutex);
279
280 /* Only allow writing new values if the table is not yet allocated. */
281 if (pool == NULL)
282 {
283 optim.aio_threads = init->aio_threads < 1 ? 1 : init->aio_threads;
284 assert (powerof2 (ENTRIES_PER_ROW));
285 optim.aio_num = (init->aio_num < ENTRIES_PER_ROW
286 ? ENTRIES_PER_ROW
287 : init->aio_num & ~(ENTRIES_PER_ROW - 1));
288 }
289
290 if (init->aio_idle_time != 0)
291 optim.aio_idle_time = init->aio_idle_time;
292
293 /* Release the mutex. */
294 pthread_mutex_unlock (&__aio_requests_mutex);
295 }
296 weak_alias (__aio_init, aio_init)
297
298
299 /* The main function of the async I/O handling. It enqueues requests
300 and if necessary starts and handles threads. */
301 struct requestlist *
302 internal_function
303 __aio_enqueue_request (aiocb_union *aiocbp, int operation)
304 {
305 int result = 0;
306 int policy, prio;
307 struct sched_param param;
308 struct requestlist *last, *runp, *newp;
309 int running = no;
310
311 if (operation == LIO_SYNC || operation == LIO_DSYNC)
312 aiocbp->aiocb.aio_reqprio = 0;
313 else if (aiocbp->aiocb.aio_reqprio < 0
314 || aiocbp->aiocb.aio_reqprio > AIO_PRIO_DELTA_MAX)
315 {
316 /* Invalid priority value. */
317 __set_errno (EINVAL);
318 aiocbp->aiocb.__error_code = EINVAL;
319 aiocbp->aiocb.__return_value = -1;
320 return NULL;
321 }
322
323 /* Compute priority for this request. */
324 pthread_getschedparam (pthread_self (), &policy, &param);
325 prio = param.sched_priority - aiocbp->aiocb.aio_reqprio;
326
327 /* Get the mutex. */
328 pthread_mutex_lock (&__aio_requests_mutex);
329
330 last = NULL;
331 runp = requests;
332 /* First look whether the current file descriptor is currently
333 worked with. */
334 while (runp != NULL
335 && runp->aiocbp->aiocb.aio_fildes < aiocbp->aiocb.aio_fildes)
336 {
337 last = runp;
338 runp = runp->next_fd;
339 }
340
341 /* Get a new element for the waiting list. */
342 newp = get_elem ();
343 if (newp == NULL)
344 {
345 pthread_mutex_unlock (&__aio_requests_mutex);
346 __set_errno (EAGAIN);
347 return NULL;
348 }
349 newp->aiocbp = aiocbp;
350 #ifdef BROKEN_THREAD_SIGNALS
351 newp->caller_pid = (aiocbp->aiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL
352 ? getpid () : 0);
353 #endif
354 newp->waiting = NULL;
355
356 aiocbp->aiocb.__abs_prio = prio;
357 aiocbp->aiocb.__policy = policy;
358 aiocbp->aiocb.aio_lio_opcode = operation;
359 aiocbp->aiocb.__error_code = EINPROGRESS;
360 aiocbp->aiocb.__return_value = 0;
361
362 if (runp != NULL
363 && runp->aiocbp->aiocb.aio_fildes == aiocbp->aiocb.aio_fildes)
364 {
365 /* The current file descriptor is worked on. It makes no sense
366 to start another thread since this new thread would fight
367 with the running thread for the resources. But we also cannot
368 say that the thread processing this desriptor shall immediately
369 after finishing the current job process this request if there
370 are other threads in the running queue which have a higher
371 priority. */
372
373 /* Simply enqueue it after the running one according to the
374 priority. */
375 last = NULL;
376 while (runp->next_prio != NULL
377 && runp->next_prio->aiocbp->aiocb.__abs_prio >= prio)
378 {
379 last = runp;
380 runp = runp->next_prio;
381 }
382
383 newp->next_prio = runp->next_prio;
384 runp->next_prio = newp;
385
386 running = queued;
387 }
388 else
389 {
390 running = yes;
391 /* Enqueue this request for a new descriptor. */
392 if (last == NULL)
393 {
394 newp->last_fd = NULL;
395 newp->next_fd = requests;
396 if (requests != NULL)
397 requests->last_fd = newp;
398 requests = newp;
399 }
400 else
401 {
402 newp->next_fd = last->next_fd;
403 newp->last_fd = last;
404 last->next_fd = newp;
405 if (newp->next_fd != NULL)
406 newp->next_fd->last_fd = newp;
407 }
408
409 newp->next_prio = NULL;
410 last = NULL;
411 }
412
413 if (running == yes)
414 {
415 /* We try to create a new thread for this file descriptor. The
416 function which gets called will handle all available requests
417 for this descriptor and when all are processed it will
418 terminate.
419
420 If no new thread can be created or if the specified limit of
421 threads for AIO is reached we queue the request. */
422
423 /* See if we need to and are able to create a thread. */
424 if (nthreads < optim.aio_threads && idle_thread_count == 0)
425 {
426 pthread_t thid;
427
428 running = newp->running = allocated;
429
430 /* Now try to start a thread. */
431 result = aio_create_helper_thread (&thid, handle_fildes_io, newp);
432 if (result == 0)
433 /* We managed to enqueue the request. All errors which can
434 happen now can be recognized by calls to `aio_return' and
435 `aio_error'. */
436 ++nthreads;
437 else
438 {
439 /* Reset the running flag. The new request is not running. */
440 running = newp->running = yes;
441
442 if (nthreads == 0)
443 {
444 /* We cannot create a thread in the moment and there is
445 also no thread running. This is a problem. `errno' is
446 set to EAGAIN if this is only a temporary problem. */
447 __aio_remove_request (last, newp, 0);
448 }
449 else
450 result = 0;
451 }
452 }
453 }
454
455 /* Enqueue the request in the run queue if it is not yet running. */
456 if (running == yes && result == 0)
457 {
458 add_request_to_runlist (newp);
459
460 /* If there is a thread waiting for work, then let it know that we
461 have just given it something to do. */
462 if (idle_thread_count > 0)
463 pthread_cond_signal (&__aio_new_request_notification);
464 }
465
466 if (result == 0)
467 newp->running = running;
468 else
469 {
470 /* Something went wrong. */
471 __aio_free_request (newp);
472 aiocbp->aiocb.__error_code = result;
473 __set_errno (result);
474 newp = NULL;
475 }
476
477 /* Release the mutex. */
478 pthread_mutex_unlock (&__aio_requests_mutex);
479
480 return newp;
481 }
482
483
484 static void *
485 handle_fildes_io (void *arg)
486 {
487 pthread_t self = pthread_self ();
488 struct sched_param param;
489 struct requestlist *runp = (struct requestlist *) arg;
490 aiocb_union *aiocbp;
491 int policy;
492 int fildes;
493
494 pthread_getschedparam (self, &policy, &param);
495
496 do
497 {
498 /* If runp is NULL, then we were created to service the work queue
499 in general, not to handle any particular request. In that case we
500 skip the "do work" stuff on the first pass, and go directly to the
501 "get work off the work queue" part of this loop, which is near the
502 end. */
503 if (runp == NULL)
504 pthread_mutex_lock (&__aio_requests_mutex);
505 else
506 {
507 /* Hopefully this request is marked as running. */
508 assert (runp->running == allocated);
509
510 /* Update our variables. */
511 aiocbp = runp->aiocbp;
512 fildes = aiocbp->aiocb.aio_fildes;
513
514 /* Change the priority to the requested value (if necessary). */
515 if (aiocbp->aiocb.__abs_prio != param.sched_priority
516 || aiocbp->aiocb.__policy != policy)
517 {
518 param.sched_priority = aiocbp->aiocb.__abs_prio;
519 policy = aiocbp->aiocb.__policy;
520 pthread_setschedparam (self, policy, &param);
521 }
522
523 /* Process request pointed to by RUNP. We must not be disturbed
524 by signals. */
525 if ((aiocbp->aiocb.aio_lio_opcode & 127) == LIO_READ)
526 {
527 if (sizeof (off_t) != sizeof (off64_t)
528 && aiocbp->aiocb.aio_lio_opcode & 128)
529 aiocbp->aiocb.__return_value =
530 TEMP_FAILURE_RETRY (__pread64 (fildes, (void *)
531 aiocbp->aiocb64.aio_buf,
532 aiocbp->aiocb64.aio_nbytes,
533 aiocbp->aiocb64.aio_offset));
534 else
535 aiocbp->aiocb.__return_value =
536 TEMP_FAILURE_RETRY (pread (fildes,
537 (void *) aiocbp->aiocb.aio_buf,
538 aiocbp->aiocb.aio_nbytes,
539 aiocbp->aiocb.aio_offset));
540
541 if (aiocbp->aiocb.__return_value == -1 && errno == ESPIPE)
542 /* The Linux kernel is different from others. It returns
543 ESPIPE if using pread on a socket. Other platforms
544 simply ignore the offset parameter and behave like
545 read. */
546 aiocbp->aiocb.__return_value =
547 TEMP_FAILURE_RETRY (read (fildes,
548 (void *) aiocbp->aiocb64.aio_buf,
549 aiocbp->aiocb64.aio_nbytes));
550 }
551 else if ((aiocbp->aiocb.aio_lio_opcode & 127) == LIO_WRITE)
552 {
553 if (sizeof (off_t) != sizeof (off64_t)
554 && aiocbp->aiocb.aio_lio_opcode & 128)
555 aiocbp->aiocb.__return_value =
556 TEMP_FAILURE_RETRY (__pwrite64 (fildes, (const void *)
557 aiocbp->aiocb64.aio_buf,
558 aiocbp->aiocb64.aio_nbytes,
559 aiocbp->aiocb64.aio_offset));
560 else
561 aiocbp->aiocb.__return_value =
562 TEMP_FAILURE_RETRY (__libc_pwrite (fildes, (const void *)
563 aiocbp->aiocb.aio_buf,
564 aiocbp->aiocb.aio_nbytes,
565 aiocbp->aiocb.aio_offset));
566
567 if (aiocbp->aiocb.__return_value == -1 && errno == ESPIPE)
568 /* The Linux kernel is different from others. It returns
569 ESPIPE if using pwrite on a socket. Other platforms
570 simply ignore the offset parameter and behave like
571 write. */
572 aiocbp->aiocb.__return_value =
573 TEMP_FAILURE_RETRY (write (fildes,
574 (void *) aiocbp->aiocb64.aio_buf,
575 aiocbp->aiocb64.aio_nbytes));
576 }
577 else if (aiocbp->aiocb.aio_lio_opcode == LIO_DSYNC)
578 aiocbp->aiocb.__return_value =
579 TEMP_FAILURE_RETRY (fdatasync (fildes));
580 else if (aiocbp->aiocb.aio_lio_opcode == LIO_SYNC)
581 aiocbp->aiocb.__return_value =
582 TEMP_FAILURE_RETRY (fsync (fildes));
583 else
584 {
585 /* This is an invalid opcode. */
586 aiocbp->aiocb.__return_value = -1;
587 __set_errno (EINVAL);
588 }
589
590 /* Get the mutex. */
591 pthread_mutex_lock (&__aio_requests_mutex);
592
593 /* In theory we would need here a write memory barrier since the
594 callers test using aio_error() whether the request finished
595 and once this value != EINPROGRESS the field __return_value
596 must be committed to memory.
597
598 But since the pthread_mutex_lock call involves write memory
599 barriers as well it is not necessary. */
600
601 if (aiocbp->aiocb.__return_value == -1)
602 aiocbp->aiocb.__error_code = errno;
603 else
604 aiocbp->aiocb.__error_code = 0;
605
606 /* Send the signal to notify about finished processing of the
607 request. */
608 __aio_notify (runp);
609
610 /* For debugging purposes we reset the running flag of the
611 finished request. */
612 assert (runp->running == allocated);
613 runp->running = done;
614
615 /* Now dequeue the current request. */
616 __aio_remove_request (NULL, runp, 0);
617 if (runp->next_prio != NULL)
618 add_request_to_runlist (runp->next_prio);
619
620 /* Free the old element. */
621 __aio_free_request (runp);
622 }
623
624 runp = runlist;
625
626 /* If the runlist is empty, then we sleep for a while, waiting for
627 something to arrive in it. */
628 if (runp == NULL && optim.aio_idle_time >= 0)
629 {
630 struct timeval now;
631 struct timespec wakeup_time;
632
633 ++idle_thread_count;
634 __gettimeofday (&now, NULL);
635 wakeup_time.tv_sec = now.tv_sec + optim.aio_idle_time;
636 wakeup_time.tv_nsec = now.tv_usec * 1000;
637 if (wakeup_time.tv_nsec >= 1000000000)
638 {
639 wakeup_time.tv_nsec -= 1000000000;
640 ++wakeup_time.tv_sec;
641 }
642 pthread_cond_timedwait (&__aio_new_request_notification,
643 &__aio_requests_mutex,
644 &wakeup_time);
645 --idle_thread_count;
646 runp = runlist;
647 }
648
649 if (runp == NULL)
650 --nthreads;
651 else
652 {
653 assert (runp->running == yes);
654 runp->running = allocated;
655 runlist = runp->next_run;
656
657 /* If we have a request to process, and there's still another in
658 the run list, then we need to either wake up or create a new
659 thread to service the request that is still in the run list. */
660 if (runlist != NULL)
661 {
662 /* There are at least two items in the work queue to work on.
663 If there are other idle threads, then we should wake them
664 up for these other work elements; otherwise, we should try
665 to create a new thread. */
666 if (idle_thread_count > 0)
667 pthread_cond_signal (&__aio_new_request_notification);
668 else if (nthreads < optim.aio_threads)
669 {
670 pthread_t thid;
671 pthread_attr_t attr;
672
673 /* Make sure the thread is created detached. */
674 pthread_attr_init (&attr);
675 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
676
677 /* Now try to start a thread. If we fail, no big deal,
678 because we know that there is at least one thread (us)
679 that is working on AIO operations. */
680 if (pthread_create (&thid, &attr, handle_fildes_io, NULL)
681 == 0)
682 ++nthreads;
683 }
684 }
685 }
686
687 /* Release the mutex. */
688 pthread_mutex_unlock (&__aio_requests_mutex);
689 }
690 while (runp != NULL);
691
692 return NULL;
693 }
694
695
696 /* Free allocated resources. */
697 libc_freeres_fn (free_res)
698 {
699 size_t row;
700
701 for (row = 0; row < pool_max_size; ++row)
702 free (pool[row]);
703
704 free (pool);
705 }
706
707
708 /* Add newrequest to the runlist. The __abs_prio flag of newrequest must
709 be correctly set to do this. Also, you had better set newrequest's
710 "running" flag to "yes" before you release your lock or you'll throw an
711 assertion. */
712 static void
713 add_request_to_runlist (struct requestlist *newrequest)
714 {
715 int prio = newrequest->aiocbp->aiocb.__abs_prio;
716 struct requestlist *runp;
717
718 if (runlist == NULL || runlist->aiocbp->aiocb.__abs_prio < prio)
719 {
720 newrequest->next_run = runlist;
721 runlist = newrequest;
722 }
723 else
724 {
725 runp = runlist;
726
727 while (runp->next_run != NULL
728 && runp->next_run->aiocbp->aiocb.__abs_prio >= prio)
729 runp = runp->next_run;
730
731 newrequest->next_run = runp->next_run;
732 runp->next_run = newrequest;
733 }
734 }