Update copyright notices with scripts/update-copyrights
[glibc.git] / sysdeps / pthread / aio_misc.c
blob5ebceeee402f872634229d32c08625bde28713d3
1 /* Handle general operations.
2 Copyright (C) 1997-2014 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
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.
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.
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/>. */
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>
32 #ifndef aio_create_helper_thread
33 # define aio_create_helper_thread __aio_create_helper_thread
35 extern inline int
36 __aio_create_helper_thread (pthread_t *threadp, void *(*tf) (void *), void *arg)
38 pthread_attr_t attr;
40 /* Make sure the thread is created detached. */
41 pthread_attr_init (&attr);
42 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
44 int ret = pthread_create (threadp, &attr, tf, arg);
46 (void) pthread_attr_destroy (&attr);
47 return ret;
49 #endif
51 static void add_request_to_runlist (struct requestlist *newrequest);
53 /* Pool of request list entries. */
54 static struct requestlist **pool;
56 /* Number of total and allocated pool entries. */
57 static size_t pool_max_size;
58 static size_t pool_size;
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
65 /* How many rows we allocate at once. */
66 #define ROWS_STEP 8
68 /* List of available entries. */
69 static struct requestlist *freelist;
71 /* List of request waiting to be processed. */
72 static struct requestlist *runlist;
74 /* Structure list of all currently processed requests. */
75 static struct requestlist *requests;
77 /* Number of threads currently running. */
78 static int nthreads;
80 /* Number of threads waiting for work to arrive. */
81 static int idle_thread_count;
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 =
88 20, /* int aio_threads; Maximal number of threads. */
89 64, /* int aio_num; Number of expected simultaneous requests. */
99 /* Since the list is global we need a mutex protecting it. */
100 pthread_mutex_t __aio_requests_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
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;
108 /* Functions to handle request list pool. */
109 static struct requestlist *
110 get_elem (void)
112 struct requestlist *result;
114 if (freelist == NULL)
116 struct requestlist *new_row;
117 int cnt;
119 assert (sizeof (struct aiocb) == sizeof (struct aiocb64));
121 if (pool_size + 1 >= pool_max_size)
123 size_t new_max_size = pool_max_size + ROWS_STEP;
124 struct requestlist **new_tab;
126 new_tab = (struct requestlist **)
127 realloc (pool, new_max_size * sizeof (struct requestlist *));
129 if (new_tab == NULL)
130 return NULL;
132 pool_max_size = new_max_size;
133 pool = new_tab;
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;
143 pool[pool_size++] = new_row;
145 /* Put all the new entries in the freelist. */
148 new_row->next_prio = freelist;
149 freelist = new_row++;
151 while (--cnt > 0);
154 result = freelist;
155 freelist = freelist->next_prio;
157 return result;
161 void
162 internal_function
163 __aio_free_request (struct requestlist *elem)
165 elem->running = no;
166 elem->next_prio = freelist;
167 freelist = elem;
171 struct requestlist *
172 internal_function
173 __aio_find_req (aiocb_union *elem)
175 struct requestlist *runp = requests;
176 int fildes = elem->aiocb.aio_fildes;
178 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
179 runp = runp->next_fd;
181 if (runp != NULL)
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;
190 return runp;
194 struct requestlist *
195 internal_function
196 __aio_find_req_fd (int fildes)
198 struct requestlist *runp = requests;
200 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
201 runp = runp->next_fd;
203 return (runp != NULL && runp->aiocbp->aiocb.aio_fildes == fildes
204 ? runp : NULL);
208 void
209 internal_function
210 __aio_remove_request (struct requestlist *last, struct requestlist *req,
211 int all)
213 assert (req->running == yes || req->running == queued
214 || req->running == done);
216 if (last != NULL)
217 last->next_prio = all ? NULL : req->next_prio;
218 else
220 if (all || req->next_prio == NULL)
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;
229 else
231 if (req->last_fd != NULL)
232 req->last_fd->next_fd = req->next_prio;
233 else
234 requests = req->next_prio;
236 if (req->next_fd != NULL)
237 req->next_fd->last_fd = req->next_prio;
239 req->next_prio->last_fd = req->last_fd;
240 req->next_prio->next_fd = req->next_fd;
242 /* Mark this entry as runnable. */
243 req->next_prio->running = yes;
246 if (req->running == yes)
248 struct requestlist *runp = runlist;
250 last = NULL;
251 while (runp != NULL)
253 if (runp == req)
255 if (last == NULL)
256 runlist = runp->next_run;
257 else
258 last->next_run = runp->next_run;
259 break;
261 last = runp;
262 runp = runp->next_run;
269 /* The thread handler. */
270 static void *handle_fildes_io (void *arg);
273 /* User optimization. */
274 void
275 __aio_init (const struct aioinit *init)
277 /* Get the mutex. */
278 pthread_mutex_lock (&__aio_requests_mutex);
280 /* Only allow writing new values if the table is not yet allocated. */
281 if (pool == NULL)
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));
290 if (init->aio_idle_time != 0)
291 optim.aio_idle_time = init->aio_idle_time;
293 /* Release the mutex. */
294 pthread_mutex_unlock (&__aio_requests_mutex);
296 weak_alias (__aio_init, aio_init)
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)
305 int result = 0;
306 int policy, prio;
307 struct sched_param param;
308 struct requestlist *last, *runp, *newp;
309 int running = no;
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)
316 /* Invalid priority value. */
317 __set_errno (EINVAL);
318 aiocbp->aiocb.__error_code = EINVAL;
319 aiocbp->aiocb.__return_value = -1;
320 return NULL;
323 /* Compute priority for this request. */
324 pthread_getschedparam (pthread_self (), &policy, &param);
325 prio = param.sched_priority - aiocbp->aiocb.aio_reqprio;
327 /* Get the mutex. */
328 pthread_mutex_lock (&__aio_requests_mutex);
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)
337 last = runp;
338 runp = runp->next_fd;
341 /* Get a new element for the waiting list. */
342 newp = get_elem ();
343 if (newp == NULL)
345 pthread_mutex_unlock (&__aio_requests_mutex);
346 __set_errno (EAGAIN);
347 return NULL;
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;
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;
362 if (runp != NULL
363 && runp->aiocbp->aiocb.aio_fildes == aiocbp->aiocb.aio_fildes)
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. */
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)
379 last = runp;
380 runp = runp->next_prio;
383 newp->next_prio = runp->next_prio;
384 runp->next_prio = newp;
386 running = queued;
388 else
390 running = yes;
391 /* Enqueue this request for a new descriptor. */
392 if (last == NULL)
394 newp->last_fd = NULL;
395 newp->next_fd = requests;
396 if (requests != NULL)
397 requests->last_fd = newp;
398 requests = newp;
400 else
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;
409 newp->next_prio = NULL;
410 last = NULL;
413 if (running == yes)
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.
420 If no new thread can be created or if the specified limit of
421 threads for AIO is reached we queue the request. */
423 /* See if we need to and are able to create a thread. */
424 if (nthreads < optim.aio_threads && idle_thread_count == 0)
426 pthread_t thid;
428 running = newp->running = allocated;
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
439 /* Reset the running flag. The new request is not running. */
440 running = newp->running = yes;
442 if (nthreads == 0)
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);
449 else
450 result = 0;
455 /* Enqueue the request in the run queue if it is not yet running. */
456 if (running == yes && result == 0)
458 add_request_to_runlist (newp);
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);
466 if (result == 0)
467 newp->running = running;
468 else
470 /* Something went wrong. */
471 __aio_free_request (newp);
472 aiocbp->aiocb.__error_code = result;
473 __set_errno (result);
474 newp = NULL;
477 /* Release the mutex. */
478 pthread_mutex_unlock (&__aio_requests_mutex);
480 return newp;
484 static void *
485 handle_fildes_io (void *arg)
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;
494 pthread_getschedparam (self, &policy, &param);
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
507 /* Hopefully this request is marked as running. */
508 assert (runp->running == allocated);
510 /* Update our variables. */
511 aiocbp = runp->aiocbp;
512 fildes = aiocbp->aiocb.aio_fildes;
514 /* Change the priority to the requested value (if necessary). */
515 if (aiocbp->aiocb.__abs_prio != param.sched_priority
516 || aiocbp->aiocb.__policy != policy)
518 param.sched_priority = aiocbp->aiocb.__abs_prio;
519 policy = aiocbp->aiocb.__policy;
520 pthread_setschedparam (self, policy, &param);
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)
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));
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));
551 else if ((aiocbp->aiocb.aio_lio_opcode & 127) == LIO_WRITE)
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));
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));
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
585 /* This is an invalid opcode. */
586 aiocbp->aiocb.__return_value = -1;
587 __set_errno (EINVAL);
590 /* Get the mutex. */
591 pthread_mutex_lock (&__aio_requests_mutex);
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.
598 But since the pthread_mutex_lock call involves write memory
599 barriers as well it is not necessary. */
601 if (aiocbp->aiocb.__return_value == -1)
602 aiocbp->aiocb.__error_code = errno;
603 else
604 aiocbp->aiocb.__error_code = 0;
606 /* Send the signal to notify about finished processing of the
607 request. */
608 __aio_notify (runp);
610 /* For debugging purposes we reset the running flag of the
611 finished request. */
612 assert (runp->running == allocated);
613 runp->running = done;
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);
620 /* Free the old element. */
621 __aio_free_request (runp);
624 runp = runlist;
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)
630 struct timeval now;
631 struct timespec wakeup_time;
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)
639 wakeup_time.tv_nsec -= 1000000000;
640 ++wakeup_time.tv_sec;
642 pthread_cond_timedwait (&__aio_new_request_notification,
643 &__aio_requests_mutex,
644 &wakeup_time);
645 --idle_thread_count;
646 runp = runlist;
649 if (runp == NULL)
650 --nthreads;
651 else
653 assert (runp->running == yes);
654 runp->running = allocated;
655 runlist = runp->next_run;
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)
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)
670 pthread_t thid;
671 pthread_attr_t attr;
673 /* Make sure the thread is created detached. */
674 pthread_attr_init (&attr);
675 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
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;
687 /* Release the mutex. */
688 pthread_mutex_unlock (&__aio_requests_mutex);
690 while (runp != NULL);
692 return NULL;
696 /* Free allocated resources. */
697 libc_freeres_fn (free_res)
699 size_t row;
701 for (row = 0; row < pool_max_size; ++row)
702 free (pool[row]);
704 free (pool);
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)
715 int prio = newrequest->aiocbp->aiocb.__abs_prio;
716 struct requestlist *runp;
718 if (runlist == NULL || runlist->aiocbp->aiocb.__abs_prio < prio)
720 newrequest->next_run = runlist;
721 runlist = newrequest;
723 else
725 runp = runlist;
727 while (runp->next_run != NULL
728 && runp->next_run->aiocbp->aiocb.__abs_prio >= prio)
729 runp = runp->next_run;
731 newrequest->next_run = runp->next_run;
732 runp->next_run = newrequest;