xref: /titanic_41/usr/src/cmd/dlmgmtd/dlmgmt_db.c (revision dc5982c9e1ebe3315aac975f1c4f1ad46c83c2d2)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <assert.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <strings.h>
35 #include <syslog.h>
36 #include <zone.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <stropts.h>
40 #include <sys/conf.h>
41 #include <pthread.h>
42 #include <unistd.h>
43 #include <wait.h>
44 #include <libcontract.h>
45 #include <libcontract_priv.h>
46 #include <sys/contract/process.h>
47 #include "dlmgmt_impl.h"
48 
49 typedef enum dlmgmt_db_op {
50 	DLMGMT_DB_OP_WRITE,
51 	DLMGMT_DB_OP_DELETE,
52 	DLMGMT_DB_OP_READ
53 } dlmgmt_db_op_t;
54 
55 typedef struct dlmgmt_db_req_s {
56 	struct dlmgmt_db_req_s	*ls_next;
57 	dlmgmt_db_op_t		ls_op;
58 	char			ls_link[MAXLINKNAMELEN];
59 	datalink_id_t		ls_linkid;
60 	zoneid_t		ls_zoneid;
61 	uint32_t		ls_flags;	/* Either DLMGMT_ACTIVE or   */
62 						/* DLMGMT_PERSIST, not both. */
63 } dlmgmt_db_req_t;
64 
65 /*
66  * List of pending db updates (e.g., because of a read-only filesystem).
67  */
68 static dlmgmt_db_req_t	*dlmgmt_db_req_head = NULL;
69 static dlmgmt_db_req_t	*dlmgmt_db_req_tail = NULL;
70 
71 /*
72  * rewrite_needed is set to B_TRUE by process_link_line() if it encounters a
73  * line with an old format.  This will cause the file being read to be
74  * re-written with the current format.
75  */
76 static boolean_t	rewrite_needed;
77 
78 static int		dlmgmt_db_update(dlmgmt_db_op_t, const char *,
79 			    dlmgmt_link_t *, uint32_t);
80 static int		dlmgmt_process_db_req(dlmgmt_db_req_t *);
81 static int		dlmgmt_process_db_onereq(dlmgmt_db_req_t *, boolean_t);
82 static void		*dlmgmt_db_update_thread(void *);
83 static boolean_t	process_link_line(char *, dlmgmt_link_t *);
84 static int		process_db_write(dlmgmt_db_req_t *, FILE *, FILE *);
85 static int		process_db_read(dlmgmt_db_req_t *, FILE *);
86 static void		generate_link_line(dlmgmt_link_t *, boolean_t, char *);
87 
88 #define	BUFLEN(lim, ptr)	(((lim) > (ptr)) ? ((lim) - (ptr)) : 0)
89 #define	MAXLINELEN		1024
90 
91 typedef void db_walk_func_t(dlmgmt_link_t *);
92 
93 /*
94  * Translator functions to go from dladm_datatype_t to character strings.
95  * Each function takes a pointer to a buffer, the size of the buffer,
96  * the name of the attribute, and the value to be written.  The functions
97  * return the number of bytes written to the buffer.  If the buffer is not big
98  * enough to hold the string representing the value, then nothing is written
99  * and 0 is returned.
100  */
101 typedef size_t write_func_t(char *, size_t, char *, void *);
102 
103 /*
104  * Translator functions to read from a NULL terminated string buffer into
105  * something of the given DLADM_TYPE_*.  The functions each return the number
106  * of bytes read from the string buffer.  If there is an error reading data
107  * from the buffer, then 0 is returned.  It is the caller's responsibility
108  * to free the data allocated by these functions.
109  */
110 typedef size_t read_func_t(char *, void **);
111 
112 typedef struct translator_s {
113 	const char	*type_name;
114 	write_func_t	*write_func;
115 	read_func_t	*read_func;
116 } translator_t;
117 
118 /*
119  * Translator functions, defined later but declared here so that
120  * the translator table can be defined.
121  */
122 static write_func_t	write_str, write_boolean, write_uint64;
123 static read_func_t	read_str, read_boolean, read_int64;
124 
125 /*
126  * Translator table, indexed by dladm_datatype_t.
127  */
128 static translator_t translators[] = {
129 	{ "string",	write_str,	read_str	},
130 	{ "boolean",	write_boolean,	read_boolean	},
131 	{ "int",	write_uint64,	read_int64	}
132 };
133 
134 static size_t ntranslators = sizeof (translators) / sizeof (translator_t);
135 
136 #define	LINK_PROPERTY_DELIMINATOR	";"
137 #define	LINK_PROPERTY_TYPE_VALUE_SEP	","
138 #define	BASE_PROPERTY_LENGTH(t, n) (strlen(translators[(t)].type_name) +\
139 				    strlen(LINK_PROPERTY_TYPE_VALUE_SEP) +\
140 				    strlen(LINK_PROPERTY_DELIMINATOR) +\
141 				    strlen((n)))
142 #define	GENERATE_PROPERTY_STRING(buf, length, conv, name, type, val) \
143 	    (snprintf((buf), (length), "%s=%s%s" conv "%s", (name), \
144 	    translators[(type)].type_name, \
145 	    LINK_PROPERTY_TYPE_VALUE_SEP, (val), LINK_PROPERTY_DELIMINATOR))
146 
147 /*
148  * Name of the cache file to keep the active <link name, linkid> mapping
149  */
150 char	cachefile[MAXPATHLEN];
151 
152 #define	DLMGMT_PERSISTENT_DB_PATH	"/etc/dladm/datalink.conf"
153 #define	DLMGMT_MAKE_FILE_DB_PATH(buffer, persistent)	\
154 	(void) snprintf((buffer), MAXPATHLEN, "%s", \
155 	(persistent) ? DLMGMT_PERSISTENT_DB_PATH : cachefile);
156 
157 typedef struct zopen_arg {
158 	const char	*zopen_modestr;
159 	int		*zopen_pipe;
160 	int		zopen_fd;
161 } zopen_arg_t;
162 
163 typedef struct zrename_arg {
164 	const char	*zrename_newname;
165 } zrename_arg_t;
166 
167 typedef union zfoparg {
168 	zopen_arg_t	zfop_openarg;
169 	zrename_arg_t	zfop_renamearg;
170 } zfoparg_t;
171 
172 typedef struct zfcbarg {
173 	boolean_t	zfarg_inglobalzone; /* is callback in global zone? */
174 	zoneid_t	zfarg_finglobalzone; /* is file in global zone? */
175 	const char	*zfarg_filename;
176 	zfoparg_t	*zfarg_oparg;
177 } zfarg_t;
178 #define	zfarg_openarg	zfarg_oparg->zfop_openarg
179 #define	zfarg_renamearg	zfarg_oparg->zfop_renamearg
180 
181 /* zone file callback */
182 typedef int zfcb_t(zfarg_t *);
183 
184 /*
185  * Execute an operation on filename relative to zoneid's zone root.  If the
186  * file is in the global zone, then the zfcb() callback will simply be called
187  * directly.  If the file is in a non-global zone, then zfcb() will be called
188  * both from the global zone's context, and from the non-global zone's context
189  * (from a fork()'ed child that has entered the non-global zone).  This is
190  * done to allow the callback to communicate with itself if needed (e.g. to
191  * pass back the file descriptor of an opened file).
192  */
193 static int
194 dlmgmt_zfop(const char *filename, zoneid_t zoneid, zfcb_t *zfcb,
195     zfoparg_t *zfoparg)
196 {
197 	int		ctfd;
198 	int		err;
199 	pid_t		childpid;
200 	siginfo_t	info;
201 	zfarg_t		zfarg;
202 	ctid_t		ct;
203 
204 	if (zoneid != GLOBAL_ZONEID) {
205 		/*
206 		 * We need to access a file that isn't in the global zone.
207 		 * Accessing non-global zone files from the global zone is
208 		 * unsafe (due to symlink attacks), we'll need to fork a child
209 		 * that enters the zone in question and executes the callback
210 		 * that will operate on the file.
211 		 *
212 		 * Before we proceed with this zone tango, we need to create a
213 		 * new process contract for the child, as required by
214 		 * zone_enter().
215 		 */
216 		errno = 0;
217 		ctfd = open64("/system/contract/process/template", O_RDWR);
218 		if (ctfd == -1)
219 			return (errno);
220 		if ((err = ct_tmpl_set_critical(ctfd, 0)) != 0 ||
221 		    (err = ct_tmpl_set_informative(ctfd, 0)) != 0 ||
222 		    (err = ct_pr_tmpl_set_fatal(ctfd, CT_PR_EV_HWERR)) != 0 ||
223 		    (err = ct_pr_tmpl_set_param(ctfd, CT_PR_PGRPONLY)) != 0 ||
224 		    (err = ct_tmpl_activate(ctfd)) != 0) {
225 			(void) close(ctfd);
226 			return (err);
227 		}
228 		childpid = fork();
229 		switch (childpid) {
230 		case -1:
231 			(void) ct_tmpl_clear(ctfd);
232 			(void) close(ctfd);
233 			return (err);
234 		case 0:
235 			(void) ct_tmpl_clear(ctfd);
236 			(void) close(ctfd);
237 			/*
238 			 * Elevate our privileges as zone_enter() requires all
239 			 * privileges.
240 			 */
241 			if ((err = dlmgmt_elevate_privileges()) != 0)
242 				_exit(err);
243 			if (zone_enter(zoneid) == -1)
244 				_exit(errno);
245 			if ((err = dlmgmt_drop_privileges()) != 0)
246 				_exit(err);
247 			break;
248 		default:
249 			if (contract_latest(&ct) == -1)
250 				ct = -1;
251 			(void) ct_tmpl_clear(ctfd);
252 			(void) close(ctfd);
253 			if (waitid(P_PID, childpid, &info, WEXITED) == -1) {
254 				(void) contract_abandon_id(ct);
255 				return (errno);
256 			}
257 			(void) contract_abandon_id(ct);
258 			if (info.si_status != 0)
259 				return (info.si_status);
260 		}
261 	}
262 
263 	zfarg.zfarg_inglobalzone = (zoneid == GLOBAL_ZONEID || childpid != 0);
264 	zfarg.zfarg_finglobalzone = (zoneid == GLOBAL_ZONEID);
265 	zfarg.zfarg_filename = filename;
266 	zfarg.zfarg_oparg = zfoparg;
267 	err = zfcb(&zfarg);
268 	if (!zfarg.zfarg_inglobalzone)
269 		_exit(err);
270 	return (err);
271 }
272 
273 static int
274 dlmgmt_zopen_cb(zfarg_t *zfarg)
275 {
276 	struct strrecvfd recvfd;
277 	boolean_t	newfile = B_FALSE;
278 	boolean_t	inglobalzone = zfarg->zfarg_inglobalzone;
279 	zoneid_t	finglobalzone = zfarg->zfarg_finglobalzone;
280 	const char	*filename = zfarg->zfarg_filename;
281 	const char	*modestr = zfarg->zfarg_openarg.zopen_modestr;
282 	int		*p = zfarg->zfarg_openarg.zopen_pipe;
283 	struct stat	statbuf;
284 	int		oflags;
285 	mode_t		mode;
286 	int		fd = -1;
287 	int		err;
288 
289 	/* We only ever open a file for reading or writing, not both. */
290 	oflags = (modestr[0] == 'r') ? O_RDONLY : O_WRONLY | O_CREAT | O_TRUNC;
291 	mode = (modestr[0] == 'r') ? 0 : S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
292 
293 	/* Open the file if we're in the same zone as the file. */
294 	if (inglobalzone == finglobalzone) {
295 		/*
296 		 * First determine if we will be creating the file as part of
297 		 * opening it.  If so, then we'll need to ensure that it has
298 		 * the proper ownership after having opened it.
299 		 */
300 		if (oflags & O_CREAT) {
301 			if (stat(filename, &statbuf) == -1) {
302 				if (errno == ENOENT)
303 					newfile = B_TRUE;
304 				else
305 					return (errno);
306 			}
307 		}
308 		if ((fd = open(filename, oflags, mode)) == -1)
309 			return (errno);
310 		if (newfile) {
311 			if (chown(filename, UID_DLADM, GID_NETADM) == -1) {
312 				err = errno;
313 				(void) close(fd);
314 				return (err);
315 			}
316 		}
317 	}
318 
319 	/*
320 	 * If we're not in the global zone, send the file-descriptor back to
321 	 * our parent in the global zone.
322 	 */
323 	if (!inglobalzone) {
324 		assert(!finglobalzone);
325 		assert(fd != -1);
326 		return (ioctl(p[1], I_SENDFD, fd) == -1 ? errno : 0);
327 	}
328 
329 	/*
330 	 * At this point, we know we're in the global zone.  If the file was
331 	 * in a non-global zone, receive the file-descriptor from our child in
332 	 * the non-global zone.
333 	 */
334 	if (!finglobalzone) {
335 		if (ioctl(p[0], I_RECVFD, &recvfd) == -1)
336 			return (errno);
337 		fd = recvfd.fd;
338 	}
339 
340 	zfarg->zfarg_openarg.zopen_fd = fd;
341 	return (0);
342 }
343 
344 static int
345 dlmgmt_zunlink_cb(zfarg_t *zfarg)
346 {
347 	if (zfarg->zfarg_inglobalzone != zfarg->zfarg_finglobalzone)
348 		return (0);
349 	return (unlink(zfarg->zfarg_filename) == 0 ? 0 : errno);
350 }
351 
352 static int
353 dlmgmt_zrename_cb(zfarg_t *zfarg)
354 {
355 	if (zfarg->zfarg_inglobalzone != zfarg->zfarg_finglobalzone)
356 		return (0);
357 	return (rename(zfarg->zfarg_filename,
358 	    zfarg->zfarg_renamearg.zrename_newname) == 0 ? 0 : errno);
359 }
360 
361 /*
362  * Same as fopen(3C), except that it opens the file relative to zoneid's zone
363  * root.
364  */
365 static FILE *
366 dlmgmt_zfopen(const char *filename, const char *modestr, zoneid_t zoneid,
367     int *err)
368 {
369 	int		p[2];
370 	zfoparg_t	zfoparg;
371 	FILE		*fp = NULL;
372 
373 	if (zoneid != GLOBAL_ZONEID && pipe(p) == -1) {
374 		*err = errno;
375 		return (NULL);
376 	}
377 
378 	zfoparg.zfop_openarg.zopen_modestr = modestr;
379 	zfoparg.zfop_openarg.zopen_pipe = p;
380 	*err = dlmgmt_zfop(filename, zoneid, dlmgmt_zopen_cb, &zfoparg);
381 	if (zoneid != GLOBAL_ZONEID) {
382 		(void) close(p[0]);
383 		(void) close(p[1]);
384 	}
385 	if (*err == 0) {
386 		fp = fdopen(zfoparg.zfop_openarg.zopen_fd, modestr);
387 		if (fp == NULL) {
388 			*err = errno;
389 			(void) close(zfoparg.zfop_openarg.zopen_fd);
390 		}
391 	}
392 	return (fp);
393 }
394 
395 /*
396  * Same as rename(2), except that old and new are relative to zoneid's zone
397  * root.
398  */
399 static int
400 dlmgmt_zrename(const char *old, const char *new, zoneid_t zoneid)
401 {
402 	zfoparg_t zfoparg;
403 
404 	zfoparg.zfop_renamearg.zrename_newname = new;
405 	return (dlmgmt_zfop(old, zoneid, dlmgmt_zrename_cb, &zfoparg));
406 }
407 
408 /*
409  * Same as unlink(2), except that filename is relative to zoneid's zone root.
410  */
411 static int
412 dlmgmt_zunlink(const char *filename, zoneid_t zoneid)
413 {
414 	return (dlmgmt_zfop(filename, zoneid, dlmgmt_zunlink_cb, NULL));
415 }
416 
417 static size_t
418 write_str(char *buffer, size_t buffer_length, char *name, void *value)
419 {
420 	char	*ptr = value;
421 	size_t	data_length = strnlen(ptr, buffer_length);
422 
423 	/*
424 	 * Strings are assumed to be NULL terminated.  In order to fit in
425 	 * the buffer, the string's length must be less then buffer_length.
426 	 * If the value is empty, there's no point in writing it, in fact,
427 	 * we shouldn't even see that case.
428 	 */
429 	if (data_length + BASE_PROPERTY_LENGTH(DLADM_TYPE_STR, name) ==
430 	    buffer_length || data_length == 0)
431 		return (0);
432 
433 	/*
434 	 * Since we know the string will fit in the buffer, snprintf will
435 	 * always return less than buffer_length, so we can just return
436 	 * whatever snprintf returns.
437 	 */
438 	return (GENERATE_PROPERTY_STRING(buffer, buffer_length, "%s",
439 	    name, DLADM_TYPE_STR, ptr));
440 }
441 
442 static size_t
443 write_boolean(char *buffer, size_t buffer_length, char *name, void *value)
444 {
445 	boolean_t	*ptr = value;
446 
447 	/*
448 	 * Booleans are either zero or one, so we only need room for two
449 	 * characters in the buffer.
450 	 */
451 	if (buffer_length <= 1 + BASE_PROPERTY_LENGTH(DLADM_TYPE_BOOLEAN, name))
452 		return (0);
453 
454 	return (GENERATE_PROPERTY_STRING(buffer, buffer_length, "%d",
455 	    name, DLADM_TYPE_BOOLEAN, *ptr));
456 }
457 
458 static size_t
459 write_uint64(char *buffer, size_t buffer_length, char *name, void *value)
460 {
461 	uint64_t	*ptr = value;
462 
463 	/*
464 	 * Limit checking for uint64_t is a little trickier.
465 	 */
466 	if (snprintf(NULL, 0, "%lld", *ptr)  +
467 	    BASE_PROPERTY_LENGTH(DLADM_TYPE_UINT64, name) >= buffer_length)
468 		return (0);
469 
470 	return (GENERATE_PROPERTY_STRING(buffer, buffer_length, "%lld",
471 	    name, DLADM_TYPE_UINT64, *ptr));
472 }
473 
474 static size_t
475 read_str(char *buffer, void **value)
476 {
477 	char		*ptr = calloc(MAXLINKATTRVALLEN, sizeof (char));
478 	ssize_t		len;
479 
480 	if (ptr == NULL || (len = strlcpy(ptr, buffer, MAXLINKATTRVALLEN))
481 	    >= MAXLINKATTRVALLEN) {
482 		free(ptr);
483 		return (0);
484 	}
485 
486 	*(char **)value = ptr;
487 
488 	/* Account for NULL terminator */
489 	return (len + 1);
490 }
491 
492 static size_t
493 read_boolean(char *buffer, void **value)
494 {
495 	boolean_t	*ptr = calloc(1, sizeof (boolean_t));
496 
497 	if (ptr == NULL)
498 		return (0);
499 
500 	*ptr = atoi(buffer);
501 	*(boolean_t **)value = ptr;
502 
503 	return (sizeof (boolean_t));
504 }
505 
506 static size_t
507 read_int64(char *buffer, void **value)
508 {
509 	int64_t	*ptr = calloc(1, sizeof (int64_t));
510 
511 	if (ptr == NULL)
512 		return (0);
513 
514 	*ptr = (int64_t)atoll(buffer);
515 	*(int64_t **)value = ptr;
516 
517 	return (sizeof (int64_t));
518 }
519 
520 static dlmgmt_db_req_t *
521 dlmgmt_db_req_alloc(dlmgmt_db_op_t op, const char *linkname,
522     datalink_id_t linkid, zoneid_t zoneid, uint32_t flags, int *err)
523 {
524 	dlmgmt_db_req_t *req;
525 
526 	if ((req = calloc(1, sizeof (dlmgmt_db_req_t))) == NULL) {
527 		*err = errno;
528 	} else {
529 		req->ls_op = op;
530 		if (linkname != NULL)
531 			(void) strlcpy(req->ls_link, linkname, MAXLINKNAMELEN);
532 		req->ls_linkid = linkid;
533 		req->ls_zoneid = zoneid;
534 		req->ls_flags = flags;
535 	}
536 	return (req);
537 }
538 
539 /*
540  * Update the db entry with name "entryname" using information from "linkp".
541  */
542 static int
543 dlmgmt_db_update(dlmgmt_db_op_t op, const char *entryname, dlmgmt_link_t *linkp,
544     uint32_t flags)
545 {
546 	dlmgmt_db_req_t	*req;
547 	int		err;
548 
549 	/* It is either a persistent request or an active request, not both. */
550 	assert((flags == DLMGMT_PERSIST) || (flags == DLMGMT_ACTIVE));
551 
552 	if ((req = dlmgmt_db_req_alloc(op, entryname, linkp->ll_linkid,
553 	    linkp->ll_zoneid, flags, &err)) == NULL)
554 		return (err);
555 
556 	/*
557 	 * If the return error is EINPROGRESS, this request is handled
558 	 * asynchronously; return success.
559 	 */
560 	err = dlmgmt_process_db_req(req);
561 	if (err != EINPROGRESS)
562 		free(req);
563 	else
564 		err = 0;
565 	return (err);
566 }
567 
568 #define	DLMGMT_DB_OP_STR(op)					\
569 	(((op) == DLMGMT_DB_OP_READ) ? "read" :			\
570 	(((op) == DLMGMT_DB_OP_WRITE) ? "write" : "delete"))
571 
572 #define	DLMGMT_DB_CONF_STR(flag)				\
573 	(((flag) == DLMGMT_ACTIVE) ? "active" :			\
574 	(((flag) == DLMGMT_PERSIST) ? "persistent" : ""))
575 
576 static int
577 dlmgmt_process_db_req(dlmgmt_db_req_t *req)
578 {
579 	pthread_t	tid;
580 	boolean_t	writeop;
581 	int		err;
582 
583 	/*
584 	 * If there are already pending "write" requests, queue this request in
585 	 * the pending list.  Note that this function is called while the
586 	 * dlmgmt_rw_lock is held, so it is safe to access the global variables.
587 	 */
588 	writeop = (req->ls_op != DLMGMT_DB_OP_READ);
589 	if (writeop && (req->ls_flags == DLMGMT_PERSIST) &&
590 	    (dlmgmt_db_req_head != NULL)) {
591 		dlmgmt_db_req_tail->ls_next = req;
592 		dlmgmt_db_req_tail = req;
593 		return (EINPROGRESS);
594 	}
595 
596 	err = dlmgmt_process_db_onereq(req, writeop);
597 	if (err != EINPROGRESS && err != 0 && err != ENOENT) {
598 		/*
599 		 * Log the error unless the request processing is still in
600 		 * progress or if the configuration file hasn't been created
601 		 * yet (ENOENT).
602 		 */
603 		dlmgmt_log(LOG_WARNING, "dlmgmt_process_db_onereq() %s "
604 		    "operation on %s configuration failed: %s",
605 		    DLMGMT_DB_OP_STR(req->ls_op),
606 		    DLMGMT_DB_CONF_STR(req->ls_flags), strerror(err));
607 	}
608 
609 	if (err == EINPROGRESS) {
610 		assert(req->ls_flags == DLMGMT_PERSIST);
611 		assert(writeop && dlmgmt_db_req_head == NULL);
612 		dlmgmt_db_req_tail = dlmgmt_db_req_head = req;
613 		err = pthread_create(&tid, NULL, dlmgmt_db_update_thread, NULL);
614 		if (err == 0)
615 			return (EINPROGRESS);
616 	}
617 	return (err);
618 }
619 
620 static int
621 dlmgmt_process_db_onereq(dlmgmt_db_req_t *req, boolean_t writeop)
622 {
623 	int	err = 0;
624 	FILE	*fp, *nfp = NULL;
625 	char	file[MAXPATHLEN];
626 	char	newfile[MAXPATHLEN];
627 
628 	DLMGMT_MAKE_FILE_DB_PATH(file, (req->ls_flags == DLMGMT_PERSIST));
629 	fp = dlmgmt_zfopen(file, "r", req->ls_zoneid, &err);
630 	/*
631 	 * Note that it is not an error if the file doesn't exist.  If we're
632 	 * reading, we treat this case the same way as an empty file.  If
633 	 * we're writing, the file will be created when we open the file for
634 	 * writing below.
635 	 */
636 	if (fp == NULL && !writeop)
637 		return (err);
638 
639 	if (writeop) {
640 		(void) snprintf(newfile, MAXPATHLEN, "%s.new", file);
641 		nfp = dlmgmt_zfopen(newfile, "w", req->ls_zoneid, &err);
642 		if (nfp == NULL) {
643 			/*
644 			 * EROFS can happen at boot when the file system is
645 			 * read-only.  Return EINPROGRESS so that the caller
646 			 * can add this request to the pending request list
647 			 * and start a retry thread.
648 			 */
649 			err = (errno == EROFS ? EINPROGRESS : errno);
650 			goto done;
651 		}
652 	}
653 	if (writeop) {
654 		if ((err = process_db_write(req, fp, nfp)) == 0)
655 			err = dlmgmt_zrename(newfile, file, req->ls_zoneid);
656 	} else {
657 		err = process_db_read(req, fp);
658 	}
659 
660 done:
661 	if (nfp != NULL) {
662 		(void) fclose(nfp);
663 		if (err != 0)
664 			(void) dlmgmt_zunlink(newfile, req->ls_zoneid);
665 	}
666 	(void) fclose(fp);
667 	return (err);
668 }
669 
670 /*ARGSUSED*/
671 static void *
672 dlmgmt_db_update_thread(void *arg)
673 {
674 	dlmgmt_db_req_t	*req;
675 
676 	dlmgmt_table_lock(B_TRUE);
677 
678 	assert(dlmgmt_db_req_head != NULL);
679 	while ((req = dlmgmt_db_req_head) != NULL) {
680 		assert(req->ls_flags == DLMGMT_PERSIST);
681 		if (dlmgmt_process_db_onereq(req, B_TRUE) == EINPROGRESS) {
682 			/*
683 			 * The filesystem is still read only. Go to sleep and
684 			 * try again.
685 			 */
686 			dlmgmt_table_unlock();
687 			(void) sleep(5);
688 			dlmgmt_table_lock(B_TRUE);
689 			continue;
690 		}
691 
692 		/*
693 		 * The filesystem is no longer read only. Continue processing
694 		 * and remove the request from the pending list.
695 		 */
696 		dlmgmt_db_req_head = req->ls_next;
697 		if (dlmgmt_db_req_tail == req) {
698 			assert(dlmgmt_db_req_head == NULL);
699 			dlmgmt_db_req_tail = NULL;
700 		}
701 		free(req);
702 	}
703 
704 	dlmgmt_table_unlock();
705 	return (NULL);
706 }
707 
708 static int
709 parse_linkprops(char *buf, dlmgmt_link_t *linkp)
710 {
711 	boolean_t		found_type = B_FALSE;
712 	dladm_datatype_t	type = DLADM_TYPE_STR;
713 	int			i, len;
714 	int			err = 0;
715 	char			*curr;
716 	char			attr_name[MAXLINKATTRLEN];
717 	size_t			attr_buf_len = 0;
718 	void			*attr_buf = NULL;
719 
720 	curr = buf;
721 	len = strlen(buf);
722 	attr_name[0] = '\0';
723 	for (i = 0; i < len && err == 0; i++) {
724 		char		c = buf[i];
725 		boolean_t	match = (c == '=' ||
726 		    (c == ',' && !found_type) || c == ';');
727 
728 		/*
729 		 * Move to the next character if there is no match and
730 		 * if we have not reached the last character.
731 		 */
732 		if (!match && i != len - 1)
733 			continue;
734 
735 		if (match) {
736 			/*
737 			 * NUL-terminate the string pointed to by 'curr'.
738 			 */
739 			buf[i] = '\0';
740 			if (*curr == '\0')
741 				goto parse_fail;
742 		}
743 
744 		if (attr_name[0] != '\0' && found_type) {
745 			/*
746 			 * We get here after we have processed the "<prop>="
747 			 * pattern. The pattern we are now interested in is
748 			 * "<val>;".
749 			 */
750 			if (c == '=')
751 				goto parse_fail;
752 
753 			if (strcmp(attr_name, "linkid") == 0) {
754 				(void) read_int64(curr, &attr_buf);
755 				linkp->ll_linkid =
756 				    (datalink_class_t)*(int64_t *)attr_buf;
757 			} else if (strcmp(attr_name, "name") == 0) {
758 				(void) read_str(curr, &attr_buf);
759 				(void) snprintf(linkp->ll_link,
760 				    MAXLINKNAMELEN, "%s", attr_buf);
761 			} else if (strcmp(attr_name, "class") == 0) {
762 				(void) read_int64(curr, &attr_buf);
763 				linkp->ll_class =
764 				    (datalink_class_t)*(int64_t *)attr_buf;
765 			} else if (strcmp(attr_name, "media") == 0) {
766 				(void) read_int64(curr, &attr_buf);
767 				linkp->ll_media =
768 				    (uint32_t)*(int64_t *)attr_buf;
769 			} else {
770 				attr_buf_len = translators[type].read_func(curr,
771 				    &attr_buf);
772 				err = linkattr_set(&(linkp->ll_head), attr_name,
773 				    attr_buf, attr_buf_len, type);
774 			}
775 
776 			free(attr_buf);
777 			attr_name[0] = '\0';
778 			found_type = B_FALSE;
779 		} else if (attr_name[0] != '\0') {
780 			/*
781 			 * Non-zero length attr_name and found_type of false
782 			 * indicates that we have not found the type for this
783 			 * attribute.  The pattern now is "<type>,<val>;", we
784 			 * want the <type> part of the pattern.
785 			 */
786 			for (type = 0; type < ntranslators; type++) {
787 				if (strcmp(curr,
788 				    translators[type].type_name) == 0) {
789 					found_type = B_TRUE;
790 					break;
791 				}
792 			}
793 
794 			if (!found_type)
795 				goto parse_fail;
796 		} else {
797 			/*
798 			 * A zero length attr_name indicates we are looking
799 			 * at the beginning of a link attribute.
800 			 */
801 			if (c != '=')
802 				goto parse_fail;
803 
804 			(void) snprintf(attr_name, MAXLINKATTRLEN, "%s", curr);
805 		}
806 		curr = buf + i + 1;
807 	}
808 
809 	return (err);
810 
811 parse_fail:
812 	return (-1);
813 }
814 
815 static boolean_t
816 process_link_line(char *buf, dlmgmt_link_t *linkp)
817 {
818 	int	i, len, llen;
819 	char	*str, *lasts;
820 	char	tmpbuf[MAXLINELEN];
821 
822 	bzero(linkp, sizeof (*linkp));
823 	linkp->ll_linkid = DATALINK_INVALID_LINKID;
824 
825 	/*
826 	 * Use a copy of buf for parsing so that we can do whatever we want.
827 	 */
828 	(void) strlcpy(tmpbuf, buf, MAXLINELEN);
829 
830 	/*
831 	 * Skip leading spaces, blank lines, and comments.
832 	 */
833 	len = strlen(tmpbuf);
834 	for (i = 0; i < len; i++) {
835 		if (!isspace(tmpbuf[i]))
836 			break;
837 	}
838 	if (i == len || tmpbuf[i] == '#')
839 		return (B_TRUE);
840 
841 	str = tmpbuf + i;
842 	/*
843 	 * Find the link name and assign it to the link structure.
844 	 */
845 	if (strtok_r(str, " \n\t", &lasts) == NULL)
846 		goto fail;
847 
848 	llen = strlen(str);
849 	/*
850 	 * Note that a previous version of the persistent datalink.conf file
851 	 * stored the linkid as the first field.  In that case, the name will
852 	 * be obtained through parse_linkprops from a property with the format
853 	 * "name=<linkname>".  If we encounter such a format, we set
854 	 * rewrite_needed so that dlmgmt_db_init() can rewrite the file with
855 	 * the new format after it's done reading in the data.
856 	 */
857 	if (isdigit(str[0])) {
858 		linkp->ll_linkid = atoi(str);
859 		rewrite_needed = B_TRUE;
860 	} else {
861 		if (strlcpy(linkp->ll_link, str, sizeof (linkp->ll_link)) >=
862 		    sizeof (linkp->ll_link))
863 			goto fail;
864 	}
865 
866 	str += llen + 1;
867 	if (str >= tmpbuf + len)
868 		goto fail;
869 
870 	/*
871 	 * Now find the list of link properties.
872 	 */
873 	if ((str = strtok_r(str, " \n\t", &lasts)) == NULL)
874 		goto fail;
875 
876 	if (parse_linkprops(str, linkp) < 0)
877 		goto fail;
878 
879 	return (B_TRUE);
880 
881 fail:
882 	/*
883 	 * Delete corrupted line.
884 	 */
885 	buf[0] = '\0';
886 	return (B_FALSE);
887 }
888 
889 /*
890  * Find any properties in linkp that refer to "old", and rename to "new".
891  * Return B_TRUE if any renaming occurred.
892  */
893 static int
894 dlmgmt_attr_rename(dlmgmt_link_t *linkp, const char *old, const char *new,
895     boolean_t *renamed)
896 {
897 	dlmgmt_linkattr_t	*attrp;
898 	char			*newval = NULL, *pname;
899 	char			valcp[MAXLINKATTRVALLEN];
900 	size_t			newsize;
901 
902 	*renamed = B_FALSE;
903 
904 	if ((attrp = linkattr_find(linkp->ll_head, "linkover")) != NULL ||
905 	    (attrp = linkattr_find(linkp->ll_head, "simnetpeer")) != NULL) {
906 		if (strcmp(old, (char *)attrp->lp_val) == 0) {
907 			newsize = strlen(new) + 1;
908 			if ((newval = malloc(newsize)) == NULL)
909 				return (errno);
910 			(void) strcpy(newval, new);
911 			free(attrp->lp_val);
912 			attrp->lp_val = newval;
913 			attrp->lp_sz = newsize;
914 			*renamed = B_TRUE;
915 		}
916 		return (0);
917 	}
918 
919 	if ((attrp = linkattr_find(linkp->ll_head, "portnames")) == NULL)
920 		return (0);
921 
922 	/* <linkname>:[<linkname>:]... */
923 	if ((newval = calloc(MAXLINKATTRVALLEN, sizeof (char))) == NULL)
924 		return (errno);
925 
926 	bcopy(attrp->lp_val, valcp, sizeof (valcp));
927 	pname = strtok(valcp, ":");
928 	while (pname != NULL) {
929 		if (strcmp(pname, old) == 0) {
930 			(void) strcat(newval, new);
931 			*renamed = B_TRUE;
932 		} else {
933 			(void) strcat(newval, pname);
934 		}
935 		(void) strcat(newval, ":");
936 		pname = strtok(NULL, ":");
937 	}
938 	if (*renamed) {
939 		free(attrp->lp_val);
940 		attrp->lp_val = newval;
941 		attrp->lp_sz = strlen(newval) + 1;
942 	} else {
943 		free(newval);
944 	}
945 	return (0);
946 }
947 
948 static int
949 process_db_write(dlmgmt_db_req_t *req, FILE *fp, FILE *nfp)
950 {
951 	boolean_t		done = B_FALSE;
952 	int			err = 0;
953 	dlmgmt_link_t		link_in_file, *linkp = NULL, *dblinkp;
954 	boolean_t		persist = (req->ls_flags == DLMGMT_PERSIST);
955 	boolean_t		writeall, rename, attr_renamed;
956 	char			buf[MAXLINELEN];
957 
958 	writeall = (req->ls_linkid == DATALINK_ALL_LINKID);
959 
960 	if (req->ls_op == DLMGMT_DB_OP_WRITE && !writeall) {
961 		/*
962 		 * find the link in the avl tree with the given linkid.
963 		 */
964 		linkp = link_by_id(req->ls_linkid, req->ls_zoneid);
965 		if (linkp == NULL || (linkp->ll_flags & req->ls_flags) == 0) {
966 			/*
967 			 * This link has already been changed. This could
968 			 * happen if the request is pending because of
969 			 * read-only file-system. If so, we are done.
970 			 */
971 			return (0);
972 		}
973 		/*
974 		 * In the case of a rename, linkp's name has been updated to
975 		 * the new name, and req->ls_link is the old link name.
976 		 */
977 		rename = (strcmp(req->ls_link, linkp->ll_link) != 0);
978 	}
979 
980 	/*
981 	 * fp can be NULL if the file didn't initially exist and we're
982 	 * creating it as part of this write operation.
983 	 */
984 	if (fp == NULL)
985 		goto write;
986 
987 	while (err == 0 && fgets(buf, sizeof (buf), fp) != NULL &&
988 	    process_link_line(buf, &link_in_file)) {
989 		if (link_in_file.ll_link[0] == '\0' || done) {
990 			/*
991 			 * this is a comment line or we are done updating the
992 			 * line for the specified link, write the rest of
993 			 * lines out.
994 			 */
995 			if (fputs(buf, nfp) == EOF)
996 				err = errno;
997 			continue;
998 		}
999 
1000 		switch (req->ls_op) {
1001 		case DLMGMT_DB_OP_WRITE:
1002 			/*
1003 			 * For write operations, we generate a new output line
1004 			 * if we're either writing all links (writeall) or if
1005 			 * the name of the link in the file matches the one
1006 			 * we're looking for.  Otherwise, we write out the
1007 			 * buffer as-is.
1008 			 *
1009 			 * If we're doing a rename operation, ensure that any
1010 			 * references to the link being renamed in link
1011 			 * properties are also updated before we write
1012 			 * anything.
1013 			 */
1014 			if (writeall) {
1015 				linkp = link_by_name(link_in_file.ll_link,
1016 				    req->ls_zoneid);
1017 			}
1018 			if (writeall || strcmp(req->ls_link,
1019 			    link_in_file.ll_link) == 0) {
1020 				generate_link_line(linkp, persist, buf);
1021 				if (!writeall && !rename)
1022 					done = B_TRUE;
1023 			} else if (rename && persist) {
1024 				dblinkp = link_by_name(link_in_file.ll_link,
1025 				    req->ls_zoneid);
1026 				err = dlmgmt_attr_rename(dblinkp, req->ls_link,
1027 				    linkp->ll_link, &attr_renamed);
1028 				if (err != 0)
1029 					break;
1030 				if (attr_renamed) {
1031 					generate_link_line(dblinkp, persist,
1032 					    buf);
1033 				}
1034 			}
1035 			if (fputs(buf, nfp) == EOF)
1036 				err = errno;
1037 			break;
1038 		case DLMGMT_DB_OP_DELETE:
1039 			/*
1040 			 * Delete is simple.  If buf does not represent the
1041 			 * link we're deleting, write it out.
1042 			 */
1043 			if (strcmp(req->ls_link, link_in_file.ll_link) != 0) {
1044 				if (fputs(buf, nfp) == EOF)
1045 					err = errno;
1046 			} else {
1047 				done = B_TRUE;
1048 			}
1049 			break;
1050 		case DLMGMT_DB_OP_READ:
1051 		default:
1052 			err = EINVAL;
1053 			break;
1054 		}
1055 	}
1056 
1057 write:
1058 	/*
1059 	 * If we get to the end of the file and have not seen what linkid
1060 	 * points to, write it out then.
1061 	 */
1062 	if (req->ls_op == DLMGMT_DB_OP_WRITE && !writeall && !rename && !done) {
1063 		generate_link_line(linkp, persist, buf);
1064 		done = B_TRUE;
1065 		if (fputs(buf, nfp) == EOF)
1066 			err = errno;
1067 	}
1068 
1069 	return (err);
1070 }
1071 
1072 static int
1073 process_db_read(dlmgmt_db_req_t *req, FILE *fp)
1074 {
1075 	avl_index_t	name_where, id_where;
1076 	dlmgmt_link_t	link_in_file, *newlink, *link_in_db;
1077 	char		buf[MAXLINELEN];
1078 	int		err = 0;
1079 
1080 	/*
1081 	 * This loop processes each line of the configuration file.
1082 	 */
1083 	while (fgets(buf, MAXLINELEN, fp) != NULL) {
1084 		if (!process_link_line(buf, &link_in_file)) {
1085 			err = EINVAL;
1086 			break;
1087 		}
1088 
1089 		/*
1090 		 * Skip the comment line.
1091 		 */
1092 		if (link_in_file.ll_link[0] == '\0')
1093 			continue;
1094 
1095 		if ((req->ls_flags & DLMGMT_ACTIVE) &&
1096 		    link_in_file.ll_linkid == DATALINK_INVALID_LINKID)
1097 			continue;
1098 
1099 		link_in_file.ll_zoneid = req->ls_zoneid;
1100 		link_in_db = avl_find(&dlmgmt_name_avl, &link_in_file,
1101 		    &name_where);
1102 		if (link_in_db != NULL) {
1103 			/*
1104 			 * If the link in the database already has the flag
1105 			 * for this request set, then the entry is a
1106 			 * duplicate.  If it's not a duplicate, then simply
1107 			 * turn on the appropriate flag on the existing link.
1108 			 */
1109 			if (link_in_db->ll_flags & req->ls_flags) {
1110 				dlmgmt_log(LOG_WARNING, "Duplicate links "
1111 				    "in the repository: %s",
1112 				    link_in_file.ll_link);
1113 			} else {
1114 				if (req->ls_flags & DLMGMT_PERSIST) {
1115 					/*
1116 					 * Save the newly read properties into
1117 					 * the existing link.
1118 					 */
1119 					assert(link_in_db->ll_head == NULL);
1120 					link_in_db->ll_head =
1121 					    link_in_file.ll_head;
1122 				}
1123 				link_in_db->ll_flags |= req->ls_flags;
1124 			}
1125 		} else {
1126 			/*
1127 			 * This is a new link.  Allocate a new dlmgmt_link_t
1128 			 * and add it to the trees.
1129 			 */
1130 			newlink = calloc(1, sizeof (*newlink));
1131 			if (newlink == NULL) {
1132 				dlmgmt_log(LOG_WARNING, "Unable to allocate "
1133 				    "memory to create new link %s",
1134 				    link_in_file.ll_link);
1135 				continue;
1136 			}
1137 			bcopy(&link_in_file, newlink, sizeof (*newlink));
1138 
1139 			if (newlink->ll_linkid == DATALINK_INVALID_LINKID)
1140 				newlink->ll_linkid = dlmgmt_nextlinkid;
1141 			if (avl_find(&dlmgmt_id_avl, newlink, &id_where) !=
1142 			    NULL) {
1143 				link_destroy(newlink);
1144 				continue;
1145 			}
1146 			if ((req->ls_flags & DLMGMT_ACTIVE) &&
1147 			    link_activate(newlink) != 0) {
1148 				dlmgmt_log(LOG_WARNING, "Unable to activate %s",
1149 				    newlink->ll_link);
1150 				link_destroy(newlink);
1151 				continue;
1152 			}
1153 			avl_insert(&dlmgmt_name_avl, newlink, name_where);
1154 			avl_insert(&dlmgmt_id_avl, newlink, id_where);
1155 			dlmgmt_advance(newlink);
1156 			newlink->ll_flags |= req->ls_flags;
1157 		}
1158 	}
1159 
1160 	return (err);
1161 }
1162 
1163 /*
1164  * Generate an entry in the link database.
1165  * Each entry has this format:
1166  * <link name>	<prop0>=<type>,<val>;...;<propn>=<type>,<val>;
1167  */
1168 static void
1169 generate_link_line(dlmgmt_link_t *linkp, boolean_t persist, char *buf)
1170 {
1171 	char			tmpbuf[MAXLINELEN];
1172 	char			*ptr = tmpbuf;
1173 	char			*lim = tmpbuf + MAXLINELEN;
1174 	dlmgmt_linkattr_t	*cur_p = NULL;
1175 	uint64_t		u64;
1176 
1177 	ptr += snprintf(ptr, BUFLEN(lim, ptr), "%s\t", linkp->ll_link);
1178 	if (!persist) {
1179 		/*
1180 		 * We store the linkid in the active database so that dlmgmtd
1181 		 * can recover in the event that it is restarted.
1182 		 */
1183 		u64 = linkp->ll_linkid;
1184 		ptr += write_uint64(ptr, BUFLEN(lim, ptr), "linkid", &u64);
1185 	}
1186 	u64 = linkp->ll_class;
1187 	ptr += write_uint64(ptr, BUFLEN(lim, ptr), "class", &u64);
1188 	u64 = linkp->ll_media;
1189 	ptr += write_uint64(ptr, BUFLEN(lim, ptr), "media", &u64);
1190 
1191 	/*
1192 	 * The daemon does not keep any active link attribute. Only store the
1193 	 * attributes if this request is for persistent configuration,
1194 	 */
1195 	if (persist) {
1196 		for (cur_p = linkp->ll_head; cur_p != NULL;
1197 		    cur_p = cur_p->lp_next) {
1198 			ptr += translators[cur_p->lp_type].write_func(ptr,
1199 			    BUFLEN(lim, ptr), cur_p->lp_name, cur_p->lp_val);
1200 		}
1201 	}
1202 
1203 	if (ptr <= lim)
1204 		(void) snprintf(buf, MAXLINELEN, "%s\n", tmpbuf);
1205 }
1206 
1207 int
1208 dlmgmt_delete_db_entry(dlmgmt_link_t *linkp, uint32_t flags)
1209 {
1210 	return (dlmgmt_db_update(DLMGMT_DB_OP_DELETE, linkp->ll_link, linkp,
1211 	    flags));
1212 }
1213 
1214 int
1215 dlmgmt_write_db_entry(const char *entryname, dlmgmt_link_t *linkp,
1216     uint32_t flags)
1217 {
1218 	int err;
1219 
1220 	if (flags & DLMGMT_PERSIST) {
1221 		if ((err = dlmgmt_db_update(DLMGMT_DB_OP_WRITE, entryname,
1222 		    linkp, DLMGMT_PERSIST)) != 0) {
1223 			return (err);
1224 		}
1225 	}
1226 
1227 	if (flags & DLMGMT_ACTIVE) {
1228 		if (((err = dlmgmt_db_update(DLMGMT_DB_OP_WRITE, entryname,
1229 		    linkp, DLMGMT_ACTIVE)) != 0) && (flags & DLMGMT_PERSIST)) {
1230 			(void) dlmgmt_db_update(DLMGMT_DB_OP_DELETE, entryname,
1231 			    linkp, DLMGMT_PERSIST);
1232 			return (err);
1233 		}
1234 	}
1235 
1236 	return (0);
1237 }
1238 
1239 /*
1240  * Upgrade properties that have link IDs as values to link names.  Because '.'
1241  * is a valid linkname character, the port separater for link aggregations
1242  * must be changed to ':'.
1243  */
1244 static void
1245 linkattr_upgrade(dlmgmt_linkattr_t *attrp)
1246 {
1247 	datalink_id_t	linkid;
1248 	char		*portidstr;
1249 	char		portname[MAXLINKNAMELEN + 1];
1250 	dlmgmt_link_t	*linkp;
1251 	char		*new_attr_val;
1252 	size_t		new_attr_sz;
1253 	boolean_t	upgraded = B_FALSE;
1254 
1255 	if (strcmp(attrp->lp_name, "linkover") == 0 ||
1256 	    strcmp(attrp->lp_name, "simnetpeer") == 0) {
1257 		if (attrp->lp_type == DLADM_TYPE_UINT64) {
1258 			linkid = (datalink_id_t)*(uint64_t *)attrp->lp_val;
1259 			if ((linkp = link_by_id(linkid, GLOBAL_ZONEID)) == NULL)
1260 				return;
1261 			new_attr_sz = strlen(linkp->ll_link) + 1;
1262 			if ((new_attr_val = malloc(new_attr_sz)) == NULL)
1263 				return;
1264 			(void) strcpy(new_attr_val, linkp->ll_link);
1265 			upgraded = B_TRUE;
1266 		}
1267 	} else if (strcmp(attrp->lp_name, "portnames") == 0) {
1268 		/*
1269 		 * The old format for "portnames" was
1270 		 * "<linkid>.[<linkid>.]...".  The new format is
1271 		 * "<linkname>:[<linkname>:]...".
1272 		 */
1273 		if (!isdigit(((char *)attrp->lp_val)[0]))
1274 			return;
1275 		new_attr_val = calloc(MAXLINKATTRVALLEN, sizeof (char));
1276 		if (new_attr_val == NULL)
1277 			return;
1278 		portidstr = (char *)attrp->lp_val;
1279 		while (*portidstr != '\0') {
1280 			errno = 0;
1281 			linkid = strtol(portidstr, &portidstr, 10);
1282 			if (linkid == 0 || *portidstr != '.' ||
1283 			    (linkp = link_by_id(linkid, GLOBAL_ZONEID)) ==
1284 			    NULL) {
1285 				free(new_attr_val);
1286 				return;
1287 			}
1288 			(void) snprintf(portname, sizeof (portname), "%s:",
1289 			    linkp->ll_link);
1290 			if (strlcat(new_attr_val, portname,
1291 			    MAXLINKATTRVALLEN) >= MAXLINKATTRVALLEN) {
1292 				free(new_attr_val);
1293 				return;
1294 			}
1295 			/* skip the '.' delimiter */
1296 			portidstr++;
1297 		}
1298 		new_attr_sz = strlen(new_attr_val) + 1;
1299 		upgraded = B_TRUE;
1300 	}
1301 
1302 	if (upgraded) {
1303 		attrp->lp_type = DLADM_TYPE_STR;
1304 		attrp->lp_sz = new_attr_sz;
1305 		free(attrp->lp_val);
1306 		attrp->lp_val = new_attr_val;
1307 	}
1308 }
1309 
1310 static void
1311 dlmgmt_db_upgrade(dlmgmt_link_t *linkp)
1312 {
1313 	dlmgmt_linkattr_t *attrp;
1314 
1315 	for (attrp = linkp->ll_head; attrp != NULL; attrp = attrp->lp_next)
1316 		linkattr_upgrade(attrp);
1317 }
1318 
1319 static void
1320 dlmgmt_db_phys_activate(dlmgmt_link_t *linkp)
1321 {
1322 	linkp->ll_flags |= DLMGMT_ACTIVE;
1323 	(void) dlmgmt_write_db_entry(linkp->ll_link, linkp, DLMGMT_ACTIVE);
1324 }
1325 
1326 static void
1327 dlmgmt_db_walk(zoneid_t zoneid, datalink_class_t class, db_walk_func_t *func)
1328 {
1329 	dlmgmt_link_t *linkp;
1330 
1331 	for (linkp = avl_first(&dlmgmt_id_avl); linkp != NULL;
1332 	    linkp = AVL_NEXT(&dlmgmt_id_avl, linkp)) {
1333 		if (linkp->ll_zoneid == zoneid && (linkp->ll_class & class))
1334 			func(linkp);
1335 	}
1336 }
1337 
1338 /*
1339  * Initialize the datalink <link name, linkid> mapping and the link's
1340  * attributes list based on the configuration file /etc/dladm/datalink.conf
1341  * and the active configuration cache file
1342  * /etc/svc/volatile/dladm/datalink-management:default.cache.
1343  */
1344 int
1345 dlmgmt_db_init(zoneid_t zoneid)
1346 {
1347 	dlmgmt_db_req_t	*req;
1348 	int		err;
1349 	boolean_t	boot = B_FALSE;
1350 
1351 	if ((req = dlmgmt_db_req_alloc(DLMGMT_DB_OP_READ, NULL,
1352 	    DATALINK_INVALID_LINKID, zoneid, DLMGMT_ACTIVE, &err)) == NULL)
1353 		return (err);
1354 
1355 	if ((err = dlmgmt_process_db_req(req)) != 0) {
1356 		/*
1357 		 * If we get back ENOENT, that means that the active
1358 		 * configuration file doesn't exist yet, and is not an error.
1359 		 * We'll create it down below after we've loaded the
1360 		 * persistent configuration.
1361 		 */
1362 		if (err != ENOENT)
1363 			goto done;
1364 		boot = B_TRUE;
1365 	}
1366 
1367 	req->ls_flags = DLMGMT_PERSIST;
1368 	err = dlmgmt_process_db_req(req);
1369 	if (err != 0 && err != ENOENT)
1370 		goto done;
1371 	err = 0;
1372 	if (rewrite_needed) {
1373 		/*
1374 		 * First update links in memory, then dump the entire db to
1375 		 * disk.
1376 		 */
1377 		dlmgmt_db_walk(zoneid, DATALINK_CLASS_ALL, dlmgmt_db_upgrade);
1378 		req->ls_op = DLMGMT_DB_OP_WRITE;
1379 		req->ls_linkid = DATALINK_ALL_LINKID;
1380 		if ((err = dlmgmt_process_db_req(req)) != 0 &&
1381 		    err != EINPROGRESS)
1382 			goto done;
1383 	}
1384 	if (boot) {
1385 		dlmgmt_db_walk(zoneid, DATALINK_CLASS_PHYS,
1386 		    dlmgmt_db_phys_activate);
1387 	}
1388 
1389 done:
1390 	if (err == EINPROGRESS)
1391 		err = 0;
1392 	else
1393 		free(req);
1394 	return (err);
1395 }
1396 
1397 /*
1398  * Remove all links in the given zoneid.
1399  */
1400 void
1401 dlmgmt_db_fini(zoneid_t zoneid)
1402 {
1403 	dlmgmt_link_t *linkp = avl_first(&dlmgmt_name_avl), *next_linkp;
1404 
1405 	while (linkp != NULL) {
1406 		next_linkp = AVL_NEXT(&dlmgmt_name_avl, linkp);
1407 		if (linkp->ll_zoneid == zoneid) {
1408 			(void) dlmgmt_destroy_common(linkp,
1409 			    DLMGMT_ACTIVE | DLMGMT_PERSIST);
1410 		}
1411 		linkp = next_linkp;
1412 	}
1413 }
1414