xref: /freebsd/sys/cam/cam.c (revision cc16dea626cf2fc80cde667ac4798065108e596c)
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 TUNABLE_INT("kern.cam.sort_io_queues", &cam_sort_io_queues);
120 SYSCTL_INT(_kern_cam, OID_AUTO, sort_io_queues, CTLFLAG_RWTUN,
121     &cam_sort_io_queues, 0, "Sort IO queues to try and optimise disk access patterns");
122 #endif
123 
124 void
125 cam_strvis(u_int8_t *dst, const u_int8_t *src, int srclen, int dstlen)
126 {
127 
128 	/* Trim leading/trailing spaces, nulls. */
129 	while (srclen > 0 && src[0] == ' ')
130 		src++, srclen--;
131 	while (srclen > 0
132 	    && (src[srclen-1] == ' ' || src[srclen-1] == '\0'))
133 		srclen--;
134 
135 	while (srclen > 0 && dstlen > 1) {
136 		u_int8_t *cur_pos = dst;
137 
138 		if (*src < 0x20 || *src >= 0x80) {
139 			/* SCSI-II Specifies that these should never occur. */
140 			/* non-printable character */
141 			if (dstlen > 4) {
142 				*cur_pos++ = '\\';
143 				*cur_pos++ = ((*src & 0300) >> 6) + '0';
144 				*cur_pos++ = ((*src & 0070) >> 3) + '0';
145 				*cur_pos++ = ((*src & 0007) >> 0) + '0';
146 			} else {
147 				*cur_pos++ = '?';
148 			}
149 		} else {
150 			/* normal character */
151 			*cur_pos++ = *src;
152 		}
153 		src++;
154 		srclen--;
155 		dstlen -= cur_pos - dst;
156 		dst = cur_pos;
157 	}
158 	*dst = '\0';
159 }
160 
161 /*
162  * Compare string with pattern, returning 0 on match.
163  * Short pattern matches trailing blanks in name,
164  * wildcard '*' in pattern matches rest of name,
165  * wildcard '?' matches a single non-space character.
166  */
167 int
168 cam_strmatch(const u_int8_t *str, const u_int8_t *pattern, int str_len)
169 {
170 
171 	while (*pattern != '\0'&& str_len > 0) {
172 
173 		if (*pattern == '*') {
174 			return (0);
175 		}
176 		if ((*pattern != *str)
177 		 && (*pattern != '?' || *str == ' ')) {
178 			return (1);
179 		}
180 		pattern++;
181 		str++;
182 		str_len--;
183 	}
184 	while (str_len > 0 && *str == ' ') {
185 		str++;
186 		str_len--;
187 	}
188 	if (str_len > 0 && *str == 0)
189 		str_len = 0;
190 
191 	return (str_len);
192 }
193 
194 caddr_t
195 cam_quirkmatch(caddr_t target, caddr_t quirk_table, int num_entries,
196 	       int entry_size, cam_quirkmatch_t *comp_func)
197 {
198 	for (; num_entries > 0; num_entries--, quirk_table += entry_size) {
199 		if ((*comp_func)(target, quirk_table) == 0)
200 			return (quirk_table);
201 	}
202 	return (NULL);
203 }
204 
205 const struct cam_status_entry*
206 cam_fetch_status_entry(cam_status status)
207 {
208 	status &= CAM_STATUS_MASK;
209 	return (bsearch(&status, &cam_status_table,
210 			num_cam_status_entries,
211 			sizeof(*cam_status_table),
212 			camstatusentrycomp));
213 }
214 
215 static int
216 camstatusentrycomp(const void *key, const void *member)
217 {
218 	cam_status status;
219 	const struct cam_status_entry *table_entry;
220 
221 	status = *(const cam_status *)key;
222 	table_entry = (const struct cam_status_entry *)member;
223 
224 	return (status - table_entry->status_code);
225 }
226 
227 
228 #ifdef _KERNEL
229 char *
230 cam_error_string(union ccb *ccb, char *str, int str_len,
231 		 cam_error_string_flags flags,
232 		 cam_error_proto_flags proto_flags)
233 #else /* !_KERNEL */
234 char *
235 cam_error_string(struct cam_device *device, union ccb *ccb, char *str,
236 		 int str_len, cam_error_string_flags flags,
237 		 cam_error_proto_flags proto_flags)
238 #endif /* _KERNEL/!_KERNEL */
239 {
240 	char path_str[64];
241 	struct sbuf sb;
242 
243 	if ((ccb == NULL)
244 	 || (str == NULL)
245 	 || (str_len <= 0))
246 		return(NULL);
247 
248 	if (flags == CAM_ESF_NONE)
249 		return(NULL);
250 
251 	switch (ccb->ccb_h.func_code) {
252 		case XPT_ATA_IO:
253 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
254 			case CAM_EPF_NONE:
255 				break;
256 			case CAM_EPF_ALL:
257 			case CAM_EPF_NORMAL:
258 				proto_flags |= CAM_EAF_PRINT_RESULT;
259 				/* FALLTHROUGH */
260 			case CAM_EPF_MINIMAL:
261 				proto_flags |= CAM_EAF_PRINT_STATUS;
262 				/* FALLTHROUGH */
263 			default:
264 				break;
265 			}
266 			break;
267 		case XPT_SCSI_IO:
268 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
269 			case CAM_EPF_NONE:
270 				break;
271 			case CAM_EPF_ALL:
272 			case CAM_EPF_NORMAL:
273 				proto_flags |= CAM_ESF_PRINT_SENSE;
274 				/* FALLTHROUGH */
275 			case CAM_EPF_MINIMAL:
276 				proto_flags |= CAM_ESF_PRINT_STATUS;
277 				/* FALLTHROUGH */
278 			default:
279 				break;
280 			}
281 			break;
282 		case XPT_SMP_IO:
283 			switch (proto_flags & CAM_EPF_LEVEL_MASK) {
284 			case CAM_EPF_NONE:
285 				break;
286 			case CAM_EPF_ALL:
287 				proto_flags |= CAM_ESMF_PRINT_FULL_CMD;
288 				/* FALLTHROUGH */
289 			case CAM_EPF_NORMAL:
290 			case CAM_EPF_MINIMAL:
291 				proto_flags |= CAM_ESMF_PRINT_STATUS;
292 				/* FALLTHROUGH */
293 			default:
294 				break;
295 			}
296 			break;
297 		default:
298 			break;
299 	}
300 #ifdef _KERNEL
301 	xpt_path_string(ccb->csio.ccb_h.path, path_str, sizeof(path_str));
302 #else /* !_KERNEL */
303 	cam_path_string(device, path_str, sizeof(path_str));
304 #endif /* _KERNEL/!_KERNEL */
305 
306 	sbuf_new(&sb, str, str_len, 0);
307 
308 	if (flags & CAM_ESF_COMMAND) {
309 		sbuf_cat(&sb, path_str);
310 		switch (ccb->ccb_h.func_code) {
311 		case XPT_ATA_IO:
312 			ata_command_sbuf(&ccb->ataio, &sb);
313 			sbuf_printf(&sb, "\n");
314 			break;
315 		case XPT_SCSI_IO:
316 #ifdef _KERNEL
317 			scsi_command_string(&ccb->csio, &sb);
318 #else /* !_KERNEL */
319 			scsi_command_string(device, &ccb->csio, &sb);
320 #endif /* _KERNEL/!_KERNEL */
321 			sbuf_printf(&sb, "\n");
322 			break;
323 		case XPT_SMP_IO:
324 			smp_command_sbuf(&ccb->smpio, &sb, path_str, 79 -
325 					 strlen(path_str), (proto_flags &
326 					 CAM_ESMF_PRINT_FULL_CMD) ? 79 : 0);
327 			sbuf_printf(&sb, "\n");
328 			break;
329 		default:
330 			break;
331 		}
332 	}
333 
334 	if (flags & CAM_ESF_CAM_STATUS) {
335 		cam_status status;
336 		const struct cam_status_entry *entry;
337 
338 		sbuf_cat(&sb, path_str);
339 
340 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
341 
342 		entry = cam_fetch_status_entry(status);
343 
344 		if (entry == NULL)
345 			sbuf_printf(&sb, "CAM status: Unknown (%#x)\n",
346 				    ccb->ccb_h.status);
347 		else
348 			sbuf_printf(&sb, "CAM status: %s\n",
349 				    entry->status_text);
350 	}
351 
352 	if (flags & CAM_ESF_PROTO_STATUS) {
353 
354 		switch (ccb->ccb_h.func_code) {
355 		case XPT_ATA_IO:
356 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
357 			     CAM_ATA_STATUS_ERROR)
358 				break;
359 			if (proto_flags & CAM_EAF_PRINT_STATUS) {
360 				sbuf_cat(&sb, path_str);
361 				ata_status_sbuf(&ccb->ataio, &sb);
362 				sbuf_printf(&sb, "\n");
363 			}
364 			if (proto_flags & CAM_EAF_PRINT_RESULT) {
365 				sbuf_cat(&sb, path_str);
366 				ata_res_sbuf(&ccb->ataio, &sb);
367 				sbuf_printf(&sb, "\n");
368 			}
369 
370 			break;
371 		case XPT_SCSI_IO:
372 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
373 			     CAM_SCSI_STATUS_ERROR)
374 				break;
375 
376 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
377 				sbuf_cat(&sb, path_str);
378 				sbuf_printf(&sb, "SCSI status: %s\n",
379 					    scsi_status_string(&ccb->csio));
380 			}
381 
382 			if ((proto_flags & CAM_ESF_PRINT_SENSE)
383 			 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
384 			 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)) {
385 
386 #ifdef _KERNEL
387 				scsi_sense_sbuf(&ccb->csio, &sb,
388 						SSS_FLAG_NONE);
389 #else /* !_KERNEL */
390 				scsi_sense_sbuf(device, &ccb->csio, &sb,
391 						SSS_FLAG_NONE);
392 #endif /* _KERNEL/!_KERNEL */
393 			}
394 			break;
395 		case XPT_SMP_IO:
396 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
397 			     CAM_SMP_STATUS_ERROR)
398 				break;
399 
400 			if (proto_flags & CAM_ESF_PRINT_STATUS) {
401 				sbuf_cat(&sb, path_str);
402 				sbuf_printf(&sb, "SMP status: %s (%#x)\n",
403 				    smp_error_desc(ccb->smpio.smp_response[2]),
404 						   ccb->smpio.smp_response[2]);
405 			}
406 			/* There is no SMP equivalent to SCSI sense. */
407 			break;
408 		default:
409 			break;
410 		}
411 	}
412 
413 	sbuf_finish(&sb);
414 
415 	return(sbuf_data(&sb));
416 }
417 
418 #ifdef _KERNEL
419 
420 void
421 cam_error_print(union ccb *ccb, cam_error_string_flags flags,
422 		cam_error_proto_flags proto_flags)
423 {
424 	char str[512];
425 
426 	printf("%s", cam_error_string(ccb, str, sizeof(str), flags,
427 	       proto_flags));
428 }
429 
430 #else /* !_KERNEL */
431 
432 void
433 cam_error_print(struct cam_device *device, union ccb *ccb,
434 		cam_error_string_flags flags, cam_error_proto_flags proto_flags,
435 		FILE *ofile)
436 {
437 	char str[512];
438 
439 	if ((device == NULL) || (ccb == NULL) || (ofile == NULL))
440 		return;
441 
442 	fprintf(ofile, "%s", cam_error_string(device, ccb, str, sizeof(str),
443 		flags, proto_flags));
444 }
445 
446 #endif /* _KERNEL/!_KERNEL */
447 
448 /*
449  * Common calculate geometry fuction
450  *
451  * Caller should set ccg->volume_size and block_size.
452  * The extended parameter should be zero if extended translation
453  * should not be used.
454  */
455 void
456 cam_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
457 {
458 	uint32_t size_mb, secs_per_cylinder;
459 
460 	if (ccg->block_size == 0) {
461 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
462 		return;
463 	}
464 	size_mb = (1024L * 1024L) / ccg->block_size;
465 	if (size_mb == 0) {
466 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
467 		return;
468 	}
469 	size_mb = ccg->volume_size / size_mb;
470 	if (size_mb > 1024 && extended) {
471 		ccg->heads = 255;
472 		ccg->secs_per_track = 63;
473 	} else {
474 		ccg->heads = 64;
475 		ccg->secs_per_track = 32;
476 	}
477 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
478 	if (secs_per_cylinder == 0) {
479 		ccg->ccb_h.status = CAM_REQ_CMP_ERR;
480 		return;
481 	}
482 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
483 	ccg->ccb_h.status = CAM_REQ_CMP;
484 }
485