xref: /netbsd-src/external/cddl/osnet/sys/kern/ddi.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License, Version 1.0 only
7  * (the "License").  You may not use this file except in compliance
8  * with the License.
9  *
10  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
11  * or http://www.opensolaris.org/os/licensing.
12  * See the License for the specific language governing permissions
13  * and limitations under the License.
14  *
15  * When distributing Covered Code, include this CDDL HEADER in each
16  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
17  * If applicable, add the following below this CDDL HEADER, with the
18  * fields enclosed by brackets "[]" replaced with your own identifying
19  * information: Portions Copyright [yyyy] [name of copyright owner]
20  *
21  * CDDL HEADER END
22  */
23 /*
24  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 /*	Copyright (c) 1988 AT&T	*/
29 /*	All Rights Reserved */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/types.h>
34 #include <sys/ddi.h>
35 #include <sys/debug.h>
36 #include <sys/errno.h>
37 #include <sys/param.h>
38 #include <sys/kernel.h>
39 #include <sys/kmem.h>
40 #include <sys/cmn_err.h>
41 #include <sys/namei.h>
42 #include <sys/stat.h>
43 #include <sys/vfs_syscalls.h>
44 
45 __strong_alias(ddi_strtol,ddi_strtoul)
46 
47 /*
48  * String to integer conversion routines.
49  *
50  * This file is derived from usr/src/common/util/strtol.c
51  *
52  * We cannot use the user land versions as there is no errno to report
53  * error in kernel.  So the return value is used to return an error,
54  * and the result is stored in an extra parameter passed by reference.
55  * Otherwise, the following functions are identical to the user land
56  * versions.
57  */
58 
59 /*
60  * We should have a kernel version of ctype.h.
61  */
62 #define	isalnum(ch)	(isalpha(ch) || isdigit(ch))
63 #define	isalpha(ch)	(isupper(ch) || islower(ch))
64 #define	isdigit(ch)	((ch) >= '0' && (ch) <= '9')
65 #define	islower(ch)	((ch) >= 'a' && (ch) <= 'z')
66 #define	isspace(ch)	(((ch) == ' ') || ((ch) == '\r') || ((ch) == '\n') || \
67 			((ch) == '\t') || ((ch) == '\f'))
68 #define	isupper(ch)	((ch) >= 'A' && (ch) <= 'Z')
69 #define	isxdigit(ch)	(isdigit(ch) || ((ch) >= 'a' && (ch) <= 'f') || \
70 			((ch) >= 'A' && (ch) <= 'F'))
71 
72 #define	DIGIT(x)	\
73 	(isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
74 
75 #define	MBASE	('z' - 'a' + 1 + 10)
76 
77 /*
78  * The following macro is a local version of isalnum() which limits
79  * alphabetic characters to the ranges a-z and A-Z; locale dependent
80  * characters will not return 1. The members of a-z and A-Z are
81  * assumed to be in ascending order and contiguous
82  */
83 #define	lisalnum(x)	\
84 	(isdigit(x) || ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))
85 
86 static int
87 do_mkdirp(const char *path)
88 {
89 	struct lwp *l = curlwp;
90 	int mode;
91 	int error;
92 	register_t ret;
93 
94 	const char *s, *e;
95 	char *here;
96 
97 	error = 0;
98 	mode = 493;
99 
100 	if (*path != '/')
101 		panic("Not an absolute path");
102 
103 	here = PNBUF_GET();
104 	for (s = path;; s = e) {
105 		e = strchr(s + 1, '/');
106 		if (e == NULL)
107 			break;
108 
109 		strlcpy(here, path, e - path + 1);
110 		error = do_sys_mkdir((const char *)here, mode, UIO_SYSSPACE);
111 	}
112 	PNBUF_PUT(here);
113 
114 	if (error == EEXIST)
115 		error = 0;
116 
117 	return error;
118 }
119 
120 int
121 ddi_strtoul(const char *str, char **nptr, int base, unsigned long *result)
122 {
123 	unsigned long val;
124 	int c;
125 	int xx;
126 	unsigned long	multmax;
127 	int neg = 0;
128 	const char **ptr = (const char **)nptr;
129 	const unsigned char	*ustr = (const unsigned char *)str;
130 
131 	if (ptr != (const char **)0)
132 		*ptr = (char *)ustr; /* in case no number is formed */
133 	if (base < 0 || base > MBASE || base == 1) {
134 		/* base is invalid -- should be a fatal error */
135 		return (EINVAL);
136 	}
137 	if (!isalnum(c = *ustr)) {
138 		while (isspace(c))
139 			c = *++ustr;
140 		switch (c) {
141 		case '-':
142 			neg++;
143 			/* FALLTHROUGH */
144 		case '+':
145 			c = *++ustr;
146 		}
147 	}
148 	if (base == 0)
149 		if (c != '0')
150 			base = 10;
151 		else if (ustr[1] == 'x' || ustr[1] == 'X')
152 			base = 16;
153 		else
154 			base = 8;
155 	/*
156 	 * for any base > 10, the digits incrementally following
157 	 *	9 are assumed to be "abc...z" or "ABC...Z"
158 	 */
159 	if (!lisalnum(c) || (xx = DIGIT(c)) >= base)
160 		return (EINVAL); /* no number formed */
161 	if (base == 16 && c == '0' && (ustr[1] == 'x' || ustr[1] == 'X') &&
162 	    isxdigit(ustr[2]))
163 		c = *(ustr += 2); /* skip over leading "0x" or "0X" */
164 
165 	multmax = ULONG_MAX / (unsigned long)base;
166 	val = DIGIT(c);
167 	for (c = *++ustr; lisalnum(c) && (xx = DIGIT(c)) < base; ) {
168 		if (val > multmax)
169 			goto overflow;
170 		val *= base;
171 		if (ULONG_MAX - val < xx)
172 			goto overflow;
173 		val += xx;
174 		c = *++ustr;
175 	}
176 	if (ptr != (const char **)0)
177 		*ptr = (char *)ustr;
178 	*result = neg ? -val : val;
179 	return (0);
180 
181 overflow:
182 	for (c = *++ustr; lisalnum(c) && (xx = DIGIT(c)) < base; (c = *++ustr))
183 		;
184 	if (ptr != (const char **)0)
185 		*ptr = (char *)ustr;
186 	return (ERANGE);
187 }
188 
189 /*
190  * Find first bit set in a mask (returned counting from 1 up)
191  */
192 
193 int
194 ddi_ffs(long mask)
195 {
196 	return (ffs(mask));
197 }
198 
199 /*
200  * Find last bit set. Take mask and clear
201  * all but the most significant bit, and
202  * then let ffs do the rest of the work.
203  *
204  * Algorithm courtesy of Steve Chessin.
205  */
206 
207 int
208 ddi_fls(long mask)
209 {
210 	while (mask) {
211 		long nx;
212 
213 		if ((nx = (mask & (mask - 1))) == 0)
214 			break;
215 		mask = nx;
216 	}
217 	return (ffs(mask));
218 }
219 
220 /*
221  * The next five routines comprise generic storage management utilities
222  * for driver soft state structures (in "the old days," this was done
223  * with a statically sized array - big systems and dynamic loading
224  * and unloading make heap allocation more attractive)
225  */
226 
227 /*
228  * Allocate a set of pointers to 'n_items' objects of size 'size'
229  * bytes.  Each pointer is initialized to nil.
230  *
231  * The 'size' and 'n_items' values are stashed in the opaque
232  * handle returned to the caller.
233  *
234  * This implementation interprets 'set of pointers' to mean 'array
235  * of pointers' but note that nothing in the interface definition
236  * precludes an implementation that uses, for example, a linked list.
237  * However there should be a small efficiency gain from using an array
238  * at lookup time.
239  *
240  * NOTE	As an optimization, we make our growable array allocations in
241  *	powers of two (bytes), since that's how much kmem_alloc (currently)
242  *	gives us anyway.  It should save us some free/realloc's ..
243  *
244  *	As a further optimization, we make the growable array start out
245  *	with MIN_N_ITEMS in it.
246  */
247 
248 /*
249  * This data structure is entirely private to the soft state allocator.
250  */
251 struct i_ddi_soft_state {
252 	void		**array;	/* the array of pointers */
253 	kmutex_t	lock;	/* serialize access to this struct */
254 	size_t		size;	/* how many bytes per state struct */
255 	size_t		n_items;	/* how many structs herein */
256 	struct i_ddi_soft_state *next;	/* 'dirty' elements */
257 };
258 
259 #define	MIN_N_ITEMS	8	/* 8 void *'s == 32 bytes */
260 
261 int
262 ddi_soft_state_init(void **state_p, size_t size, size_t n_items)
263 {
264 	struct i_ddi_soft_state *ss;
265 
266 	if (state_p == NULL || *state_p != NULL || size == 0)
267 		return (EINVAL);
268 
269 	ss = kmem_zalloc(sizeof (*ss), KM_SLEEP);
270 	mutex_init(&ss->lock, NULL, MUTEX_DRIVER, NULL);
271 	ss->size = size;
272 
273 	if (n_items < MIN_N_ITEMS)
274 		ss->n_items = MIN_N_ITEMS;
275 	else {
276 		int bitlog;
277 
278 		if ((bitlog = ddi_fls(n_items)) == ddi_ffs(n_items))
279 			bitlog--;
280 		ss->n_items = 1 << bitlog;
281 	}
282 
283 	ASSERT(ss->n_items >= n_items);
284 
285 	ss->array = kmem_zalloc(ss->n_items * sizeof (void *), KM_SLEEP);
286 
287 	*state_p = ss;
288 
289 	return (0);
290 }
291 
292 
293 /*
294  * Allocate a state structure of size 'size' to be associated
295  * with item 'item'.
296  *
297  * In this implementation, the array is extended to
298  * allow the requested offset, if needed.
299  */
300 int
301 ddi_soft_state_zalloc(void *state, int item)
302 {
303 	struct i_ddi_soft_state *ss;
304 	void **array;
305 	void *new_element;
306 
307 	if ((ss = state) == NULL || item < 0)
308 		return (DDI_FAILURE);
309 
310 	mutex_enter(&ss->lock);
311 	if (ss->size == 0) {
312 		mutex_exit(&ss->lock);
313 		cmn_err(CE_WARN, "ddi_soft_state_zalloc: bad handle");
314 		return (DDI_FAILURE);
315 	}
316 
317 	array = ss->array;	/* NULL if ss->n_items == 0 */
318 	ASSERT(ss->n_items != 0 && array != NULL);
319 
320 	/*
321 	 * refuse to tread on an existing element
322 	 */
323 	if (item < ss->n_items && array[item] != NULL) {
324 		mutex_exit(&ss->lock);
325 		return (DDI_FAILURE);
326 	}
327 
328 	/*
329 	 * Allocate a new element to plug in
330 	 */
331 	new_element = kmem_zalloc(ss->size, KM_SLEEP);
332 
333 	/*
334 	 * Check if the array is big enough, if not, grow it.
335 	 */
336 	if (item >= ss->n_items) {
337 		void	**new_array;
338 		size_t	new_n_items;
339 		struct i_ddi_soft_state *dirty;
340 
341 		/*
342 		 * Allocate a new array of the right length, copy
343 		 * all the old pointers to the new array, then
344 		 * if it exists at all, put the old array on the
345 		 * dirty list.
346 		 *
347 		 * Note that we can't kmem_free() the old array.
348 		 *
349 		 * Why -- well the 'get' operation is 'mutex-free', so we
350 		 * can't easily catch a suspended thread that is just about
351 		 * to dereference the array we just grew out of.  So we
352 		 * cons up a header and put it on a list of 'dirty'
353 		 * pointer arrays.  (Dirty in the sense that there may
354 		 * be suspended threads somewhere that are in the middle
355 		 * of referencing them).  Fortunately, we -can- garbage
356 		 * collect it all at ddi_soft_state_fini time.
357 		 */
358 		new_n_items = ss->n_items;
359 		while (new_n_items < (1 + item))
360 			new_n_items <<= 1;	/* double array size .. */
361 
362 		ASSERT(new_n_items >= (1 + item));	/* sanity check! */
363 
364 		new_array = kmem_zalloc(new_n_items * sizeof (void *),
365 		    KM_SLEEP);
366 		/*
367 		 * Copy the pointers into the new array
368 		 */
369 		bcopy(array, new_array, ss->n_items * sizeof (void *));
370 
371 		/*
372 		 * Save the old array on the dirty list
373 		 */
374 		dirty = kmem_zalloc(sizeof (*dirty), KM_SLEEP);
375 		dirty->array = ss->array;
376 		dirty->n_items = ss->n_items;
377 		dirty->next = ss->next;
378 		ss->next = dirty;
379 
380 		ss->array = (array = new_array);
381 		ss->n_items = new_n_items;
382 	}
383 
384 	ASSERT(array != NULL && item < ss->n_items && array[item] == NULL);
385 
386 	array[item] = new_element;
387 
388 	mutex_exit(&ss->lock);
389 	return (DDI_SUCCESS);
390 }
391 
392 
393 /*
394  * Fetch a pointer to the allocated soft state structure.
395  *
396  * This is designed to be cheap.
397  *
398  * There's an argument that there should be more checking for
399  * nil pointers and out of bounds on the array.. but we do a lot
400  * of that in the alloc/free routines.
401  *
402  * An array has the convenience that we don't need to lock read-access
403  * to it c.f. a linked list.  However our "expanding array" strategy
404  * means that we should hold a readers lock on the i_ddi_soft_state
405  * structure.
406  *
407  * However, from a performance viewpoint, we need to do it without
408  * any locks at all -- this also makes it a leaf routine.  The algorithm
409  * is 'lock-free' because we only discard the pointer arrays at
410  * ddi_soft_state_fini() time.
411  */
412 void *
413 ddi_get_soft_state(void *state, int item)
414 {
415 	struct i_ddi_soft_state *ss = state;
416 
417 	ASSERT(ss != NULL && item >= 0);
418 
419 	if (item < ss->n_items && ss->array != NULL)
420 		return (ss->array[item]);
421 	return (NULL);
422 }
423 
424 /*
425  * Free the state structure corresponding to 'item.'   Freeing an
426  * element that has either gone or was never allocated is not
427  * considered an error.  Note that we free the state structure, but
428  * we don't shrink our pointer array, or discard 'dirty' arrays,
429  * since even a few pointers don't really waste too much memory.
430  *
431  * Passing an item number that is out of bounds, or a null pointer will
432  * provoke an error message.
433  */
434 void
435 ddi_soft_state_free(void *state, int item)
436 {
437 	struct i_ddi_soft_state *ss;
438 	void **array;
439 	void *element;
440 	static char msg[] = "ddi_soft_state_free:";
441 
442 	if ((ss = state) == NULL) {
443 		cmn_err(CE_WARN, "%s null handle",
444 		    msg);
445 		return;
446 	}
447 
448 	element = NULL;
449 
450 	mutex_enter(&ss->lock);
451 
452 	if ((array = ss->array) == NULL || ss->size == 0) {
453 		cmn_err(CE_WARN, "%s bad handle",
454 		    msg);
455 	} else if (item < 0 || item >= ss->n_items) {
456 		cmn_err(CE_WARN, "%s item %d not in range [0..%lu]",
457 		    msg, item, ss->n_items - 1);
458 	} else if (array[item] != NULL) {
459 		element = array[item];
460 		array[item] = NULL;
461 	}
462 
463 	mutex_exit(&ss->lock);
464 
465 	if (element)
466 		kmem_free(element, ss->size);
467 }
468 
469 
470 /*
471  * Free the entire set of pointers, and any
472  * soft state structures contained therein.
473  *
474  * Note that we don't grab the ss->lock mutex, even though
475  * we're inspecting the various fields of the data structure.
476  *
477  * There is an implicit assumption that this routine will
478  * never run concurrently with any of the above on this
479  * particular state structure i.e. by the time the driver
480  * calls this routine, there should be no other threads
481  * running in the driver.
482  */
483 void
484 ddi_soft_state_fini(void **state_p)
485 {
486 	struct i_ddi_soft_state *ss, *dirty;
487 	int item;
488 	static char msg[] = "ddi_soft_state_fini:";
489 
490 	if (state_p == NULL || (ss = *state_p) == NULL) {
491 		cmn_err(CE_WARN, "%s null handle",
492 		    msg);
493 		return;
494 	}
495 
496 	if (ss->size == 0) {
497 		cmn_err(CE_WARN, "%s bad handle",
498 		    msg);
499 		return;
500 	}
501 
502 	if (ss->n_items > 0) {
503 		for (item = 0; item < ss->n_items; item++)
504 			ddi_soft_state_free(ss, item);
505 		kmem_free(ss->array, ss->n_items * sizeof (void *));
506 	}
507 
508 	/*
509 	 * Now delete any dirty arrays from previous 'grow' operations
510 	 */
511 	for (dirty = ss->next; dirty; dirty = ss->next) {
512 		ss->next = dirty->next;
513 		kmem_free(dirty->array, dirty->n_items * sizeof (void *));
514 		kmem_free(dirty, sizeof (*dirty));
515 	}
516 
517 	mutex_destroy(&ss->lock);
518 	kmem_free(ss, sizeof (*ss));
519 
520 	*state_p = NULL;
521 }
522 
523 int
524 ddi_create_minor_node(dev_info_t *dip, char *name, int spec_type,
525     minor_t minor_num, char *node_type, int flag)
526 {
527 	struct lwp *l = curlwp;
528 	char *pn;
529 	dev_t dev;
530 	int error;
531 	register_t ret;
532 
533 	printf("ddi_create_minor_node: name %s\n", name);
534 
535 	dev = makedev(flag, minor_num);
536 
537 	pn = PNBUF_GET();
538 	if (spec_type == S_IFCHR)
539 		snprintf(pn, MAXPATHLEN, "/dev/zvol/rdsk/%s", name);
540 	else
541 		snprintf(pn, MAXPATHLEN, "/dev/zvol/dsk/%s", name);
542 
543 	if ((error = do_mkdirp(pn)) != 0)
544 		goto exit;
545 
546 	error = do_sys_mknod(l, (const char *)pn, spec_type, dev, &ret, UIO_SYSSPACE);
547 
548 exit:
549 	PNBUF_PUT(pn);
550 
551 	return error;
552 }
553 
554 void
555 ddi_remove_minor_node(dev_info_t *dip, char *name)
556 {
557 	char *pn;
558 	int error;
559 
560 	pn = PNBUF_GET();
561 	snprintf(pn, MAXPATHLEN, "/dev/zvol/dsk/%s", name);
562 	(void)do_sys_unlink(pn, UIO_SYSSPACE);
563 	PNBUF_PUT(pn);
564 
565 	/* We need to remove raw and block device nodes */
566 	pn = PNBUF_GET();
567 	snprintf(pn, MAXPATHLEN, "/dev/zvol/rdsk/%s", name);
568 	(void)do_sys_unlink(pn, UIO_SYSSPACE);
569 	PNBUF_PUT(pn);
570 }
571 
572 clock_t
573 ddi_get_lbolt()
574 {
575 
576 	return hardclock_ticks;
577 }
578 
579 int64_t
580 ddi_get_lbolt64()
581 {
582 
583 	return hardclock_ticks;
584 }
585