1/* -*- c-basic-offset: 8; -*-
2 *
3 * Copyright (c) 1993 W. Richard Stevens.  All rights reserved.
4 * Permission to use or modify this software and its documentation only for
5 * educational purposes and without fee is hereby granted, provided that
6 * the above copyright notice appear in all copies.  The author makes no
7 * representations about the suitability of this software for any purpose.
8 * It is provided "as is" without express or implied warranty.
9 */
10
11#include "sock.h"
12
13#ifndef	UIO_MAXIOV
14#define	UIO_MAXIOV	16	/* we assume this; may not be true? */
15#endif
16
17ssize_t
18dowrite(int fd, const void *vptr, size_t nbytes)
19{
20	struct iovec	iov[UIO_MAXIOV];
21	const char     *ptr;
22	int		chunksize, i, n, nleft, nwritten, ntotal;
23
24	if (chunkwrite == 0 && usewritev == 0)
25		return(write(fd, vptr, nbytes));		/* common case */
26
27	/*
28	 * Figure out what sized chunks to write.
29	 * Try to use UIO_MAXIOV chunks.
30	 */
31
32	chunksize = nbytes / UIO_MAXIOV;
33	if (chunksize <= 0)
34		chunksize = 1;
35	else if ((nbytes % UIO_MAXIOV) != 0)
36		chunksize++;
37
38	ptr = vptr;
39	nleft = nbytes;
40	for (i = 0; i < UIO_MAXIOV; i++)
41	  {
42	    iov[i].iov_base = (void *) ptr;
43	    n = (nleft >= chunksize) ? chunksize : nleft;
44	    iov[i].iov_len = n;
45	    if (verbose)
46	      fprintf(stderr, "iov[%2d].iov_base = %x, iov[%2d].iov_len = %d\n",
47		      i, (u_int32_t) iov[i].iov_base, i, (int) iov[i].iov_len);
48		ptr += n;
49		if ((nleft -= n) == 0)
50			break;
51	}
52	if (i == UIO_MAXIOV)
53		err_quit("i == UIO_MAXIOV");
54
55	if (usewritev)
56		return(writev(fd, iov, i+1));
57	else {
58		ntotal = 0;
59		for (n = 0; n <= i; n++) {
60			nwritten = write(fd, iov[n].iov_base, iov[n].iov_len);
61			if (nwritten != (int) iov[n].iov_len)
62				return(-1);
63			ntotal += nwritten;
64		}
65		return(ntotal);
66	}
67}
68