xref: /freebsd/sbin/camcontrol/modeedit.c (revision 535af610)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2000 Kelly Yancey <kbyanc@posi.net>
5  * Derived from work done by Julian Elischer <julian@tfs.com,
6  * julian@dialix.oz.au>, 1993, and Peter Dufault <dufault@hda.com>, 1994.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer,
14  *    without modification, immediately at the beginning of the file.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/queue.h>
35 #include <sys/types.h>
36 #include <sys/sbuf.h>
37 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <stdio.h>
45 #include <sysexits.h>
46 #include <unistd.h>
47 
48 #include <cam/scsi/scsi_all.h>
49 #include <cam/cam.h>
50 #include <cam/cam_ccb.h>
51 #include <camlib.h>
52 #include "camcontrol.h"
53 
54 #define	DEFAULT_SCSI_MODE_DB	"/usr/share/misc/scsi_modes"
55 #define	DEFAULT_EDITOR		"vi"
56 #define	MAX_FORMAT_SPEC		4096	/* Max CDB format specifier. */
57 #define	MAX_PAGENUM_LEN		10	/* Max characters in page num. */
58 #define	MAX_PAGENAME_LEN	64	/* Max characters in page name. */
59 #define	PAGEDEF_START		'{'	/* Page definition delimiter. */
60 #define	PAGEDEF_END		'}'	/* Page definition delimiter. */
61 #define	PAGENAME_START		'"'	/* Page name delimiter. */
62 #define	PAGENAME_END		'"'	/* Page name delimiter. */
63 #define	PAGEENTRY_END		';'	/* Page entry terminator (optional). */
64 #define	MAX_DATA_SIZE		4096	/* Mode/Log sense data buffer size. */
65 #define PAGE_CTRL_SHIFT		6	/* Bit offset to page control field. */
66 
67 struct editentry {
68 	STAILQ_ENTRY(editentry) link;
69 	char	*name;
70 	char	type;
71 	int	editable;
72 	int	size;
73 	union {
74 		int	ivalue;
75 		char	*svalue;
76 	} value;
77 };
78 static STAILQ_HEAD(, editentry) editlist; /* List of page entries. */
79 static int editlist_changed = 0;	/* Whether any entries were changed. */
80 
81 struct pagename {
82 	SLIST_ENTRY(pagename) link;
83 	int page;
84 	int subpage;
85 	char *name;
86 };
87 static SLIST_HEAD(, pagename) namelist;	/* Page number to name mappings. */
88 
89 static char format[MAX_FORMAT_SPEC];	/* Buffer for scsi cdb format def. */
90 
91 static FILE *edit_file = NULL;		/* File handle for edit file. */
92 static char edit_path[] = "/tmp/camXXXXXX";
93 
94 
95 /* Function prototypes. */
96 static void		 editentry_create(void *hook, int letter, void *arg,
97 					  int count, char *name);
98 static void		 editentry_update(void *hook, int letter, void *arg,
99 					  int count, char *name);
100 static void		 editentry_create_desc(void *hook, int letter, void *arg,
101 					  int count, char *name);
102 static int		 editentry_save(void *hook, char *name);
103 static struct editentry	*editentry_lookup(char *name);
104 static int		 editentry_set(char *name, char *newvalue,
105 				       int editonly);
106 static void		 editlist_populate(struct cam_device *device,
107 			    int cdb_len, int dbd, int pc, int page, int subpage,
108 			    int task_attr, int retries, int timeout);
109 static void		 editlist_populate_desc(struct cam_device *device,
110 			    int cdb_len, int llbaa, int pc, int page,
111 			    int subpage, int task_attr, int retries,
112 			    int timeout);
113 static void		 editlist_save(struct cam_device *device, int cdb_len,
114 			    int dbd, int pc, int page, int subpage,
115 			    int task_attr, int retries, int timeout);
116 static void		 editlist_save_desc(struct cam_device *device, int cdb_len,
117 			    int llbaa, int pc, int page, int subpage,
118 			    int task_attr, int retries, int timeout);
119 static void		 nameentry_create(int page, int subpage, char *name);
120 static struct pagename	*nameentry_lookup(int page, int subpage);
121 static int		 load_format(const char *pagedb_path, int lpage,
122 			    int lsubpage);
123 static int		 modepage_write(FILE *file, int editonly);
124 static int		 modepage_read(FILE *file);
125 static void		 modepage_edit(void);
126 static void		 modepage_dump(struct cam_device *device, int cdb_len,
127 			    int dbd, int pc, int page, int subpage,
128 			    int task_attr, int retries, int timeout);
129 static void		 modepage_dump_desc(struct cam_device *device,
130 			    int cdb_len, int llbaa, int pc, int page,
131 			    int subpage, int task_attr, int retries,
132 			    int timeout);
133 static void		 cleanup_editfile(void);
134 
135 
136 #define	returnerr(code) do {						\
137 	errno = code;							\
138 	return (-1);							\
139 } while (0)
140 
141 
142 #define	RTRIM(string) do {						\
143 	int _length;							\
144 	while (isspace(string[_length = strlen(string) - 1]))		\
145 		string[_length] = '\0';					\
146 } while (0)
147 
148 
149 static void
150 editentry_create(void *hook __unused, int letter, void *arg, int count,
151 		 char *name)
152 {
153 	struct editentry *newentry;	/* Buffer to hold new entry. */
154 
155 	/* Allocate memory for the new entry and a copy of the entry name. */
156 	if ((newentry = malloc(sizeof(struct editentry))) == NULL ||
157 	    (newentry->name = strdup(name)) == NULL)
158 		err(EX_OSERR, NULL);
159 
160 	/* Trim any trailing whitespace for the entry name. */
161 	RTRIM(newentry->name);
162 
163 	newentry->editable = (arg != NULL);
164 	newentry->type = letter;
165 	newentry->size = count;		/* Placeholder; not accurate. */
166 	newentry->value.svalue = NULL;
167 
168 	STAILQ_INSERT_TAIL(&editlist, newentry, link);
169 }
170 
171 static void
172 editentry_update(void *hook __unused, int letter, void *arg, int count,
173 		 char *name)
174 {
175 	struct editentry *dest;		/* Buffer to hold entry to update. */
176 
177 	dest = editentry_lookup(name);
178 	assert(dest != NULL);
179 
180 	dest->type = letter;
181 	dest->size = count;		/* We get the real size now. */
182 
183 	switch (dest->type) {
184 	case 'i':			/* Byte-sized integral type. */
185 	case 'b':			/* Bit-sized integral types. */
186 	case 't':
187 		dest->value.ivalue = (intptr_t)arg;
188 		break;
189 
190 	case 'c':			/* Character array. */
191 	case 'z':			/* Null-padded string. */
192 		editentry_set(name, (char *)arg, 0);
193 		break;
194 	default:
195 		; /* NOTREACHED */
196 	}
197 }
198 
199 static void
200 editentry_create_desc(void *hook __unused, int letter, void *arg, int count,
201 		 char *name)
202 {
203 	struct editentry *newentry;	/* Buffer to hold new entry. */
204 
205 	/* Allocate memory for the new entry and a copy of the entry name. */
206 	if ((newentry = malloc(sizeof(struct editentry))) == NULL ||
207 	    (newentry->name = strdup(name)) == NULL)
208 		err(EX_OSERR, NULL);
209 
210 	/* Trim any trailing whitespace for the entry name. */
211 	RTRIM(newentry->name);
212 
213 	newentry->editable = 1;
214 	newentry->type = letter;
215 	newentry->size = count;
216 	newentry->value.svalue = NULL;
217 
218 	STAILQ_INSERT_TAIL(&editlist, newentry, link);
219 
220 	switch (letter) {
221 	case 'i':			/* Byte-sized integral type. */
222 	case 'b':			/* Bit-sized integral types. */
223 	case 't':
224 		newentry->value.ivalue = (intptr_t)arg;
225 		break;
226 
227 	case 'c':			/* Character array. */
228 	case 'z':			/* Null-padded string. */
229 		editentry_set(name, (char *)arg, 0);
230 		break;
231 	default:
232 		; /* NOTREACHED */
233 	}
234 }
235 
236 static int
237 editentry_save(void *hook __unused, char *name)
238 {
239 	struct editentry *src;		/* Entry value to save. */
240 
241 	src = editentry_lookup(name);
242 	if (src == 0) {
243 		/*
244 		 * This happens if field does not fit into read page size.
245 		 * It also means that this field won't be written, so the
246 		 * returned value does not really matter.
247 		 */
248 		return (0);
249 	}
250 
251 	switch (src->type) {
252 	case 'i':			/* Byte-sized integral type. */
253 	case 'b':			/* Bit-sized integral types. */
254 	case 't':
255 		return (src->value.ivalue);
256 		/* NOTREACHED */
257 
258 	case 'c':			/* Character array. */
259 	case 'z':			/* Null-padded string. */
260 		return ((intptr_t)src->value.svalue);
261 		/* NOTREACHED */
262 
263 	default:
264 		; /* NOTREACHED */
265 	}
266 
267 	return (0);			/* This should never happen. */
268 }
269 
270 static struct editentry *
271 editentry_lookup(char *name)
272 {
273 	struct editentry *scan;
274 
275 	assert(name != NULL);
276 
277 	STAILQ_FOREACH(scan, &editlist, link) {
278 		if (strcasecmp(scan->name, name) == 0)
279 			return (scan);
280 	}
281 
282 	/* Not found during list traversal. */
283 	return (NULL);
284 }
285 
286 static int
287 editentry_set(char *name, char *newvalue, int editonly)
288 {
289 	struct editentry *dest;	/* Modepage entry to update. */
290 	char *cval;		/* Pointer to new string value. */
291 	char *convertend;	/* End-of-conversion pointer. */
292 	long long ival, newival; /* New integral value. */
293 	int resolution;		/* Resolution in bits for integer conversion. */
294 
295 /*
296  * Macro to determine the maximum value of the given size for the current
297  * resolution.
298  */
299 #define	RESOLUTION_MAX(size)	((1LL << (resolution * (size))) - 1)
300 
301 	assert(newvalue != NULL);
302 	if (*newvalue == '\0')
303 		return (0);	/* Nothing to do. */
304 
305 	if ((dest = editentry_lookup(name)) == NULL)
306 		returnerr(ENOENT);
307 	if (!dest->editable && editonly)
308 		returnerr(EPERM);
309 
310 	switch (dest->type) {
311 	case 'i':		/* Byte-sized integral type. */
312 	case 'b':		/* Bit-sized integral types. */
313 	case 't':
314 		/* Convert the value string to an integer. */
315 		resolution = (dest->type == 'i')? 8: 1;
316 		ival = strtoll(newvalue, &convertend, 0);
317 		if (*convertend != '\0')
318 			returnerr(EINVAL);
319 		if (ival > RESOLUTION_MAX(dest->size) || ival < 0) {
320 			newival = (ival < 0) ? 0 : RESOLUTION_MAX(dest->size);
321 			warnx("value %lld is out of range for entry %s; "
322 			    "clipping to %lld", ival, name, newival);
323 			ival = newival;
324 		}
325 		if (dest->value.ivalue != ival)
326 			editlist_changed = 1;
327 		dest->value.ivalue = ival;
328 		break;
329 
330 	case 'c':		/* Character array. */
331 	case 'z':		/* Null-padded string. */
332 		if ((cval = calloc(1, dest->size + 1)) == NULL)
333 			err(EX_OSERR, NULL);
334 		strlcpy(cval, newvalue, dest->size + 1);
335 		if (dest->type == 'z') {
336 			/* Convert trailing spaces to nulls. */
337 			char *convertend2;
338 
339 			for (convertend2 = cval + dest->size;
340 			    convertend2 >= cval; convertend2--) {
341 				if (*convertend2 == ' ')
342 					*convertend2 = '\0';
343 				else if (*convertend2 != '\0')
344 					break;
345 			}
346 		}
347 		if (strncmp(dest->value.svalue, cval, dest->size) == 0) {
348 			/* Nothing changed, free the newly allocated string. */
349 			free(cval);
350 			break;
351 		}
352 		if (dest->value.svalue != NULL) {
353 			/* Free the current string buffer. */
354 			free(dest->value.svalue);
355 			dest->value.svalue = NULL;
356 		}
357 		dest->value.svalue = cval;
358 		editlist_changed = 1;
359 		break;
360 
361 	default:
362 		; /* NOTREACHED */
363 	}
364 
365 	return (0);
366 #undef RESOLUTION_MAX
367 }
368 
369 static void
370 nameentry_create(int page, int subpage, char *name) {
371 	struct pagename *newentry;
372 
373 	if (page < 0 || subpage < 0 || name == NULL || name[0] == '\0')
374 		return;
375 
376 	/* Allocate memory for the new entry and a copy of the entry name. */
377 	if ((newentry = malloc(sizeof(struct pagename))) == NULL ||
378 	    (newentry->name = strdup(name)) == NULL)
379 		err(EX_OSERR, NULL);
380 
381 	/* Trim any trailing whitespace for the page name. */
382 	RTRIM(newentry->name);
383 
384 	newentry->page = page;
385 	newentry->subpage = subpage;
386 	SLIST_INSERT_HEAD(&namelist, newentry, link);
387 }
388 
389 static struct pagename *
390 nameentry_lookup(int page, int subpage) {
391 	struct pagename *scan;
392 
393 	SLIST_FOREACH(scan, &namelist, link) {
394 		if (page == scan->page && subpage == scan->subpage)
395 			return (scan);
396 	}
397 
398 	/* Not found during list traversal. */
399 	return (NULL);
400 }
401 
402 static int
403 load_format(const char *pagedb_path, int lpage, int lsubpage)
404 {
405 	FILE *pagedb;
406 	char str_page[MAX_PAGENUM_LEN];
407 	char *str_subpage;
408 	char str_pagename[MAX_PAGENAME_LEN];
409 	int page;
410 	int subpage;
411 	int depth;			/* Quoting depth. */
412 	int found;
413 	int lineno;
414 	enum { LOCATE, PAGENAME, PAGEDEF } state;
415 	int ch;
416 	char c;
417 
418 #define	SETSTATE_LOCATE do {						\
419 	str_page[0] = '\0';						\
420 	str_pagename[0] = '\0';						\
421 	page = -1;							\
422 	subpage = -1;							\
423 	state = LOCATE;							\
424 } while (0)
425 
426 #define	SETSTATE_PAGENAME do {						\
427 	str_pagename[0] = '\0';						\
428 	state = PAGENAME;						\
429 } while (0)
430 
431 #define	SETSTATE_PAGEDEF do {						\
432 	format[0] = '\0';						\
433 	state = PAGEDEF;						\
434 } while (0)
435 
436 #define	UPDATE_LINENO do {						\
437 	if (c == '\n')							\
438 		lineno++;						\
439 } while (0)
440 
441 #define	BUFFERFULL(buffer)	(strlen(buffer) + 1 >= sizeof(buffer))
442 
443 	if ((pagedb = fopen(pagedb_path, "r")) == NULL)
444 		returnerr(ENOENT);
445 
446 	SLIST_INIT(&namelist);
447 
448 	c = '\0';
449 	depth = 0;
450 	lineno = 0;
451 	found = 0;
452 	SETSTATE_LOCATE;
453 	while ((ch = fgetc(pagedb)) != EOF) {
454 
455 		/* Keep a line count to make error messages more useful. */
456 		UPDATE_LINENO;
457 
458 		/* Skip over comments anywhere in the mode database. */
459 		if (ch == '#') {
460 			do {
461 				ch = fgetc(pagedb);
462 			} while (ch != '\n' && ch != EOF);
463 			UPDATE_LINENO;
464 			continue;
465 		}
466 		c = ch;
467 
468 		/* Strip out newline characters. */
469 		if (c == '\n')
470 			continue;
471 
472 		/* Keep track of the nesting depth for braces. */
473 		if (c == PAGEDEF_START)
474 			depth++;
475 		else if (c == PAGEDEF_END) {
476 			depth--;
477 			if (depth < 0) {
478 				errx(EX_OSFILE, "%s:%d: %s", pagedb_path,
479 				    lineno, "mismatched bracket");
480 			}
481 		}
482 
483 		switch (state) {
484 		case LOCATE:
485 			/*
486 			 * Locate the page the user is interested in, skipping
487 			 * all others.
488 			 */
489 			if (isspace(c)) {
490 				/* Ignore all whitespace between pages. */
491 				break;
492 			} else if (depth == 0 && c == PAGEENTRY_END) {
493 				/*
494 				 * A page entry terminator will reset page
495 				 * scanning (useful for assigning names to
496 				 * modes without providing a mode definition).
497 				 */
498 				/* Record the name of this page. */
499 				str_subpage = str_page;
500 				strsep(&str_subpage, ",");
501 				page = strtol(str_page, NULL, 0);
502 				if (str_subpage)
503 				    subpage = strtol(str_subpage, NULL, 0);
504 				else
505 				    subpage = 0;
506 				nameentry_create(page, subpage, str_pagename);
507 				SETSTATE_LOCATE;
508 			} else if (depth == 0 && c == PAGENAME_START) {
509 				SETSTATE_PAGENAME;
510 			} else if (c == PAGEDEF_START) {
511 				str_subpage = str_page;
512 				strsep(&str_subpage, ",");
513 				page = strtol(str_page, NULL, 0);
514 				if (str_subpage)
515 				    subpage = strtol(str_subpage, NULL, 0);
516 				else
517 				    subpage = 0;
518 				if (depth == 1) {
519 					/* Record the name of this page. */
520 					nameentry_create(page, subpage,
521 					    str_pagename);
522 					/*
523 					 * Only record the format if this is
524 					 * the page we are interested in.
525 					 */
526 					if (lpage == page &&
527 					    lsubpage == subpage && !found)
528 						SETSTATE_PAGEDEF;
529 				}
530 			} else if (c == PAGEDEF_END) {
531 				/* Reset the processor state. */
532 				SETSTATE_LOCATE;
533 			} else if (depth == 0 && ! BUFFERFULL(str_page)) {
534 				strncat(str_page, &c, 1);
535 			} else if (depth == 0) {
536 				errx(EX_OSFILE, "%s:%d: %s %zd %s", pagedb_path,
537 				    lineno, "page identifier exceeds",
538 				    sizeof(str_page) - 1, "characters");
539 			}
540 			break;
541 
542 		case PAGENAME:
543 			if (c == PAGENAME_END) {
544 				/*
545 				 * Return to LOCATE state without resetting the
546 				 * page number buffer.
547 				 */
548 				state = LOCATE;
549 			} else if (! BUFFERFULL(str_pagename)) {
550 				strncat(str_pagename, &c, 1);
551 			} else {
552 				errx(EX_OSFILE, "%s:%d: %s %zd %s", pagedb_path,
553 				    lineno, "page name exceeds",
554 				    sizeof(str_page) - 1, "characters");
555 			}
556 			break;
557 
558 		case PAGEDEF:
559 			/*
560 			 * Transfer the page definition into a format buffer
561 			 * suitable for use with CDB encoding/decoding routines.
562 			 */
563 			if (depth == 0) {
564 				found = 1;
565 				SETSTATE_LOCATE;
566 			} else if (! BUFFERFULL(format)) {
567 				strncat(format, &c, 1);
568 			} else {
569 				errx(EX_OSFILE, "%s:%d: %s %zd %s", pagedb_path,
570 				    lineno, "page definition exceeds",
571 				    sizeof(format) - 1, "characters");
572 			}
573 			break;
574 
575 		default:
576 			; /* NOTREACHED */
577 		}
578 
579 		/* Repeat processing loop with next character. */
580 	}
581 
582 	if (ferror(pagedb))
583 		err(EX_OSFILE, "%s", pagedb_path);
584 
585 	/* Close the SCSI page database. */
586 	fclose(pagedb);
587 
588 	if (!found)			/* Never found a matching page. */
589 		returnerr(ESRCH);
590 
591 	return (0);
592 }
593 
594 static void
595 editlist_populate(struct cam_device *device, int cdb_len, int dbd, int pc,
596     int page, int subpage, int task_attr, int retries, int timeout)
597 {
598 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
599 	uint8_t *mode_pars;		/* Pointer to modepage params. */
600 	struct scsi_mode_page_header *mph;
601 	struct scsi_mode_page_header_sp *mphsp;
602 	size_t len;
603 
604 	STAILQ_INIT(&editlist);
605 
606 	/* Fetch changeable values; use to build initial editlist. */
607 	mode_sense(device, &cdb_len, dbd, 0, 1, page, subpage, task_attr,
608 		   retries, timeout, data, sizeof(data));
609 
610 	if (cdb_len == 6) {
611 		struct scsi_mode_header_6 *mh =
612 		    (struct scsi_mode_header_6 *)data;
613 		mph = find_mode_page_6(mh);
614 	} else {
615 		struct scsi_mode_header_10 *mh =
616 		    (struct scsi_mode_header_10 *)data;
617 		mph = find_mode_page_10(mh);
618 	}
619 	if ((mph->page_code & SMPH_SPF) == 0) {
620 		mode_pars = (uint8_t *)(mph + 1);
621 		len = mph->page_length;
622 	} else {
623 		mphsp = (struct scsi_mode_page_header_sp *)mph;
624 		mode_pars = (uint8_t *)(mphsp + 1);
625 		len = scsi_2btoul(mphsp->page_length);
626 	}
627 	len = MIN(len, sizeof(data) - (mode_pars - data));
628 
629 	/* Decode the value data, creating edit_entries for each value. */
630 	buff_decode_visit(mode_pars, len, format, editentry_create, 0);
631 
632 	/* Fetch the current/saved values; use to set editentry values. */
633 	mode_sense(device, &cdb_len, dbd, 0, pc, page, subpage, task_attr,
634 	    retries, timeout, data, sizeof(data));
635 	buff_decode_visit(mode_pars, len, format, editentry_update, 0);
636 }
637 
638 static void
639 editlist_populate_desc(struct cam_device *device, int cdb_len, int llbaa, int pc,
640     int page, int subpage, int task_attr, int retries, int timeout)
641 {
642 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
643 	uint8_t *desc;			/* Pointer to block descriptor. */
644 	char num[8];
645 	struct sbuf sb;
646 	size_t len;
647 	u_int longlba, dlen, i;
648 
649 	STAILQ_INIT(&editlist);
650 
651 	/* Fetch the current/saved values. */
652 	mode_sense(device, &cdb_len, 0, llbaa, pc, page, subpage, task_attr,
653 	    retries, timeout, data, sizeof(data));
654 
655 	if (cdb_len == 6) {
656 		struct scsi_mode_header_6 *mh =
657 		    (struct scsi_mode_header_6 *)data;
658 		desc = (uint8_t *)(mh + 1);
659 		len = mh->blk_desc_len;
660 		longlba = 0;
661 	} else {
662 		struct scsi_mode_header_10 *mh =
663 		    (struct scsi_mode_header_10 *)data;
664 		desc = (uint8_t *)(mh + 1);
665 		len = scsi_2btoul(mh->blk_desc_len);
666 		longlba = (mh->flags & SMH_LONGLBA) != 0;
667 	}
668 	dlen = longlba ? 16 : 8;
669 	len = MIN(len, sizeof(data) - (desc - data));
670 
671 	sbuf_new(&sb, format, sizeof(format), SBUF_FIXEDLEN);
672 	num[0] = 0;
673 	for (i = 0; i * dlen < len; i++) {
674 		if (i > 0)
675 			snprintf(num, sizeof(num), " %d", i + 1);
676 		if (longlba) {
677 			sbuf_printf(&sb, "{Number of Logical Blocks%s High} i4\n", num);
678 			sbuf_printf(&sb, "{Number of Logical Blocks%s} i4\n", num);
679 			sbuf_cat(&sb, "{Reserved} *i4\n");
680 			sbuf_printf(&sb, "{Logical Block Length%s} i4\n", num);
681 		} else if (device->pd_type == T_DIRECT) {
682 			sbuf_printf(&sb, "{Number of Logical Blocks%s} i4\n", num);
683 			sbuf_cat(&sb, "{Reserved} *i1\n");
684 			sbuf_printf(&sb, "{Logical Block Length%s} i3\n", num);
685 		} else {
686 			sbuf_printf(&sb, "{Density Code%s} i1\n", num);
687 			sbuf_printf(&sb, "{Number of Logical Blocks%s} i3\n", num);
688 			sbuf_cat(&sb, "{Reserved} *i1\n");
689 			sbuf_printf(&sb, "{Logical Block Length%s} i3\n", num);
690 		}
691 	}
692 	sbuf_finish(&sb);
693 	sbuf_delete(&sb);
694 
695 	/* Decode the value data, creating edit_entries for each value. */
696 	buff_decode_visit(desc, len, format, editentry_create_desc, 0);
697 }
698 
699 static void
700 editlist_save(struct cam_device *device, int cdb_len, int dbd, int pc,
701     int page, int subpage, int task_attr, int retries, int timeout)
702 {
703 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
704 	uint8_t *mode_pars;		/* Pointer to modepage params. */
705 	struct scsi_mode_page_header *mph;
706 	struct scsi_mode_page_header_sp *mphsp;
707 	size_t len, hlen, mphlen;
708 
709 	/* Make sure that something changed before continuing. */
710 	if (! editlist_changed)
711 		return;
712 
713 	/* Preload the CDB buffer with the current mode page data. */
714 	mode_sense(device, &cdb_len, dbd, 0, pc, page, subpage, task_attr,
715 	    retries, timeout, data, sizeof(data));
716 
717 	/* Initial headers & offsets. */
718 	/*
719 	 * Tape drives include write protect (WP), Buffered Mode and Speed
720 	 * settings in the device-specific parameter.  Clearing this
721 	 * parameter on a mode select can have the effect of turning off
722 	 * write protect or buffered mode, or changing the speed setting of
723 	 * the tape drive.
724 	 *
725 	 * Disks report DPO/FUA support via the device specific parameter
726 	 * for MODE SENSE, but the bit is reserved for MODE SELECT.  So we
727 	 * clear this for disks (and other non-tape devices) to avoid
728 	 * potential errors from the target device.
729 	 */
730 	if (cdb_len == 6) {
731 		struct scsi_mode_header_6 *mh =
732 		    (struct scsi_mode_header_6 *)data;
733 		hlen = sizeof(*mh);
734 		/* Eliminate block descriptors. */
735 		if (mh->blk_desc_len > 0) {
736 			bcopy(find_mode_page_6(mh), mh + 1,
737 			    mh->data_length + 1 - hlen -
738 			    mh->blk_desc_len);
739 			mh->blk_desc_len = 0;
740 		}
741 		mh->data_length = 0;	/* Reserved for MODE SELECT command. */
742 		if (device->pd_type != T_SEQUENTIAL)
743 			mh->dev_spec = 0;	/* See comment above */
744 		mph = find_mode_page_6(mh);
745 	} else {
746 		struct scsi_mode_header_10 *mh =
747 		    (struct scsi_mode_header_10 *)data;
748 		hlen = sizeof(*mh);
749 		/* Eliminate block descriptors. */
750 		if (scsi_2btoul(mh->blk_desc_len) > 0) {
751 			bcopy(find_mode_page_10(mh), mh + 1,
752 			    scsi_2btoul(mh->data_length) + 1 - hlen -
753 			    scsi_2btoul(mh->blk_desc_len));
754 			scsi_ulto2b(0, mh->blk_desc_len);
755 		}
756 		scsi_ulto2b(0, mh->data_length); /* Reserved for MODE SELECT. */
757 		if (device->pd_type != T_SEQUENTIAL)
758 			mh->dev_spec = 0;	/* See comment above */
759 		mph = find_mode_page_10(mh);
760 	}
761 	if ((mph->page_code & SMPH_SPF) == 0) {
762 		mphlen = sizeof(*mph);
763 		mode_pars = (uint8_t *)(mph + 1);
764 		len = mph->page_length;
765 	} else {
766 		mphsp = (struct scsi_mode_page_header_sp *)mph;
767 		mphlen = sizeof(*mphsp);
768 		mode_pars = (uint8_t *)(mphsp + 1);
769 		len = scsi_2btoul(mphsp->page_length);
770 	}
771 	len = MIN(len, sizeof(data) - (mode_pars - data));
772 
773 	/* Encode the value data to be passed back to the device. */
774 	buff_encode_visit(mode_pars, len, format, editentry_save, 0);
775 
776 	mph->page_code &= ~SMPH_PS;	/* Reserved for MODE SELECT command. */
777 
778 	/*
779 	 * Write the changes back to the device. If the user editted control
780 	 * page 3 (saved values) then request the changes be permanently
781 	 * recorded.
782 	 */
783 	mode_select(device, cdb_len, (pc << PAGE_CTRL_SHIFT == SMS_PAGE_CTRL_SAVED),
784 	    task_attr, retries, timeout, data, hlen + mphlen + len);
785 }
786 
787 static void
788 editlist_save_desc(struct cam_device *device, int cdb_len, int llbaa, int pc,
789     int page, int subpage, int task_attr, int retries, int timeout)
790 {
791 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
792 	uint8_t *desc;			/* Pointer to block descriptor. */
793 	size_t len, hlen;
794 
795 	/* Make sure that something changed before continuing. */
796 	if (! editlist_changed)
797 		return;
798 
799 	/* Preload the CDB buffer with the current mode page data. */
800 	mode_sense(device, &cdb_len, 0, llbaa, pc, page, subpage, task_attr,
801 	    retries, timeout, data, sizeof(data));
802 
803 	/* Initial headers & offsets. */
804 	if (cdb_len == 6) {
805 		struct scsi_mode_header_6 *mh =
806 		    (struct scsi_mode_header_6 *)data;
807 		hlen = sizeof(*mh);
808 		desc = (uint8_t *)(mh + 1);
809 		len = mh->blk_desc_len;
810 		mh->data_length = 0;	/* Reserved for MODE SELECT command. */
811 		if (device->pd_type != T_SEQUENTIAL)
812 			mh->dev_spec = 0;	/* See comment above */
813 	} else {
814 		struct scsi_mode_header_10 *mh =
815 		    (struct scsi_mode_header_10 *)data;
816 		hlen = sizeof(*mh);
817 		desc = (uint8_t *)(mh + 1);
818 		len = scsi_2btoul(mh->blk_desc_len);
819 		scsi_ulto2b(0, mh->data_length); /* Reserved for MODE SELECT. */
820 		if (device->pd_type != T_SEQUENTIAL)
821 			mh->dev_spec = 0;	/* See comment above */
822 	}
823 	len = MIN(len, sizeof(data) - (desc - data));
824 
825 	/* Encode the value data to be passed back to the device. */
826 	buff_encode_visit(desc, len, format, editentry_save, 0);
827 
828 	/*
829 	 * Write the changes back to the device. If the user editted control
830 	 * page 3 (saved values) then request the changes be permanently
831 	 * recorded.
832 	 */
833 	mode_select(device, cdb_len, (pc << PAGE_CTRL_SHIFT == SMS_PAGE_CTRL_SAVED),
834 	    task_attr, retries, timeout, data, hlen + len);
835 }
836 
837 static int
838 modepage_write(FILE *file, int editonly)
839 {
840 	struct editentry *scan;
841 	int written = 0;
842 
843 	STAILQ_FOREACH(scan, &editlist, link) {
844 		if (scan->editable || !editonly) {
845 			written++;
846 			if (scan->type == 'c' || scan->type == 'z') {
847 				fprintf(file, "%s:  %s\n", scan->name,
848 				    scan->value.svalue);
849 			} else {
850 				fprintf(file, "%s:  %u\n", scan->name,
851 				    scan->value.ivalue);
852 			}
853 		}
854 	}
855 	return (written);
856 }
857 
858 static int
859 modepage_read(FILE *file)
860 {
861 	char *buffer;			/* Pointer to dynamic line buffer.  */
862 	char *line;			/* Pointer to static fgetln buffer. */
863 	char *name;			/* Name portion of the line buffer. */
864 	char *value;			/* Value portion of line buffer.    */
865 	size_t length;			/* Length of static fgetln buffer.  */
866 
867 #define	ABORT_READ(message, param) do {					\
868 	warnx(message, param);						\
869 	free(buffer);							\
870 	returnerr(EAGAIN);						\
871 } while (0)
872 
873 	while ((line = fgetln(file, &length)) != NULL) {
874 		/* Trim trailing whitespace (including optional newline). */
875 		while (length > 0 && isspace(line[length - 1]))
876 			length--;
877 
878 	    	/* Allocate a buffer to hold the line + terminating null. */
879 	    	if ((buffer = malloc(length + 1)) == NULL)
880 			err(EX_OSERR, NULL);
881 		memcpy(buffer, line, length);
882 		buffer[length] = '\0';
883 
884 		/* Strip out comments. */
885 		if ((value = strchr(buffer, '#')) != NULL)
886 			*value = '\0';
887 
888 		/* The name is first in the buffer. Trim whitespace.*/
889 		name = buffer;
890 		RTRIM(name);
891 		while (isspace(*name))
892 			name++;
893 
894 		/* Skip empty lines. */
895 		if (strlen(name) == 0)
896 			continue;
897 
898 		/* The name ends at the colon; the value starts there. */
899 		if ((value = strrchr(buffer, ':')) == NULL)
900 			ABORT_READ("no value associated with %s", name);
901 		*value = '\0';			/* Null-terminate name. */
902 		value++;			/* Value starts afterwards. */
903 
904 		/* Trim leading and trailing whitespace. */
905 		RTRIM(value);
906 		while (isspace(*value))
907 			value++;
908 
909 		/* Make sure there is a value left. */
910 		if (strlen(value) == 0)
911 			ABORT_READ("no value associated with %s", name);
912 
913 		/* Update our in-memory copy of the modepage entry value. */
914 		if (editentry_set(name, value, 1) != 0) {
915 			if (errno == ENOENT) {
916 				/* No entry by the name. */
917 				ABORT_READ("no such modepage entry \"%s\"",
918 				    name);
919 			} else if (errno == EINVAL) {
920 				/* Invalid value. */
921 				ABORT_READ("Invalid value for entry \"%s\"",
922 				    name);
923 			} else if (errno == ERANGE) {
924 				/* Value out of range for entry type. */
925 				ABORT_READ("value out of range for %s", name);
926 			} else if (errno == EPERM) {
927 				/* Entry is not editable; not fatal. */
928 				warnx("modepage entry \"%s\" is read-only; "
929 				    "skipping.", name);
930 			}
931 		}
932 
933 		free(buffer);
934 	}
935 	return (ferror(file)? -1: 0);
936 
937 #undef ABORT_READ
938 }
939 
940 static void
941 modepage_edit(void)
942 {
943 	const char *editor;
944 	char *commandline;
945 	int fd;
946 	int written;
947 
948 	if (!isatty(fileno(stdin))) {
949 		/* Not a tty, read changes from stdin. */
950 		modepage_read(stdin);
951 		return;
952 	}
953 
954 	/* Lookup editor to invoke. */
955 	if ((editor = getenv("EDITOR")) == NULL)
956 		editor = DEFAULT_EDITOR;
957 
958 	/* Create temp file for editor to modify. */
959 	if ((fd = mkstemp(edit_path)) == -1)
960 		errx(EX_CANTCREAT, "mkstemp failed");
961 
962 	atexit(cleanup_editfile);
963 
964 	if ((edit_file = fdopen(fd, "w")) == NULL)
965 		err(EX_NOINPUT, "%s", edit_path);
966 
967 	written = modepage_write(edit_file, 1);
968 
969 	fclose(edit_file);
970 	edit_file = NULL;
971 
972 	if (written == 0) {
973 		warnx("no editable entries");
974 		cleanup_editfile();
975 		return;
976 	}
977 
978 	/*
979 	 * Allocate memory to hold the command line (the 2 extra characters
980 	 * are to hold the argument separator (a space), and the terminating
981 	 * null character.
982 	 */
983 	commandline = malloc(strlen(editor) + strlen(edit_path) + 2);
984 	if (commandline == NULL)
985 		err(EX_OSERR, NULL);
986 	sprintf(commandline, "%s %s", editor, edit_path);
987 
988 	/* Invoke the editor on the temp file. */
989 	if (system(commandline) == -1)
990 		err(EX_UNAVAILABLE, "could not invoke %s", editor);
991 	free(commandline);
992 
993 	if ((edit_file = fopen(edit_path, "r")) == NULL)
994 		err(EX_NOINPUT, "%s", edit_path);
995 
996 	/* Read any changes made to the temp file. */
997 	modepage_read(edit_file);
998 
999 	cleanup_editfile();
1000 }
1001 
1002 static void
1003 modepage_dump(struct cam_device *device, int cdb_len, int dbd, int pc,
1004 	      int page, int subpage, int task_attr, int retries, int timeout)
1005 {
1006 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
1007 	uint8_t *mode_pars;		/* Pointer to modepage params. */
1008 	struct scsi_mode_page_header *mph;
1009 	struct scsi_mode_page_header_sp *mphsp;
1010 	size_t indx, len;
1011 
1012 	mode_sense(device, &cdb_len, dbd, 0, pc, page, subpage, task_attr,
1013 	    retries, timeout, data, sizeof(data));
1014 
1015 	if (cdb_len == 6) {
1016 		struct scsi_mode_header_6 *mh =
1017 		    (struct scsi_mode_header_6 *)data;
1018 		mph = find_mode_page_6(mh);
1019 	} else {
1020 		struct scsi_mode_header_10 *mh =
1021 		    (struct scsi_mode_header_10 *)data;
1022 		mph = find_mode_page_10(mh);
1023 	}
1024 	if ((mph->page_code & SMPH_SPF) == 0) {
1025 		mode_pars = (uint8_t *)(mph + 1);
1026 		len = mph->page_length;
1027 	} else {
1028 		mphsp = (struct scsi_mode_page_header_sp *)mph;
1029 		mode_pars = (uint8_t *)(mphsp + 1);
1030 		len = scsi_2btoul(mphsp->page_length);
1031 	}
1032 	len = MIN(len, sizeof(data) - (mode_pars - data));
1033 
1034 	/* Print the raw mode page data with newlines each 8 bytes. */
1035 	for (indx = 0; indx < len; indx++) {
1036 		printf("%02x%c",mode_pars[indx],
1037 		    (((indx + 1) % 8) == 0) ? '\n' : ' ');
1038 	}
1039 	putchar('\n');
1040 }
1041 static void
1042 modepage_dump_desc(struct cam_device *device, int cdb_len, int llbaa, int pc,
1043 	      int page, int subpage, int task_attr, int retries, int timeout)
1044 {
1045 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
1046 	uint8_t *desc;			/* Pointer to block descriptor. */
1047 	size_t indx, len;
1048 
1049 	mode_sense(device, &cdb_len, 0, llbaa, pc, page, subpage, task_attr,
1050 	    retries, timeout, data, sizeof(data));
1051 
1052 	if (cdb_len == 6) {
1053 		struct scsi_mode_header_6 *mh =
1054 		    (struct scsi_mode_header_6 *)data;
1055 		desc = (uint8_t *)(mh + 1);
1056 		len = mh->blk_desc_len;
1057 	} else {
1058 		struct scsi_mode_header_10 *mh =
1059 		    (struct scsi_mode_header_10 *)data;
1060 		desc = (uint8_t *)(mh + 1);
1061 		len = scsi_2btoul(mh->blk_desc_len);
1062 	}
1063 	len = MIN(len, sizeof(data) - (desc - data));
1064 
1065 	/* Print the raw mode page data with newlines each 8 bytes. */
1066 	for (indx = 0; indx < len; indx++) {
1067 		printf("%02x%c", desc[indx],
1068 		    (((indx + 1) % 8) == 0) ? '\n' : ' ');
1069 	}
1070 	putchar('\n');
1071 }
1072 
1073 static void
1074 cleanup_editfile(void)
1075 {
1076 	if (edit_file == NULL)
1077 		return;
1078 	if (fclose(edit_file) != 0 || unlink(edit_path) != 0)
1079 		warn("%s", edit_path);
1080 	edit_file = NULL;
1081 }
1082 
1083 void
1084 mode_edit(struct cam_device *device, int cdb_len, int desc, int dbd, int llbaa,
1085     int pc, int page, int subpage, int edit, int binary, int task_attr,
1086     int retry_count, int timeout)
1087 {
1088 	const char *pagedb_path;	/* Path to modepage database. */
1089 
1090 	if (binary) {
1091 		if (edit)
1092 			errx(EX_USAGE, "cannot edit in binary mode.");
1093 	} else if (desc) {
1094 		editlist_populate_desc(device, cdb_len, llbaa, pc, page,
1095 		    subpage, task_attr, retry_count, timeout);
1096 	} else {
1097 		if ((pagedb_path = getenv("SCSI_MODES")) == NULL)
1098 			pagedb_path = DEFAULT_SCSI_MODE_DB;
1099 
1100 		if (load_format(pagedb_path, page, subpage) != 0 &&
1101 		    (edit || verbose)) {
1102 			if (errno == ENOENT) {
1103 				/* Modepage database file not found. */
1104 				warn("cannot open modepage database \"%s\"",
1105 				    pagedb_path);
1106 			} else if (errno == ESRCH) {
1107 				/* Modepage entry not found in database. */
1108 				warnx("modepage 0x%02x,0x%02x not found in "
1109 				    "database \"%s\"", page, subpage,
1110 				    pagedb_path);
1111 			}
1112 			/* We can recover in display mode, otherwise we exit. */
1113 			if (!edit) {
1114 				warnx("reverting to binary display only");
1115 				binary = 1;
1116 			} else
1117 				exit(EX_OSFILE);
1118 		}
1119 
1120 		editlist_populate(device, cdb_len, dbd, pc, page, subpage,
1121 		    task_attr, retry_count, timeout);
1122 	}
1123 
1124 	if (edit) {
1125 		if (pc << PAGE_CTRL_SHIFT != SMS_PAGE_CTRL_CURRENT &&
1126 		    pc << PAGE_CTRL_SHIFT != SMS_PAGE_CTRL_SAVED)
1127 			errx(EX_USAGE, "it only makes sense to edit page 0 "
1128 			    "(current) or page 3 (saved values)");
1129 		modepage_edit();
1130 		if (desc) {
1131 			editlist_save_desc(device, cdb_len, llbaa, pc, page,
1132 			    subpage, task_attr, retry_count, timeout);
1133 		} else {
1134 			editlist_save(device, cdb_len, dbd, pc, page, subpage,
1135 			    task_attr, retry_count, timeout);
1136 		}
1137 	} else if (binary || STAILQ_EMPTY(&editlist)) {
1138 		/* Display without formatting information. */
1139 		if (desc) {
1140 			modepage_dump_desc(device, cdb_len, llbaa, pc, page,
1141 			    subpage, task_attr, retry_count, timeout);
1142 		} else {
1143 			modepage_dump(device, cdb_len, dbd, pc, page, subpage,
1144 			    task_attr, retry_count, timeout);
1145 		}
1146 	} else {
1147 		/* Display with format. */
1148 		modepage_write(stdout, 0);
1149 	}
1150 }
1151 
1152 void
1153 mode_list(struct cam_device *device, int cdb_len, int dbd, int pc, int subpages,
1154 	  int task_attr, int retry_count, int timeout)
1155 {
1156 	uint8_t data[MAX_DATA_SIZE];	/* Buffer to hold mode parameters. */
1157 	struct scsi_mode_page_header *mph;
1158 	struct scsi_mode_page_header_sp *mphsp;
1159 	struct pagename *nameentry;
1160 	const char *pagedb_path;
1161 	int len, off, page, subpage;
1162 
1163 	if ((pagedb_path = getenv("SCSI_MODES")) == NULL)
1164 		pagedb_path = DEFAULT_SCSI_MODE_DB;
1165 
1166 	if (load_format(pagedb_path, 0, 0) != 0 && verbose && errno == ENOENT) {
1167 		/* Modepage database file not found. */
1168 		warn("cannot open modepage database \"%s\"", pagedb_path);
1169 	}
1170 
1171 	/* Build the list of all mode pages by querying the "all pages" page. */
1172 	mode_sense(device, &cdb_len, dbd, 0, pc, SMS_ALL_PAGES_PAGE,
1173 	    subpages ? SMS_SUBPAGE_ALL : 0,
1174 	    task_attr, retry_count, timeout, data, sizeof(data));
1175 
1176 	/* Skip block descriptors. */
1177 	if (cdb_len == 6) {
1178 		struct scsi_mode_header_6 *mh =
1179 		    (struct scsi_mode_header_6 *)data;
1180 		len = mh->data_length;
1181 		off = sizeof(*mh) + mh->blk_desc_len;
1182 	} else {
1183 		struct scsi_mode_header_10 *mh =
1184 		    (struct scsi_mode_header_10 *)data;
1185 		len = scsi_2btoul(mh->data_length);
1186 		off = sizeof(*mh) + scsi_2btoul(mh->blk_desc_len);
1187 	}
1188 	/* Iterate through the pages in the reply. */
1189 	while (off < len) {
1190 		/* Locate the next mode page header. */
1191 		mph = (struct scsi_mode_page_header *)(data + off);
1192 
1193 		if ((mph->page_code & SMPH_SPF) == 0) {
1194 			page = mph->page_code & SMS_PAGE_CODE;
1195 			subpage = 0;
1196 			off += sizeof(*mph) + mph->page_length;
1197 		} else {
1198 			mphsp = (struct scsi_mode_page_header_sp *)mph;
1199 			page = mphsp->page_code & SMS_PAGE_CODE;
1200 			subpage = mphsp->subpage;
1201 			off += sizeof(*mphsp) + scsi_2btoul(mphsp->page_length);
1202 		}
1203 
1204 		nameentry = nameentry_lookup(page, subpage);
1205 		if (subpage == 0) {
1206 			printf("0x%02x\t%s\n", page,
1207 			    nameentry ? nameentry->name : "");
1208 		} else {
1209 			printf("0x%02x,0x%02x\t%s\n", page, subpage,
1210 			    nameentry ? nameentry->name : "");
1211 		}
1212 	}
1213 }
1214