xref: /freebsd/sys/cam/cam.c (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
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 const int num_cam_status_entries =
109     sizeof(cam_status_table)/sizeof(*cam_status_table);
110 
111 #ifdef _KERNEL
112 SYSCTL_NODE(_kern, OID_AUTO, cam, CTLFLAG_RD, 0, "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 /*
211  * Compare string with pattern, returning 0 on match.
212  * Short pattern matches trailing blanks in name,
213  * wildcard '*' in pattern matches rest of name,
214  * wildcard '?' matches a single non-space character.
215  */
216 int
217 cam_strmatch(const u_int8_t *str, const u_int8_t *pattern, int str_len)
218 {
219 
220 	while (*pattern != '\0'&& str_len > 0) {
221 
222 		if (*pattern == '*') {
223 			return (0);
224 		}
225 		if ((*pattern != *str)
226 		 && (*pattern != '?' || *str == ' ')) {
227 			return (1);
228 		}
229 		pattern++;
230 		str++;
231 		str_len--;
232 	}
233 	while (str_len > 0 && *str == ' ') {
234 		str++;
235 		str_len--;
236 	}
237 	if (str_len > 0 && *str == 0)
238 		str_len = 0;
239 
240 	return (str_len);
241 }
242 
243 caddr_t
244 cam_quirkmatch(caddr_t target, caddr_t quirk_table, int num_entries,
245 	       int entry_size, cam_quirkmatch_t *comp_func)
246 {
247 	for (; num_entries > 0; num_entries--, quirk_table += entry_size) {
248 		if ((*comp_func)(target, quirk_table) == 0)
249 			return (quirk_table);
250 	}
251 	return (NULL);
252 }
253 
254 const struct cam_status_entry*
255 cam_fetch_status_entry(cam_status status)
256 {
257 	status &= CAM_STATUS_MASK;
258 	return (bsearch(&status, &cam_status_table,
259 			num_cam_status_entries,
260 			sizeof(*cam_status_table),
261 			camstatusentrycomp));
262 }
263 
264 static int
265 camstatusentrycomp(const void *key, const void *member)
266 {
267 	cam_status status;
268 	const struct cam_status_entry *table_entry;
269 
270 	status = *(const cam_status *)key;
271 	table_entry = (const struct cam_status_entry *)member;
272 
273 	return (status - table_entry->status_code);
274 }
275 
276 
277 #ifdef _KERNEL
278 char *
279 cam_error_string(union ccb *ccb, char *str, int str_len,
280 		 cam_error_string_flags flags,
281 		 cam_error_proto_flags proto_flags)
282 #else /* !_KERNEL */
283 char *
284 cam_error_string(struct cam_device *device, union ccb *ccb, char *str,
285 		 int str_len, cam_error_string_flags flags,
286 		 cam_error_proto_flags proto_flags)
287 #endif /* _KERNEL/!_KERNEL */
288 {
289 	char path_str[64];
290 	struct sbuf sb;
291 
292 	if ((ccb == NULL)
293 	 || (str == NULL)
294 	 || (str_len <= 0))
295 		return(NULL);
296 
297 	if (flags == CAM_ESF_NONE)
298 		return(NULL);
299 
300 	switch (ccb->ccb_h.func_code) {
301 		case XPT_ATA_IO:
302 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
303 			case CAM_EPF_NONE:
304 				break;
305 			case CAM_EPF_ALL:
306 			case CAM_EPF_NORMAL:
307 				proto_flags |= CAM_EAF_PRINT_RESULT;
308 				/* FALLTHROUGH */
309 			case CAM_EPF_MINIMAL:
310 				proto_flags |= CAM_EAF_PRINT_STATUS;
311 				/* FALLTHROUGH */
312 			default:
313 				break;
314 			}
315 			break;
316 		case XPT_SCSI_IO:
317 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
318 			case CAM_EPF_NONE:
319 				break;
320 			case CAM_EPF_ALL:
321 			case CAM_EPF_NORMAL:
322 				proto_flags |= CAM_ESF_PRINT_SENSE;
323 				/* FALLTHROUGH */
324 			case CAM_EPF_MINIMAL:
325 				proto_flags |= CAM_ESF_PRINT_STATUS;
326 				/* FALLTHROUGH */
327 			default:
328 				break;
329 			}
330 			break;
331 		case XPT_SMP_IO:
332 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
333 			case CAM_EPF_NONE:
334 				break;
335 			case CAM_EPF_ALL:
336 				proto_flags |= CAM_ESMF_PRINT_FULL_CMD;
337 				/* FALLTHROUGH */
338 			case CAM_EPF_NORMAL:
339 			case CAM_EPF_MINIMAL:
340 				proto_flags |= CAM_ESMF_PRINT_STATUS;
341 				/* FALLTHROUGH */
342 			default:
343 				break;
344 			}
345 			break;
346 		default:
347 			break;
348 	}
349 #ifdef _KERNEL
350 	xpt_path_string(ccb->csio.ccb_h.path, path_str, sizeof(path_str));
351 #else /* !_KERNEL */
352 	cam_path_string(device, path_str, sizeof(path_str));
353 #endif /* _KERNEL/!_KERNEL */
354 
355 	sbuf_new(&sb, str, str_len, 0);
356 
357 	if (flags & CAM_ESF_COMMAND) {
358 		sbuf_cat(&sb, path_str);
359 		switch (ccb->ccb_h.func_code) {
360 		case XPT_ATA_IO:
361 			ata_command_sbuf(&ccb->ataio, &sb);
362 			sbuf_printf(&sb, "\n");
363 			break;
364 		case XPT_SCSI_IO:
365 #ifdef _KERNEL
366 			scsi_command_string(&ccb->csio, &sb);
367 #else /* !_KERNEL */
368 			scsi_command_string(device, &ccb->csio, &sb);
369 #endif /* _KERNEL/!_KERNEL */
370 			sbuf_printf(&sb, "\n");
371 			break;
372 		case XPT_SMP_IO:
373 			smp_command_sbuf(&ccb->smpio, &sb, path_str, 79 -
374 					 strlen(path_str), (proto_flags &
375 					 CAM_ESMF_PRINT_FULL_CMD) ? 79 : 0);
376 			sbuf_printf(&sb, "\n");
377 			break;
378 		default:
379 			break;
380 		}
381 	}
382 
383 	if (flags & CAM_ESF_CAM_STATUS) {
384 		cam_status status;
385 		const struct cam_status_entry *entry;
386 
387 		sbuf_cat(&sb, path_str);
388 
389 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
390 
391 		entry = cam_fetch_status_entry(status);
392 
393 		if (entry == NULL)
394 			sbuf_printf(&sb, "CAM status: Unknown (%#x)\n",
395 				    ccb->ccb_h.status);
396 		else
397 			sbuf_printf(&sb, "CAM status: %s\n",
398 				    entry->status_text);
399 	}
400 
401 	if (flags & CAM_ESF_PROTO_STATUS) {
402 
403 		switch (ccb->ccb_h.func_code) {
404 		case XPT_ATA_IO:
405 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
406 			     CAM_ATA_STATUS_ERROR)
407 				break;
408 			if (proto_flags & CAM_EAF_PRINT_STATUS) {
409 				sbuf_cat(&sb, path_str);
410 				ata_status_sbuf(&ccb->ataio, &sb);
411 				sbuf_printf(&sb, "\n");
412 			}
413 			if (proto_flags & CAM_EAF_PRINT_RESULT) {
414 				sbuf_cat(&sb, path_str);
415 				sbuf_printf(&sb, "RES: ");
416 				ata_res_sbuf(&ccb->ataio.res, &sb);
417 				sbuf_printf(&sb, "\n");
418 			}
419 
420 			break;
421 		case XPT_SCSI_IO:
422 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
423 			     CAM_SCSI_STATUS_ERROR)
424 				break;
425 
426 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
427 				sbuf_cat(&sb, path_str);
428 				sbuf_printf(&sb, "SCSI status: %s\n",
429 					    scsi_status_string(&ccb->csio));
430 			}
431 
432 			if ((proto_flags & CAM_ESF_PRINT_SENSE)
433 			 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
434 			 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)) {
435 
436 #ifdef _KERNEL
437 				scsi_sense_sbuf(&ccb->csio, &sb,
438 						SSS_FLAG_NONE);
439 #else /* !_KERNEL */
440 				scsi_sense_sbuf(device, &ccb->csio, &sb,
441 						SSS_FLAG_NONE);
442 #endif /* _KERNEL/!_KERNEL */
443 			}
444 			break;
445 		case XPT_SMP_IO:
446 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
447 			     CAM_SMP_STATUS_ERROR)
448 				break;
449 
450 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
451 				sbuf_cat(&sb, path_str);
452 				sbuf_printf(&sb, "SMP status: %s (%#x)\n",
453 				    smp_error_desc(ccb->smpio.smp_response[2]),
454 						   ccb->smpio.smp_response[2]);
455 			}
456 			/* There is no SMP equivalent to SCSI sense. */
457 			break;
458 		default:
459 			break;
460 		}
461 	}
462 
463 	sbuf_finish(&sb);
464 
465 	return(sbuf_data(&sb));
466 }
467 
468 #ifdef _KERNEL
469 
470 void
471 cam_error_print(union ccb *ccb, cam_error_string_flags flags,
472 		cam_error_proto_flags proto_flags)
473 {
474 	char str[512];
475 
476 	printf("%s", cam_error_string(ccb, str, sizeof(str), flags,
477 	       proto_flags));
478 }
479 
480 #else /* !_KERNEL */
481 
482 void
483 cam_error_print(struct cam_device *device, union ccb *ccb,
484 		cam_error_string_flags flags, cam_error_proto_flags proto_flags,
485 		FILE *ofile)
486 {
487 	char str[512];
488 
489 	if ((device == NULL) || (ccb == NULL) || (ofile == NULL))
490 		return;
491 
492 	fprintf(ofile, "%s", cam_error_string(device, ccb, str, sizeof(str),
493 		flags, proto_flags));
494 }
495 
496 #endif /* _KERNEL/!_KERNEL */
497 
498 /*
499  * Common calculate geometry fuction
500  *
501  * Caller should set ccg->volume_size and block_size.
502  * The extended parameter should be zero if extended translation
503  * should not be used.
504  */
505 void
506 cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
507 {
508 	uint32_t size_mb, secs_per_cylinder;
509 
510 	if (ccg->block_size == 0) {
511 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
512 		return;
513 	}
514 	size_mb = (1024L * 1024L) / ccg->block_size;
515 	if (size_mb == 0) {
516 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
517 		return;
518 	}
519 	size_mb = ccg->volume_size / size_mb;
520 	if (size_mb > 1024 && extended) {
521 		ccg->heads = 255;
522 		ccg->secs_per_track = 63;
523 	} else {
524 		ccg->heads = 64;
525 		ccg->secs_per_track = 32;
526 	}
527 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
528 	if (secs_per_cylinder == 0) {
529 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
530 		return;
531 	}
532 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
533 	ccg->ccb_h.status = CAM_REQ_CMP;
534 }
535