xref: /freebsd/sys/cam/cam.c (revision 076b94438c7d42c1b4661ed1e12e3b12ca69361a)
1 /*-
2  * Generic utility routines for the Common Access Method layer.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 1997 Justin T. Gibbs.
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. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/sysctl.h>
39 #else /* _KERNEL */
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <camlib.h>
44 #endif /* _KERNEL */
45 
46 #include <cam/cam.h>
47 #include <cam/cam_ccb.h>
48 #include <cam/scsi/scsi_all.h>
49 #include <cam/scsi/smp_all.h>
50 #include <sys/sbuf.h>
51 
52 #ifdef _KERNEL
53 #include <sys/libkern.h>
54 #include <cam/cam_queue.h>
55 #include <cam/cam_xpt.h>
56 
57 FEATURE(scbus, "SCSI devices support");
58 
59 #endif
60 
61 static int	camstatusentrycomp(const void *key, const void *member);
62 
63 const struct cam_status_entry cam_status_table[] = {
64 	{ CAM_REQ_INPROG,	 "CCB request is in progress"		     },
65 	{ CAM_REQ_CMP,		 "CCB request completed without error"	     },
66 	{ CAM_REQ_ABORTED,	 "CCB request aborted by the host"	     },
67 	{ CAM_UA_ABORT,		 "Unable to abort CCB request"		     },
68 	{ CAM_REQ_CMP_ERR,	 "CCB request completed with an error"	     },
69 	{ CAM_BUSY,		 "CAM subsystem is busy"		     },
70 	{ CAM_REQ_INVALID,	 "CCB request was invalid"		     },
71 	{ CAM_PATH_INVALID,	 "Supplied Path ID is invalid"		     },
72 	{ CAM_DEV_NOT_THERE,	 "Device Not Present"			     },
73 	{ CAM_UA_TERMIO,	 "Unable to terminate I/O CCB request"	     },
74 	{ CAM_SEL_TIMEOUT,	 "Selection Timeout"			     },
75 	{ CAM_CMD_TIMEOUT,	 "Command timeout"			     },
76 	{ CAM_SCSI_STATUS_ERROR, "SCSI Status Error"			     },
77 	{ CAM_MSG_REJECT_REC,	 "Message Reject Reveived"		     },
78 	{ CAM_SCSI_BUS_RESET,	 "SCSI Bus Reset Sent/Received"		     },
79 	{ CAM_UNCOR_PARITY,	 "Uncorrectable parity/CRC error"	     },
80 	{ CAM_AUTOSENSE_FAIL,	 "Auto-Sense Retrieval Failed"		     },
81 	{ CAM_NO_HBA,		 "No HBA Detected"			     },
82 	{ CAM_DATA_RUN_ERR,	 "Data Overrun error"			     },
83 	{ CAM_UNEXP_BUSFREE,	 "Unexpected Bus Free"			     },
84 	{ CAM_SEQUENCE_FAIL,	 "Target Bus Phase Sequence Failure"	     },
85 	{ CAM_CCB_LEN_ERR,	 "CCB length supplied is inadequate"	     },
86 	{ CAM_PROVIDE_FAIL,	 "Unable to provide requested capability"    },
87 	{ CAM_BDR_SENT,		 "SCSI BDR Message Sent"		     },
88 	{ CAM_REQ_TERMIO,	 "CCB request terminated by the host"	     },
89 	{ CAM_UNREC_HBA_ERROR,	 "Unrecoverable Host Bus Adapter Error"	     },
90 	{ CAM_REQ_TOO_BIG,	 "The request was too large for this host"   },
91 	{ CAM_REQUEUE_REQ,	 "Unconditionally Re-queue Request",	     },
92 	{ CAM_ATA_STATUS_ERROR,	 "ATA Status Error"			     },
93 	{ CAM_SCSI_IT_NEXUS_LOST,"Initiator/Target Nexus Lost"               },
94 	{ CAM_SMP_STATUS_ERROR,	 "SMP Status Error"                          },
95 	{ CAM_IDE,		 "Initiator Detected Error Message Received" },
96 	{ CAM_RESRC_UNAVAIL,	 "Resource Unavailable"			     },
97 	{ CAM_UNACKED_EVENT,	 "Unacknowledged Event by Host"		     },
98 	{ CAM_MESSAGE_RECV,	 "Message Received in Host Target Mode"	     },
99 	{ CAM_INVALID_CDB,	 "Invalid CDB received in Host Target Mode"  },
100 	{ CAM_LUN_INVALID,	 "Invalid Lun"				     },
101 	{ CAM_TID_INVALID,	 "Invalid Target ID"			     },
102 	{ CAM_FUNC_NOTAVAIL,	 "Function Not Available"		     },
103 	{ CAM_NO_NEXUS,		 "Nexus Not Established"		     },
104 	{ CAM_IID_INVALID,	 "Invalid Initiator ID"			     },
105 	{ CAM_CDB_RECVD,	 "CDB Received"				     },
106 	{ CAM_LUN_ALRDY_ENA,	 "LUN Already Enabled for Target Mode"	     },
107 	{ CAM_SCSI_BUSY,	 "SCSI Bus Busy"			     },
108 };
109 
110 #ifdef _KERNEL
111 SYSCTL_NODE(_kern, OID_AUTO, cam, CTLFLAG_RD, 0, "CAM Subsystem");
112 
113 #ifndef CAM_DEFAULT_SORT_IO_QUEUES
114 #define CAM_DEFAULT_SORT_IO_QUEUES 1
115 #endif
116 
117 int cam_sort_io_queues = CAM_DEFAULT_SORT_IO_QUEUES;
118 SYSCTL_INT(_kern_cam, OID_AUTO, sort_io_queues, CTLFLAG_RWTUN,
119     &cam_sort_io_queues, 0, "Sort IO queues to try and optimise disk access patterns");
120 #endif
121 
122 void
123 cam_strvis(u_int8_t *dst, const u_int8_t *src, int srclen, int dstlen)
124 {
125 
126 	/* Trim leading/trailing spaces, nulls. */
127 	while (srclen > 0 && src[0] == ' ')
128 		src++, srclen--;
129 	while (srclen > 0
130 	    && (src[srclen-1] == ' ' || src[srclen-1] == '\0'))
131 		srclen--;
132 
133 	while (srclen > 0 && dstlen > 1) {
134 		u_int8_t *cur_pos = dst;
135 
136 		if (*src < 0x20 || *src >= 0x80) {
137 			/* SCSI-II Specifies that these should never occur. */
138 			/* non-printable character */
139 			if (dstlen > 4) {
140 				*cur_pos++ = '\\';
141 				*cur_pos++ = ((*src & 0300) >> 6) + '0';
142 				*cur_pos++ = ((*src & 0070) >> 3) + '0';
143 				*cur_pos++ = ((*src & 0007) >> 0) + '0';
144 			} else {
145 				*cur_pos++ = '?';
146 			}
147 		} else {
148 			/* normal character */
149 			*cur_pos++ = *src;
150 		}
151 		src++;
152 		srclen--;
153 		dstlen -= cur_pos - dst;
154 		dst = cur_pos;
155 	}
156 	*dst = '\0';
157 }
158 
159 void
160 cam_strvis_sbuf(struct sbuf *sb, const u_int8_t *src, int srclen,
161 		uint32_t flags)
162 {
163 
164 	/* Trim leading/trailing spaces, nulls. */
165 	while (srclen > 0 && src[0] == ' ')
166 		src++, srclen--;
167 	while (srclen > 0
168 	    && (src[srclen-1] == ' ' || src[srclen-1] == '\0'))
169 		srclen--;
170 
171 	while (srclen > 0) {
172 		if (*src < 0x20 || *src >= 0x80) {
173 			/* SCSI-II Specifies that these should never occur. */
174 			/* non-printable character */
175 			switch (flags & CAM_STRVIS_FLAG_NONASCII_MASK) {
176 			case CAM_STRVIS_FLAG_NONASCII_ESC:
177 				sbuf_printf(sb, "\\%c%c%c",
178 				    ((*src & 0300) >> 6) + '0',
179 				    ((*src & 0070) >> 3) + '0',
180 				    ((*src & 0007) >> 0) + '0');
181 				break;
182 			case CAM_STRVIS_FLAG_NONASCII_RAW:
183 				/*
184 				 * If we run into a NUL, just transform it
185 				 * into a space.
186 				 */
187 				if (*src != 0x00)
188 					sbuf_putc(sb, *src);
189 				else
190 					sbuf_putc(sb, ' ');
191 				break;
192 			case CAM_STRVIS_FLAG_NONASCII_SPC:
193 				sbuf_putc(sb, ' ');
194 				break;
195 			case CAM_STRVIS_FLAG_NONASCII_TRIM:
196 			default:
197 				break;
198 			}
199 		} else {
200 			/* normal character */
201 			sbuf_putc(sb, *src);
202 		}
203 		src++;
204 		srclen--;
205 	}
206 }
207 
208 
209 /*
210  * Compare string with pattern, returning 0 on match.
211  * Short pattern matches trailing blanks in name,
212  * Shell globbing rules apply: * matches 0 or more characters,
213  * ? matchces one character, [...] denotes a set to match one char,
214  * [^...] denotes a complimented set to match one character.
215  * Spaces in str used to match anything in the pattern string
216  * but was removed because it's a bug. No current patterns require
217  * it, as far as I know, but it's impossible to know what drives
218  * returned.
219  *
220  * Each '*' generates recursion, so keep the number of * in check.
221  */
222 int
223 cam_strmatch(const u_int8_t *str, const u_int8_t *pattern, int str_len)
224 {
225 
226 	while (*pattern != '\0' && str_len > 0) {
227 		if (*pattern == '*') {
228 			pattern++;
229 			if (*pattern == '\0')
230 				return (0);
231 			do {
232 				if (cam_strmatch(str, pattern, str_len) == 0)
233 					return (0);
234 				str++;
235 				str_len--;
236 			} while (str_len > 0);
237 			return (1);
238 		} else if (*pattern == '[') {
239 			int negate_range, ok;
240 			uint8_t pc = UCHAR_MAX;
241 			uint8_t sc;
242 
243 			ok = 0;
244 			sc = *str++;
245 			str_len--;
246 			pattern++;
247 			if ((negate_range = (*pattern == '^')) != 0)
248 				pattern++;
249 			while ((*pattern != ']') && *pattern != '\0') {
250 				if (*pattern == '-') {
251 					if (pattern[1] == '\0') /* Bad pattern */
252 						return (1);
253 					if (sc >= pc && sc <= pattern[1])
254 						ok = 1;
255 					pattern++;
256 				} else if (*pattern == sc)
257 					ok = 1;
258 				pc = *pattern;
259 				pattern++;
260 			}
261 			if (ok == negate_range)
262 				return (1);
263 			pattern++;
264 		} else if (*pattern == '?') {
265 			/*
266 			 * NB: || *str == ' ' of the old code is a bug and was
267 			 * removed.  If you add it back, keep this the last if
268 			 * before the naked else */
269 			pattern++;
270 			str++;
271 			str_len--;
272 		} else {
273 			if (*str != *pattern)
274 				return (1);
275 			pattern++;
276 			str++;
277 			str_len--;
278 		}
279 	}
280 
281 	/* '*' is allowed to match nothing, so gobble it */
282 	while (*pattern == '*')
283 		pattern++;
284 
285 	if ( *pattern != '\0') {
286 		/* Pattern not fully consumed.  Not a match */
287 		return (1);
288 	}
289 
290 	/* Eat trailing spaces, which get added by SAT */
291 	while (str_len > 0 && *str == ' ') {
292 		str++;
293 		str_len--;
294 	}
295 
296 	return (str_len);
297 }
298 
299 caddr_t
300 cam_quirkmatch(caddr_t target, caddr_t quirk_table, int num_entries,
301 	       int entry_size, cam_quirkmatch_t *comp_func)
302 {
303 	for (; num_entries > 0; num_entries--, quirk_table += entry_size) {
304 		if ((*comp_func)(target, quirk_table) == 0)
305 			return (quirk_table);
306 	}
307 	return (NULL);
308 }
309 
310 const struct cam_status_entry*
311 cam_fetch_status_entry(cam_status status)
312 {
313 	status &= CAM_STATUS_MASK;
314 	return (bsearch(&status, &cam_status_table,
315 			nitems(cam_status_table),
316 			sizeof(*cam_status_table),
317 			camstatusentrycomp));
318 }
319 
320 static int
321 camstatusentrycomp(const void *key, const void *member)
322 {
323 	cam_status status;
324 	const struct cam_status_entry *table_entry;
325 
326 	status = *(const cam_status *)key;
327 	table_entry = (const struct cam_status_entry *)member;
328 
329 	return (status - table_entry->status_code);
330 }
331 
332 
333 #ifdef _KERNEL
334 char *
335 cam_error_string(union ccb *ccb, char *str, int str_len,
336 		 cam_error_string_flags flags,
337 		 cam_error_proto_flags proto_flags)
338 #else /* !_KERNEL */
339 char *
340 cam_error_string(struct cam_device *device, union ccb *ccb, char *str,
341 		 int str_len, cam_error_string_flags flags,
342 		 cam_error_proto_flags proto_flags)
343 #endif /* _KERNEL/!_KERNEL */
344 {
345 	char path_str[64];
346 	struct sbuf sb;
347 
348 	if ((ccb == NULL)
349 	 || (str == NULL)
350 	 || (str_len <= 0))
351 		return(NULL);
352 
353 	if (flags == CAM_ESF_NONE)
354 		return(NULL);
355 
356 	switch (ccb->ccb_h.func_code) {
357 		case XPT_ATA_IO:
358 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
359 			case CAM_EPF_NONE:
360 				break;
361 			case CAM_EPF_ALL:
362 			case CAM_EPF_NORMAL:
363 				proto_flags |= CAM_EAF_PRINT_RESULT;
364 				/* FALLTHROUGH */
365 			case CAM_EPF_MINIMAL:
366 				proto_flags |= CAM_EAF_PRINT_STATUS;
367 				/* FALLTHROUGH */
368 			default:
369 				break;
370 			}
371 			break;
372 		case XPT_SCSI_IO:
373 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
374 			case CAM_EPF_NONE:
375 				break;
376 			case CAM_EPF_ALL:
377 			case CAM_EPF_NORMAL:
378 				proto_flags |= CAM_ESF_PRINT_SENSE;
379 				/* FALLTHROUGH */
380 			case CAM_EPF_MINIMAL:
381 				proto_flags |= CAM_ESF_PRINT_STATUS;
382 				/* FALLTHROUGH */
383 			default:
384 				break;
385 			}
386 			break;
387 		case XPT_SMP_IO:
388 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
389 			case CAM_EPF_NONE:
390 				break;
391 			case CAM_EPF_ALL:
392 				proto_flags |= CAM_ESMF_PRINT_FULL_CMD;
393 				/* FALLTHROUGH */
394 			case CAM_EPF_NORMAL:
395 			case CAM_EPF_MINIMAL:
396 				proto_flags |= CAM_ESMF_PRINT_STATUS;
397 				/* FALLTHROUGH */
398 			default:
399 				break;
400 			}
401 			break;
402 		default:
403 			break;
404 	}
405 #ifdef _KERNEL
406 	xpt_path_string(ccb->csio.ccb_h.path, path_str, sizeof(path_str));
407 #else /* !_KERNEL */
408 	cam_path_string(device, path_str, sizeof(path_str));
409 #endif /* _KERNEL/!_KERNEL */
410 
411 	sbuf_new(&sb, str, str_len, 0);
412 
413 	if (flags & CAM_ESF_COMMAND) {
414 		sbuf_cat(&sb, path_str);
415 		switch (ccb->ccb_h.func_code) {
416 		case XPT_ATA_IO:
417 			ata_command_sbuf(&ccb->ataio, &sb);
418 			sbuf_printf(&sb, "\n");
419 			break;
420 		case XPT_SCSI_IO:
421 #ifdef _KERNEL
422 			scsi_command_string(&ccb->csio, &sb);
423 #else /* !_KERNEL */
424 			scsi_command_string(device, &ccb->csio, &sb);
425 #endif /* _KERNEL/!_KERNEL */
426 			sbuf_printf(&sb, "\n");
427 			break;
428 		case XPT_SMP_IO:
429 			smp_command_sbuf(&ccb->smpio, &sb, path_str, 79 -
430 					 strlen(path_str), (proto_flags &
431 					 CAM_ESMF_PRINT_FULL_CMD) ? 79 : 0);
432 			sbuf_printf(&sb, "\n");
433 			break;
434 		default:
435 			break;
436 		}
437 	}
438 
439 	if (flags & CAM_ESF_CAM_STATUS) {
440 		cam_status status;
441 		const struct cam_status_entry *entry;
442 
443 		sbuf_cat(&sb, path_str);
444 
445 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
446 
447 		entry = cam_fetch_status_entry(status);
448 
449 		if (entry == NULL)
450 			sbuf_printf(&sb, "CAM status: Unknown (%#x)\n",
451 				    ccb->ccb_h.status);
452 		else
453 			sbuf_printf(&sb, "CAM status: %s\n",
454 				    entry->status_text);
455 	}
456 
457 	if (flags & CAM_ESF_PROTO_STATUS) {
458 
459 		switch (ccb->ccb_h.func_code) {
460 		case XPT_ATA_IO:
461 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
462 			     CAM_ATA_STATUS_ERROR)
463 				break;
464 			if (proto_flags & CAM_EAF_PRINT_STATUS) {
465 				sbuf_cat(&sb, path_str);
466 				ata_status_sbuf(&ccb->ataio, &sb);
467 				sbuf_printf(&sb, "\n");
468 			}
469 			if (proto_flags & CAM_EAF_PRINT_RESULT) {
470 				sbuf_cat(&sb, path_str);
471 				sbuf_printf(&sb, "RES: ");
472 				ata_res_sbuf(&ccb->ataio.res, &sb);
473 				sbuf_printf(&sb, "\n");
474 			}
475 
476 			break;
477 		case XPT_SCSI_IO:
478 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
479 			     CAM_SCSI_STATUS_ERROR)
480 				break;
481 
482 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
483 				sbuf_cat(&sb, path_str);
484 				sbuf_printf(&sb, "SCSI status: %s\n",
485 					    scsi_status_string(&ccb->csio));
486 			}
487 
488 			if ((proto_flags & CAM_ESF_PRINT_SENSE)
489 			 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
490 			 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)) {
491 
492 #ifdef _KERNEL
493 				scsi_sense_sbuf(&ccb->csio, &sb,
494 						SSS_FLAG_NONE);
495 #else /* !_KERNEL */
496 				scsi_sense_sbuf(device, &ccb->csio, &sb,
497 						SSS_FLAG_NONE);
498 #endif /* _KERNEL/!_KERNEL */
499 			}
500 			break;
501 		case XPT_SMP_IO:
502 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
503 			     CAM_SMP_STATUS_ERROR)
504 				break;
505 
506 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
507 				sbuf_cat(&sb, path_str);
508 				sbuf_printf(&sb, "SMP status: %s (%#x)\n",
509 				    smp_error_desc(ccb->smpio.smp_response[2]),
510 						   ccb->smpio.smp_response[2]);
511 			}
512 			/* There is no SMP equivalent to SCSI sense. */
513 			break;
514 		default:
515 			break;
516 		}
517 	}
518 
519 	sbuf_finish(&sb);
520 
521 	return(sbuf_data(&sb));
522 }
523 
524 #ifdef _KERNEL
525 
526 void
527 cam_error_print(union ccb *ccb, cam_error_string_flags flags,
528 		cam_error_proto_flags proto_flags)
529 {
530 	char str[512];
531 
532 	printf("%s", cam_error_string(ccb, str, sizeof(str), flags,
533 	       proto_flags));
534 }
535 
536 #else /* !_KERNEL */
537 
538 void
539 cam_error_print(struct cam_device *device, union ccb *ccb,
540 		cam_error_string_flags flags, cam_error_proto_flags proto_flags,
541 		FILE *ofile)
542 {
543 	char str[512];
544 
545 	if ((device == NULL) || (ccb == NULL) || (ofile == NULL))
546 		return;
547 
548 	fprintf(ofile, "%s", cam_error_string(device, ccb, str, sizeof(str),
549 		flags, proto_flags));
550 }
551 
552 #endif /* _KERNEL/!_KERNEL */
553 
554 /*
555  * Common calculate geometry fuction
556  *
557  * Caller should set ccg->volume_size and block_size.
558  * The extended parameter should be zero if extended translation
559  * should not be used.
560  */
561 void
562 cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
563 {
564 	uint32_t size_mb, secs_per_cylinder;
565 
566 	if (ccg->block_size == 0) {
567 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
568 		return;
569 	}
570 	size_mb = (1024L * 1024L) / ccg->block_size;
571 	if (size_mb == 0) {
572 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
573 		return;
574 	}
575 	size_mb = ccg->volume_size / size_mb;
576 	if (size_mb > 1024 && extended) {
577 		ccg->heads = 255;
578 		ccg->secs_per_track = 63;
579 	} else {
580 		ccg->heads = 64;
581 		ccg->secs_per_track = 32;
582 	}
583 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
584 	if (secs_per_cylinder == 0) {
585 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
586 		return;
587 	}
588 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
589 	ccg->ccb_h.status = CAM_REQ_CMP;
590 }
591