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