1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24 * Use is subject to license terms.
25 */
26
27/*	Copyright (c) 1988 AT&T	*/
28/*	  All Rights Reserved	*/
29
30#include "lint.h"
31#include "file64.h"
32#include "mtlib.h"
33#include <sys/types.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <thread.h>
37#include <synch.h>
38#include "stdiom.h"
39
40int
41setvbuf(FILE *iop, char *abuf, int type, size_t size)
42{
43
44	Uchar	*buf = (Uchar *)abuf;
45	Uchar *temp;
46	int	sflag = iop->_flag & _IOMYBUF;
47	rmutex_t *lk;
48	int fd = _get_fd(iop);
49
50	FLOCKFILE(lk, iop);
51	iop->_flag &= ~(_IOMYBUF | _IONBF | _IOLBF);
52	switch (type) {
53	/* note that the flags are the same as the possible values for type */
54	case _IONBF:
55		iop->_flag |= _IONBF;	 /* file is unbuffered */
56		if (fd == 0 || fd == 1) {
57			/* use special buffer for std{in,out} */
58			buf = (fd == 0) ? _sibuf : _sobuf;
59			size = BUFSIZ;
60		} else if (fd >= 2 && fd < _NFILE) {
61			buf = _smbuf[fd];
62			size = _SMBFSZ - PUSHBACK;
63		} else {
64			if ((buf = malloc(_SMBFSZ * sizeof (Uchar))) != NULL) {
65				iop->_flag |= _IOMYBUF;
66				size = _SMBFSZ - PUSHBACK;
67			} else {
68				FUNLOCKFILE(lk);
69				return (EOF);
70			}
71		}
72		break;
73	case _IOLBF:
74	case _IOFBF:
75		iop->_flag |= type;	/* buffer file */
76		/*
77		 * need at least an 8 character buffer for
78		 * out_of_sync concerns.
79		 */
80		if (size <= _SMBFSZ) {
81			size = BUFSIZ;
82			buf = NULL;
83		}
84		if (buf == NULL) {
85			if ((buf = malloc(sizeof (Uchar) *
86			    (size + _SMBFSZ))) != NULL)
87				iop->_flag |= _IOMYBUF;
88			else {
89				FUNLOCKFILE(lk);
90				return (EOF);
91			}
92		}
93		else
94			size -= _SMBFSZ;
95		break;
96	default:
97		FUNLOCKFILE(lk);
98		return (EOF);
99	}
100	if (iop->_base != NULL && sflag)
101		free((char *)iop->_base - PUSHBACK);
102	temp = buf + PUSHBACK;
103	iop->_base = temp;
104	_setbufend(iop, temp + size);
105	iop->_ptr = temp;
106	iop->_cnt = 0;
107	FUNLOCKFILE(lk);
108	return (0);
109}
110