xref: /freebsd/sys/cam/cam.c (revision 25ecdc7d52770caf1c9b44b5ec11f468f6b636f3)
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 | CTLFLAG_MPSAFE, 0,
112     "CAM Subsystem");
113 
114 #ifndef CAM_DEFAULT_SORT_IO_QUEUES
115 #define CAM_DEFAULT_SORT_IO_QUEUES 1
116 #endif
117 
118 int cam_sort_io_queues = CAM_DEFAULT_SORT_IO_QUEUES;
119 SYSCTL_INT(_kern_cam, OID_AUTO, sort_io_queues, CTLFLAG_RWTUN,
120     &cam_sort_io_queues, 0, "Sort IO queues to try and optimise disk access patterns");
121 #endif
122 
123 void
124 cam_strvis(u_int8_t *dst, const u_int8_t *src, int srclen, int dstlen)
125 {
126 
127 	/* Trim leading/trailing spaces, nulls. */
128 	while (srclen > 0 && src[0] == ' ')
129 		src++, srclen--;
130 	while (srclen > 0
131 	    && (src[srclen-1] == ' ' || src[srclen-1] == '\0'))
132 		srclen--;
133 
134 	while (srclen > 0 && dstlen > 1) {
135 		u_int8_t *cur_pos = dst;
136 
137 		if (*src < 0x20 || *src >= 0x80) {
138 			/* SCSI-II Specifies that these should never occur. */
139 			/* non-printable character */
140 			if (dstlen > 4) {
141 				*cur_pos++ = '\\';
142 				*cur_pos++ = ((*src & 0300) >> 6) + '0';
143 				*cur_pos++ = ((*src & 0070) >> 3) + '0';
144 				*cur_pos++ = ((*src & 0007) >> 0) + '0';
145 			} else {
146 				*cur_pos++ = '?';
147 			}
148 		} else {
149 			/* normal character */
150 			*cur_pos++ = *src;
151 		}
152 		src++;
153 		srclen--;
154 		dstlen -= cur_pos - dst;
155 		dst = cur_pos;
156 	}
157 	*dst = '\0';
158 }
159 
160 void
161 cam_strvis_sbuf(struct sbuf *sb, const u_int8_t *src, int srclen,
162 		uint32_t flags)
163 {
164 
165 	/* Trim leading/trailing spaces, nulls. */
166 	while (srclen > 0 && src[0] == ' ')
167 		src++, srclen--;
168 	while (srclen > 0
169 	    && (src[srclen-1] == ' ' || src[srclen-1] == '\0'))
170 		srclen--;
171 
172 	while (srclen > 0) {
173 		if (*src < 0x20 || *src >= 0x80) {
174 			/* SCSI-II Specifies that these should never occur. */
175 			/* non-printable character */
176 			switch (flags & CAM_STRVIS_FLAG_NONASCII_MASK) {
177 			case CAM_STRVIS_FLAG_NONASCII_ESC:
178 				sbuf_printf(sb, "\\%c%c%c",
179 				    ((*src & 0300) >> 6) + '0',
180 				    ((*src & 0070) >> 3) + '0',
181 				    ((*src & 0007) >> 0) + '0');
182 				break;
183 			case CAM_STRVIS_FLAG_NONASCII_RAW:
184 				/*
185 				 * If we run into a NUL, just transform it
186 				 * into a space.
187 				 */
188 				if (*src != 0x00)
189 					sbuf_putc(sb, *src);
190 				else
191 					sbuf_putc(sb, ' ');
192 				break;
193 			case CAM_STRVIS_FLAG_NONASCII_SPC:
194 				sbuf_putc(sb, ' ');
195 				break;
196 			case CAM_STRVIS_FLAG_NONASCII_TRIM:
197 			default:
198 				break;
199 			}
200 		} else {
201 			/* normal character */
202 			sbuf_putc(sb, *src);
203 		}
204 		src++;
205 		srclen--;
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 #ifdef _KERNEL
333 char *
334 cam_error_string(union ccb *ccb, char *str, int str_len,
335 		 cam_error_string_flags flags,
336 		 cam_error_proto_flags proto_flags)
337 #else /* !_KERNEL */
338 char *
339 cam_error_string(struct cam_device *device, union ccb *ccb, char *str,
340 		 int str_len, cam_error_string_flags flags,
341 		 cam_error_proto_flags proto_flags)
342 #endif /* _KERNEL/!_KERNEL */
343 {
344 	char path_str[64];
345 	struct sbuf sb;
346 
347 	if ((ccb == NULL)
348 	 || (str == NULL)
349 	 || (str_len <= 0))
350 		return(NULL);
351 
352 	if (flags == CAM_ESF_NONE)
353 		return(NULL);
354 
355 	switch (ccb->ccb_h.func_code) {
356 		case XPT_ATA_IO:
357 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
358 			case CAM_EPF_NONE:
359 				break;
360 			case CAM_EPF_ALL:
361 			case CAM_EPF_NORMAL:
362 				proto_flags |= CAM_EAF_PRINT_RESULT;
363 				/* FALLTHROUGH */
364 			case CAM_EPF_MINIMAL:
365 				proto_flags |= CAM_EAF_PRINT_STATUS;
366 				/* FALLTHROUGH */
367 			default:
368 				break;
369 			}
370 			break;
371 		case XPT_SCSI_IO:
372 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
373 			case CAM_EPF_NONE:
374 				break;
375 			case CAM_EPF_ALL:
376 			case CAM_EPF_NORMAL:
377 				proto_flags |= CAM_ESF_PRINT_SENSE;
378 				/* FALLTHROUGH */
379 			case CAM_EPF_MINIMAL:
380 				proto_flags |= CAM_ESF_PRINT_STATUS;
381 				/* FALLTHROUGH */
382 			default:
383 				break;
384 			}
385 			break;
386 		case XPT_SMP_IO:
387 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
388 			case CAM_EPF_NONE:
389 				break;
390 			case CAM_EPF_ALL:
391 				proto_flags |= CAM_ESMF_PRINT_FULL_CMD;
392 				/* FALLTHROUGH */
393 			case CAM_EPF_NORMAL:
394 			case CAM_EPF_MINIMAL:
395 				proto_flags |= CAM_ESMF_PRINT_STATUS;
396 				/* FALLTHROUGH */
397 			default:
398 				break;
399 			}
400 			break;
401 		default:
402 			break;
403 	}
404 #ifdef _KERNEL
405 	xpt_path_string(ccb->csio.ccb_h.path, path_str, sizeof(path_str));
406 #else /* !_KERNEL */
407 	cam_path_string(device, path_str, sizeof(path_str));
408 #endif /* _KERNEL/!_KERNEL */
409 
410 	sbuf_new(&sb, str, str_len, 0);
411 
412 	if (flags & CAM_ESF_COMMAND) {
413 		sbuf_cat(&sb, path_str);
414 		switch (ccb->ccb_h.func_code) {
415 		case XPT_ATA_IO:
416 			ata_command_sbuf(&ccb->ataio, &sb);
417 			break;
418 		case XPT_SCSI_IO:
419 #ifdef _KERNEL
420 			scsi_command_string(&ccb->csio, &sb);
421 #else /* !_KERNEL */
422 			scsi_command_string(device, &ccb->csio, &sb);
423 #endif /* _KERNEL/!_KERNEL */
424 			break;
425 		case XPT_SMP_IO:
426 			smp_command_sbuf(&ccb->smpio, &sb, path_str, 79 -
427 					 strlen(path_str), (proto_flags &
428 					 CAM_ESMF_PRINT_FULL_CMD) ? 79 : 0);
429 			break;
430 		case XPT_NVME_IO:
431 		case XPT_NVME_ADMIN:
432 			nvme_command_sbuf(&ccb->nvmeio, &sb);
433 			break;
434 		default:
435 			sbuf_printf(&sb, "CAM func %#x",
436 			    ccb->ccb_h.func_code);
437 			break;
438 		}
439 		sbuf_printf(&sb, "\n");
440 	}
441 
442 	if (flags & CAM_ESF_CAM_STATUS) {
443 		cam_status status;
444 		const struct cam_status_entry *entry;
445 
446 		sbuf_cat(&sb, path_str);
447 
448 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
449 
450 		entry = cam_fetch_status_entry(status);
451 
452 		if (entry == NULL)
453 			sbuf_printf(&sb, "CAM status: Unknown (%#x)\n",
454 				    ccb->ccb_h.status);
455 		else
456 			sbuf_printf(&sb, "CAM status: %s\n",
457 				    entry->status_text);
458 	}
459 
460 	if (flags & CAM_ESF_PROTO_STATUS) {
461 
462 		switch (ccb->ccb_h.func_code) {
463 		case XPT_ATA_IO:
464 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
465 			     CAM_ATA_STATUS_ERROR)
466 				break;
467 			if (proto_flags & CAM_EAF_PRINT_STATUS) {
468 				sbuf_cat(&sb, path_str);
469 				ata_status_sbuf(&ccb->ataio, &sb);
470 				sbuf_printf(&sb, "\n");
471 			}
472 			if (proto_flags & CAM_EAF_PRINT_RESULT) {
473 				sbuf_cat(&sb, path_str);
474 				sbuf_printf(&sb, "RES: ");
475 				ata_res_sbuf(&ccb->ataio.res, &sb);
476 				sbuf_printf(&sb, "\n");
477 			}
478 
479 			break;
480 		case XPT_SCSI_IO:
481 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
482 			     CAM_SCSI_STATUS_ERROR)
483 				break;
484 
485 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
486 				sbuf_cat(&sb, path_str);
487 				sbuf_printf(&sb, "SCSI status: %s\n",
488 					    scsi_status_string(&ccb->csio));
489 			}
490 
491 			if ((proto_flags & CAM_ESF_PRINT_SENSE)
492 			 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
493 			 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)) {
494 #ifdef _KERNEL
495 				scsi_sense_sbuf(&ccb->csio, &sb,
496 						SSS_FLAG_NONE);
497 #else /* !_KERNEL */
498 				scsi_sense_sbuf(device, &ccb->csio, &sb,
499 						SSS_FLAG_NONE);
500 #endif /* _KERNEL/!_KERNEL */
501 			}
502 			break;
503 		case XPT_SMP_IO:
504 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
505 			     CAM_SMP_STATUS_ERROR)
506 				break;
507 
508 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
509 				sbuf_cat(&sb, path_str);
510 				sbuf_printf(&sb, "SMP status: %s (%#x)\n",
511 				    smp_error_desc(ccb->smpio.smp_response[2]),
512 						   ccb->smpio.smp_response[2]);
513 			}
514 			/* There is no SMP equivalent to SCSI sense. */
515 			break;
516 		default:
517 			break;
518 		}
519 	}
520 
521 	sbuf_finish(&sb);
522 
523 	return(sbuf_data(&sb));
524 }
525 
526 #ifdef _KERNEL
527 
528 void
529 cam_error_print(union ccb *ccb, cam_error_string_flags flags,
530 		cam_error_proto_flags proto_flags)
531 {
532 	char str[512];
533 
534 	printf("%s", cam_error_string(ccb, str, sizeof(str), flags,
535 	       proto_flags));
536 }
537 
538 #else /* !_KERNEL */
539 
540 void
541 cam_error_print(struct cam_device *device, union ccb *ccb,
542 		cam_error_string_flags flags, cam_error_proto_flags proto_flags,
543 		FILE *ofile)
544 {
545 	char str[512];
546 
547 	if ((device == NULL) || (ccb == NULL) || (ofile == NULL))
548 		return;
549 
550 	fprintf(ofile, "%s", cam_error_string(device, ccb, str, sizeof(str),
551 		flags, proto_flags));
552 }
553 
554 #endif /* _KERNEL/!_KERNEL */
555 
556 /*
557  * Common calculate geometry fuction
558  *
559  * Caller should set ccg->volume_size and block_size.
560  * The extended parameter should be zero if extended translation
561  * should not be used.
562  */
563 void
564 cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
565 {
566 	uint32_t size_mb, secs_per_cylinder;
567 
568 	if (ccg->block_size == 0) {
569 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
570 		return;
571 	}
572 	size_mb = (1024L * 1024L) / ccg->block_size;
573 	if (size_mb == 0) {
574 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
575 		return;
576 	}
577 	size_mb = ccg->volume_size / size_mb;
578 	if (size_mb > 1024 && extended) {
579 		ccg->heads = 255;
580 		ccg->secs_per_track = 63;
581 	} else {
582 		ccg->heads = 64;
583 		ccg->secs_per_track = 32;
584 	}
585 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
586 	if (secs_per_cylinder == 0) {
587 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
588 		return;
589 	}
590 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
591 	ccg->ccb_h.status = CAM_REQ_CMP;
592 }
593