xref: /freebsd/sys/cam/cam.c (revision 4bc52338)
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 			break;
419 		case XPT_SCSI_IO:
420 #ifdef _KERNEL
421 			scsi_command_string(&ccb->csio, &sb);
422 #else /* !_KERNEL */
423 			scsi_command_string(device, &ccb->csio, &sb);
424 #endif /* _KERNEL/!_KERNEL */
425 			break;
426 		case XPT_SMP_IO:
427 			smp_command_sbuf(&ccb->smpio, &sb, path_str, 79 -
428 					 strlen(path_str), (proto_flags &
429 					 CAM_ESMF_PRINT_FULL_CMD) ? 79 : 0);
430 			break;
431 		case XPT_NVME_IO:
432 		case XPT_NVME_ADMIN:
433 			nvme_command_sbuf(&ccb->nvmeio, &sb);
434 			break;
435 		default:
436 			sbuf_printf(&sb, "CAM func %#x",
437 			    ccb->ccb_h.func_code);
438 			break;
439 		}
440 		sbuf_printf(&sb, "\n");
441 	}
442 
443 	if (flags & CAM_ESF_CAM_STATUS) {
444 		cam_status status;
445 		const struct cam_status_entry *entry;
446 
447 		sbuf_cat(&sb, path_str);
448 
449 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
450 
451 		entry = cam_fetch_status_entry(status);
452 
453 		if (entry == NULL)
454 			sbuf_printf(&sb, "CAM status: Unknown (%#x)\n",
455 				    ccb->ccb_h.status);
456 		else
457 			sbuf_printf(&sb, "CAM status: %s\n",
458 				    entry->status_text);
459 	}
460 
461 	if (flags & CAM_ESF_PROTO_STATUS) {
462 
463 		switch (ccb->ccb_h.func_code) {
464 		case XPT_ATA_IO:
465 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
466 			     CAM_ATA_STATUS_ERROR)
467 				break;
468 			if (proto_flags & CAM_EAF_PRINT_STATUS) {
469 				sbuf_cat(&sb, path_str);
470 				ata_status_sbuf(&ccb->ataio, &sb);
471 				sbuf_printf(&sb, "\n");
472 			}
473 			if (proto_flags & CAM_EAF_PRINT_RESULT) {
474 				sbuf_cat(&sb, path_str);
475 				sbuf_printf(&sb, "RES: ");
476 				ata_res_sbuf(&ccb->ataio.res, &sb);
477 				sbuf_printf(&sb, "\n");
478 			}
479 
480 			break;
481 		case XPT_SCSI_IO:
482 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
483 			     CAM_SCSI_STATUS_ERROR)
484 				break;
485 
486 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
487 				sbuf_cat(&sb, path_str);
488 				sbuf_printf(&sb, "SCSI status: %s\n",
489 					    scsi_status_string(&ccb->csio));
490 			}
491 
492 			if ((proto_flags & CAM_ESF_PRINT_SENSE)
493 			 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
494 			 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)) {
495 
496 #ifdef _KERNEL
497 				scsi_sense_sbuf(&ccb->csio, &sb,
498 						SSS_FLAG_NONE);
499 #else /* !_KERNEL */
500 				scsi_sense_sbuf(device, &ccb->csio, &sb,
501 						SSS_FLAG_NONE);
502 #endif /* _KERNEL/!_KERNEL */
503 			}
504 			break;
505 		case XPT_SMP_IO:
506 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
507 			     CAM_SMP_STATUS_ERROR)
508 				break;
509 
510 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
511 				sbuf_cat(&sb, path_str);
512 				sbuf_printf(&sb, "SMP status: %s (%#x)\n",
513 				    smp_error_desc(ccb->smpio.smp_response[2]),
514 						   ccb->smpio.smp_response[2]);
515 			}
516 			/* There is no SMP equivalent to SCSI sense. */
517 			break;
518 		default:
519 			break;
520 		}
521 	}
522 
523 	sbuf_finish(&sb);
524 
525 	return(sbuf_data(&sb));
526 }
527 
528 #ifdef _KERNEL
529 
530 void
531 cam_error_print(union ccb *ccb, cam_error_string_flags flags,
532 		cam_error_proto_flags proto_flags)
533 {
534 	char str[512];
535 
536 	printf("%s", cam_error_string(ccb, str, sizeof(str), flags,
537 	       proto_flags));
538 }
539 
540 #else /* !_KERNEL */
541 
542 void
543 cam_error_print(struct cam_device *device, union ccb *ccb,
544 		cam_error_string_flags flags, cam_error_proto_flags proto_flags,
545 		FILE *ofile)
546 {
547 	char str[512];
548 
549 	if ((device == NULL) || (ccb == NULL) || (ofile == NULL))
550 		return;
551 
552 	fprintf(ofile, "%s", cam_error_string(device, ccb, str, sizeof(str),
553 		flags, proto_flags));
554 }
555 
556 #endif /* _KERNEL/!_KERNEL */
557 
558 /*
559  * Common calculate geometry fuction
560  *
561  * Caller should set ccg->volume_size and block_size.
562  * The extended parameter should be zero if extended translation
563  * should not be used.
564  */
565 void
566 cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
567 {
568 	uint32_t size_mb, secs_per_cylinder;
569 
570 	if (ccg->block_size == 0) {
571 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
572 		return;
573 	}
574 	size_mb = (1024L * 1024L) / ccg->block_size;
575 	if (size_mb == 0) {
576 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
577 		return;
578 	}
579 	size_mb = ccg->volume_size / size_mb;
580 	if (size_mb > 1024 && extended) {
581 		ccg->heads = 255;
582 		ccg->secs_per_track = 63;
583 	} else {
584 		ccg->heads = 64;
585 		ccg->secs_per_track = 32;
586 	}
587 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
588 	if (secs_per_cylinder == 0) {
589 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
590 		return;
591 	}
592 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
593 	ccg->ccb_h.status = CAM_REQ_CMP;
594 }
595