1 /*-
2 * Common functions for CAM "type" (peripheral) drivers.
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 *
6 * Copyright (c) 1997, 1998 Justin T. Gibbs.
7 * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions, and the following disclaimer,
15 * without modification, immediately at the beginning of the file.
16 * 2. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/types.h>
36 #include <sys/malloc.h>
37 #include <sys/kernel.h>
38 #include <sys/bio.h>
39 #include <sys/conf.h>
40 #include <sys/devctl.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/buf.h>
44 #include <sys/proc.h>
45 #include <sys/devicestat.h>
46 #include <sys/sbuf.h>
47 #include <sys/sysctl.h>
48 #include <vm/vm.h>
49 #include <vm/vm_extern.h>
50
51 #include <cam/cam.h>
52 #include <cam/cam_ccb.h>
53 #include <cam/cam_compat.h>
54 #include <cam/cam_queue.h>
55 #include <cam/cam_xpt_periph.h>
56 #include <cam/cam_xpt_internal.h>
57 #include <cam/cam_periph.h>
58 #include <cam/cam_debug.h>
59 #include <cam/cam_sim.h>
60
61 #include <cam/scsi/scsi_all.h>
62 #include <cam/scsi/scsi_message.h>
63 #include <cam/scsi/scsi_pass.h>
64
65 static u_int camperiphnextunit(struct periph_driver *p_drv,
66 u_int newunit, int wired,
67 path_id_t pathid, target_id_t target,
68 lun_id_t lun);
69 static u_int camperiphunit(struct periph_driver *p_drv,
70 path_id_t pathid, target_id_t target,
71 lun_id_t lun);
72 static void camperiphdone(struct cam_periph *periph,
73 union ccb *done_ccb);
74 static void camperiphfree(struct cam_periph *periph);
75 static int camperiphscsistatuserror(union ccb *ccb,
76 union ccb **orig_ccb,
77 cam_flags camflags,
78 u_int32_t sense_flags,
79 int *openings,
80 u_int32_t *relsim_flags,
81 u_int32_t *timeout,
82 u_int32_t *action,
83 const char **action_string);
84 static int camperiphscsisenseerror(union ccb *ccb,
85 union ccb **orig_ccb,
86 cam_flags camflags,
87 u_int32_t sense_flags,
88 int *openings,
89 u_int32_t *relsim_flags,
90 u_int32_t *timeout,
91 u_int32_t *action,
92 const char **action_string);
93 static void cam_periph_devctl_notify(union ccb *ccb);
94
95 static int nperiph_drivers;
96 static int initialized = 0;
97 struct periph_driver **periph_drivers;
98
99 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
100
101 static int periph_selto_delay = 1000;
102 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
103 static int periph_noresrc_delay = 500;
104 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
105 static int periph_busy_delay = 500;
106 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
107
108 static u_int periph_mapmem_thresh = 65536;
109 SYSCTL_UINT(_kern_cam, OID_AUTO, mapmem_thresh, CTLFLAG_RWTUN,
110 &periph_mapmem_thresh, 0, "Threshold for user-space buffer mapping");
111
112 void
periphdriver_register(void * data)113 periphdriver_register(void *data)
114 {
115 struct periph_driver *drv = (struct periph_driver *)data;
116 struct periph_driver **newdrivers, **old;
117 int ndrivers;
118
119 again:
120 ndrivers = nperiph_drivers + 2;
121 newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
122 M_WAITOK);
123 xpt_lock_buses();
124 if (ndrivers != nperiph_drivers + 2) {
125 /*
126 * Lost race against itself; go around.
127 */
128 xpt_unlock_buses();
129 free(newdrivers, M_CAMPERIPH);
130 goto again;
131 }
132 if (periph_drivers)
133 bcopy(periph_drivers, newdrivers,
134 sizeof(*newdrivers) * nperiph_drivers);
135 newdrivers[nperiph_drivers] = drv;
136 newdrivers[nperiph_drivers + 1] = NULL;
137 old = periph_drivers;
138 periph_drivers = newdrivers;
139 nperiph_drivers++;
140 xpt_unlock_buses();
141 if (old)
142 free(old, M_CAMPERIPH);
143 /* If driver marked as early or it is late now, initialize it. */
144 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
145 initialized > 1)
146 (*drv->init)();
147 }
148
149 int
periphdriver_unregister(void * data)150 periphdriver_unregister(void *data)
151 {
152 struct periph_driver *drv = (struct periph_driver *)data;
153 int error, n;
154
155 /* If driver marked as early or it is late now, deinitialize it. */
156 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
157 initialized > 1) {
158 if (drv->deinit == NULL) {
159 printf("CAM periph driver '%s' doesn't have deinit.\n",
160 drv->driver_name);
161 return (EOPNOTSUPP);
162 }
163 error = drv->deinit();
164 if (error != 0)
165 return (error);
166 }
167
168 xpt_lock_buses();
169 for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
170 ;
171 KASSERT(n < nperiph_drivers,
172 ("Periph driver '%s' was not registered", drv->driver_name));
173 for (; n + 1 < nperiph_drivers; n++)
174 periph_drivers[n] = periph_drivers[n + 1];
175 periph_drivers[n + 1] = NULL;
176 nperiph_drivers--;
177 xpt_unlock_buses();
178 return (0);
179 }
180
181 void
periphdriver_init(int level)182 periphdriver_init(int level)
183 {
184 int i, early;
185
186 initialized = max(initialized, level);
187 for (i = 0; periph_drivers[i] != NULL; i++) {
188 early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
189 if (early == initialized)
190 (*periph_drivers[i]->init)();
191 }
192 }
193
194 cam_status
cam_periph_alloc(periph_ctor_t * periph_ctor,periph_oninv_t * periph_oninvalidate,periph_dtor_t * periph_dtor,periph_start_t * periph_start,char * name,cam_periph_type type,struct cam_path * path,ac_callback_t * ac_callback,ac_code code,void * arg)195 cam_periph_alloc(periph_ctor_t *periph_ctor,
196 periph_oninv_t *periph_oninvalidate,
197 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
198 char *name, cam_periph_type type, struct cam_path *path,
199 ac_callback_t *ac_callback, ac_code code, void *arg)
200 {
201 struct periph_driver **p_drv;
202 struct cam_sim *sim;
203 struct cam_periph *periph;
204 struct cam_periph *cur_periph;
205 path_id_t path_id;
206 target_id_t target_id;
207 lun_id_t lun_id;
208 cam_status status;
209 u_int init_level;
210
211 init_level = 0;
212 /*
213 * Handle Hot-Plug scenarios. If there is already a peripheral
214 * of our type assigned to this path, we are likely waiting for
215 * final close on an old, invalidated, peripheral. If this is
216 * the case, queue up a deferred call to the peripheral's async
217 * handler. If it looks like a mistaken re-allocation, complain.
218 */
219 if ((periph = cam_periph_find(path, name)) != NULL) {
220 if ((periph->flags & CAM_PERIPH_INVALID) != 0
221 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
222 periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
223 periph->deferred_callback = ac_callback;
224 periph->deferred_ac = code;
225 return (CAM_REQ_INPROG);
226 } else {
227 printf("cam_periph_alloc: attempt to re-allocate "
228 "valid device %s%d rejected flags %#x "
229 "refcount %d\n", periph->periph_name,
230 periph->unit_number, periph->flags,
231 periph->refcount);
232 }
233 return (CAM_REQ_INVALID);
234 }
235
236 periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
237 M_NOWAIT|M_ZERO);
238
239 if (periph == NULL)
240 return (CAM_RESRC_UNAVAIL);
241
242 init_level++;
243
244 sim = xpt_path_sim(path);
245 path_id = xpt_path_path_id(path);
246 target_id = xpt_path_target_id(path);
247 lun_id = xpt_path_lun_id(path);
248 periph->periph_start = periph_start;
249 periph->periph_dtor = periph_dtor;
250 periph->periph_oninval = periph_oninvalidate;
251 periph->type = type;
252 periph->periph_name = name;
253 periph->scheduled_priority = CAM_PRIORITY_NONE;
254 periph->immediate_priority = CAM_PRIORITY_NONE;
255 periph->refcount = 1; /* Dropped by invalidation. */
256 periph->sim = sim;
257 SLIST_INIT(&periph->ccb_list);
258 status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
259 if (status != CAM_REQ_CMP)
260 goto failure;
261 periph->path = path;
262
263 xpt_lock_buses();
264 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
265 if (strcmp((*p_drv)->driver_name, name) == 0)
266 break;
267 }
268 if (*p_drv == NULL) {
269 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
270 xpt_unlock_buses();
271 xpt_free_path(periph->path);
272 free(periph, M_CAMPERIPH);
273 return (CAM_REQ_INVALID);
274 }
275 periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
276 cur_periph = TAILQ_FIRST(&(*p_drv)->units);
277 while (cur_periph != NULL
278 && cur_periph->unit_number < periph->unit_number)
279 cur_periph = TAILQ_NEXT(cur_periph, unit_links);
280 if (cur_periph != NULL) {
281 KASSERT(cur_periph->unit_number != periph->unit_number,
282 ("duplicate units on periph list"));
283 TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
284 } else {
285 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
286 (*p_drv)->generation++;
287 }
288 xpt_unlock_buses();
289
290 init_level++;
291
292 status = xpt_add_periph(periph);
293 if (status != CAM_REQ_CMP)
294 goto failure;
295
296 init_level++;
297 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
298
299 status = periph_ctor(periph, arg);
300
301 if (status == CAM_REQ_CMP)
302 init_level++;
303
304 failure:
305 switch (init_level) {
306 case 4:
307 /* Initialized successfully */
308 break;
309 case 3:
310 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
311 xpt_remove_periph(periph);
312 /* FALLTHROUGH */
313 case 2:
314 xpt_lock_buses();
315 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
316 xpt_unlock_buses();
317 xpt_free_path(periph->path);
318 /* FALLTHROUGH */
319 case 1:
320 free(periph, M_CAMPERIPH);
321 /* FALLTHROUGH */
322 case 0:
323 /* No cleanup to perform. */
324 break;
325 default:
326 panic("%s: Unknown init level", __func__);
327 }
328 return(status);
329 }
330
331 /*
332 * Find a peripheral structure with the specified path, target, lun,
333 * and (optionally) type. If the name is NULL, this function will return
334 * the first peripheral driver that matches the specified path.
335 */
336 struct cam_periph *
cam_periph_find(struct cam_path * path,char * name)337 cam_periph_find(struct cam_path *path, char *name)
338 {
339 struct periph_driver **p_drv;
340 struct cam_periph *periph;
341
342 xpt_lock_buses();
343 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
344 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
345 continue;
346
347 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
348 if (xpt_path_comp(periph->path, path) == 0) {
349 xpt_unlock_buses();
350 cam_periph_assert(periph, MA_OWNED);
351 return(periph);
352 }
353 }
354 if (name != NULL) {
355 xpt_unlock_buses();
356 return(NULL);
357 }
358 }
359 xpt_unlock_buses();
360 return(NULL);
361 }
362
363 /*
364 * Find peripheral driver instances attached to the specified path.
365 */
366 int
cam_periph_list(struct cam_path * path,struct sbuf * sb)367 cam_periph_list(struct cam_path *path, struct sbuf *sb)
368 {
369 struct sbuf local_sb;
370 struct periph_driver **p_drv;
371 struct cam_periph *periph;
372 int count;
373 int sbuf_alloc_len;
374
375 sbuf_alloc_len = 16;
376 retry:
377 sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
378 count = 0;
379 xpt_lock_buses();
380 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
381 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
382 if (xpt_path_comp(periph->path, path) != 0)
383 continue;
384
385 if (sbuf_len(&local_sb) != 0)
386 sbuf_cat(&local_sb, ",");
387
388 sbuf_printf(&local_sb, "%s%d", periph->periph_name,
389 periph->unit_number);
390
391 if (sbuf_error(&local_sb) == ENOMEM) {
392 sbuf_alloc_len *= 2;
393 xpt_unlock_buses();
394 sbuf_delete(&local_sb);
395 goto retry;
396 }
397 count++;
398 }
399 }
400 xpt_unlock_buses();
401 sbuf_finish(&local_sb);
402 if (sbuf_len(sb) != 0)
403 sbuf_cat(sb, ",");
404 sbuf_cat(sb, sbuf_data(&local_sb));
405 sbuf_delete(&local_sb);
406 return (count);
407 }
408
409 int
cam_periph_acquire(struct cam_periph * periph)410 cam_periph_acquire(struct cam_periph *periph)
411 {
412 int status;
413
414 if (periph == NULL)
415 return (EINVAL);
416
417 status = ENOENT;
418 xpt_lock_buses();
419 if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
420 periph->refcount++;
421 status = 0;
422 }
423 xpt_unlock_buses();
424
425 return (status);
426 }
427
428 void
cam_periph_doacquire(struct cam_periph * periph)429 cam_periph_doacquire(struct cam_periph *periph)
430 {
431
432 xpt_lock_buses();
433 KASSERT(periph->refcount >= 1,
434 ("cam_periph_doacquire() with refcount == %d", periph->refcount));
435 periph->refcount++;
436 xpt_unlock_buses();
437 }
438
439 void
cam_periph_release_locked_buses(struct cam_periph * periph)440 cam_periph_release_locked_buses(struct cam_periph *periph)
441 {
442
443 cam_periph_assert(periph, MA_OWNED);
444 KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
445 if (--periph->refcount == 0)
446 camperiphfree(periph);
447 }
448
449 void
cam_periph_release_locked(struct cam_periph * periph)450 cam_periph_release_locked(struct cam_periph *periph)
451 {
452
453 if (periph == NULL)
454 return;
455
456 xpt_lock_buses();
457 cam_periph_release_locked_buses(periph);
458 xpt_unlock_buses();
459 }
460
461 void
cam_periph_release(struct cam_periph * periph)462 cam_periph_release(struct cam_periph *periph)
463 {
464 struct mtx *mtx;
465
466 if (periph == NULL)
467 return;
468
469 cam_periph_assert(periph, MA_NOTOWNED);
470 mtx = cam_periph_mtx(periph);
471 mtx_lock(mtx);
472 cam_periph_release_locked(periph);
473 mtx_unlock(mtx);
474 }
475
476 /*
477 * hold/unhold act as mutual exclusion for sections of the code that
478 * need to sleep and want to make sure that other sections that
479 * will interfere are held off. This only protects exclusive sections
480 * from each other.
481 */
482 int
cam_periph_hold(struct cam_periph * periph,int priority)483 cam_periph_hold(struct cam_periph *periph, int priority)
484 {
485 int error;
486
487 /*
488 * Increment the reference count on the peripheral
489 * while we wait for our lock attempt to succeed
490 * to ensure the peripheral doesn't disappear out
491 * from user us while we sleep.
492 */
493
494 if (cam_periph_acquire(periph) != 0)
495 return (ENXIO);
496
497 cam_periph_assert(periph, MA_OWNED);
498 while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
499 periph->flags |= CAM_PERIPH_LOCK_WANTED;
500 if ((error = cam_periph_sleep(periph, periph, priority,
501 "caplck", 0)) != 0) {
502 cam_periph_release_locked(periph);
503 return (error);
504 }
505 if (periph->flags & CAM_PERIPH_INVALID) {
506 cam_periph_release_locked(periph);
507 return (ENXIO);
508 }
509 }
510
511 periph->flags |= CAM_PERIPH_LOCKED;
512 return (0);
513 }
514
515 void
cam_periph_unhold(struct cam_periph * periph)516 cam_periph_unhold(struct cam_periph *periph)
517 {
518
519 cam_periph_assert(periph, MA_OWNED);
520
521 periph->flags &= ~CAM_PERIPH_LOCKED;
522 if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
523 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
524 wakeup(periph);
525 }
526
527 cam_periph_release_locked(periph);
528 }
529
530 void
cam_periph_hold_boot(struct cam_periph * periph)531 cam_periph_hold_boot(struct cam_periph *periph)
532 {
533
534 root_mount_hold_token(periph->periph_name, &periph->periph_rootmount);
535 }
536
537 void
cam_periph_release_boot(struct cam_periph * periph)538 cam_periph_release_boot(struct cam_periph *periph)
539 {
540
541 root_mount_rel(&periph->periph_rootmount);
542 }
543
544 /*
545 * Look for the next unit number that is not currently in use for this
546 * peripheral type starting at "newunit". Also exclude unit numbers that
547 * are reserved by for future "hardwiring" unless we already know that this
548 * is a potential wired device. Only assume that the device is "wired" the
549 * first time through the loop since after that we'll be looking at unit
550 * numbers that did not match a wiring entry.
551 */
552 static u_int
camperiphnextunit(struct periph_driver * p_drv,u_int newunit,int wired,path_id_t pathid,target_id_t target,lun_id_t lun)553 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
554 path_id_t pathid, target_id_t target, lun_id_t lun)
555 {
556 struct cam_periph *periph;
557 char *periph_name;
558 int i, val, dunit, r;
559 const char *dname, *strval;
560
561 periph_name = p_drv->driver_name;
562 for (;;newunit++) {
563 for (periph = TAILQ_FIRST(&p_drv->units);
564 periph != NULL && periph->unit_number != newunit;
565 periph = TAILQ_NEXT(periph, unit_links))
566 ;
567
568 if (periph != NULL && periph->unit_number == newunit) {
569 if (wired != 0) {
570 xpt_print(periph->path, "Duplicate Wired "
571 "Device entry!\n");
572 xpt_print(periph->path, "Second device (%s "
573 "device at scbus%d target %d lun %d) will "
574 "not be wired\n", periph_name, pathid,
575 target, lun);
576 wired = 0;
577 }
578 continue;
579 }
580 if (wired)
581 break;
582
583 /*
584 * Don't match entries like "da 4" as a wired down
585 * device, but do match entries like "da 4 target 5"
586 * or even "da 4 scbus 1".
587 */
588 i = 0;
589 dname = periph_name;
590 for (;;) {
591 r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
592 if (r != 0)
593 break;
594 /* if no "target" and no specific scbus, skip */
595 if (resource_int_value(dname, dunit, "target", &val) &&
596 (resource_string_value(dname, dunit, "at",&strval)||
597 strcmp(strval, "scbus") == 0))
598 continue;
599 if (newunit == dunit)
600 break;
601 }
602 if (r != 0)
603 break;
604 }
605 return (newunit);
606 }
607
608 static u_int
camperiphunit(struct periph_driver * p_drv,path_id_t pathid,target_id_t target,lun_id_t lun)609 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
610 target_id_t target, lun_id_t lun)
611 {
612 u_int unit;
613 int wired, i, val, dunit;
614 const char *dname, *strval;
615 char pathbuf[32], *periph_name;
616
617 periph_name = p_drv->driver_name;
618 snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
619 unit = 0;
620 i = 0;
621 dname = periph_name;
622 for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
623 wired = 0) {
624 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
625 if (strcmp(strval, pathbuf) != 0)
626 continue;
627 wired++;
628 }
629 if (resource_int_value(dname, dunit, "target", &val) == 0) {
630 if (val != target)
631 continue;
632 wired++;
633 }
634 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
635 if (val != lun)
636 continue;
637 wired++;
638 }
639 if (wired != 0) {
640 unit = dunit;
641 break;
642 }
643 }
644
645 /*
646 * Either start from 0 looking for the next unit or from
647 * the unit number given in the resource config. This way,
648 * if we have wildcard matches, we don't return the same
649 * unit number twice.
650 */
651 unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
652
653 return (unit);
654 }
655
656 void
cam_periph_invalidate(struct cam_periph * periph)657 cam_periph_invalidate(struct cam_periph *periph)
658 {
659
660 cam_periph_assert(periph, MA_OWNED);
661 /*
662 * We only tear down the device the first time a peripheral is
663 * invalidated.
664 */
665 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
666 return;
667
668 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
669 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
670 struct sbuf sb;
671 char buffer[160];
672
673 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
674 xpt_denounce_periph_sbuf(periph, &sb);
675 sbuf_finish(&sb);
676 sbuf_putbuf(&sb);
677 }
678 periph->flags |= CAM_PERIPH_INVALID;
679 periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
680 if (periph->periph_oninval != NULL)
681 periph->periph_oninval(periph);
682 cam_periph_release_locked(periph);
683 }
684
685 static void
camperiphfree(struct cam_periph * periph)686 camperiphfree(struct cam_periph *periph)
687 {
688 struct periph_driver **p_drv;
689 struct periph_driver *drv;
690
691 cam_periph_assert(periph, MA_OWNED);
692 KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
693 periph->periph_name, periph->unit_number));
694 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
695 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
696 break;
697 }
698 if (*p_drv == NULL) {
699 printf("camperiphfree: attempt to free non-existant periph\n");
700 return;
701 }
702 /*
703 * Cache a pointer to the periph_driver structure. If a
704 * periph_driver is added or removed from the array (see
705 * periphdriver_register()) while we drop the toplogy lock
706 * below, p_drv may change. This doesn't protect against this
707 * particular periph_driver going away. That will require full
708 * reference counting in the periph_driver infrastructure.
709 */
710 drv = *p_drv;
711
712 /*
713 * We need to set this flag before dropping the topology lock, to
714 * let anyone who is traversing the list that this peripheral is
715 * about to be freed, and there will be no more reference count
716 * checks.
717 */
718 periph->flags |= CAM_PERIPH_FREE;
719
720 /*
721 * The peripheral destructor semantics dictate calling with only the
722 * SIM mutex held. Since it might sleep, it should not be called
723 * with the topology lock held.
724 */
725 xpt_unlock_buses();
726
727 /*
728 * We need to call the peripheral destructor prior to removing the
729 * peripheral from the list. Otherwise, we risk running into a
730 * scenario where the peripheral unit number may get reused
731 * (because it has been removed from the list), but some resources
732 * used by the peripheral are still hanging around. In particular,
733 * the devfs nodes used by some peripherals like the pass(4) driver
734 * aren't fully cleaned up until the destructor is run. If the
735 * unit number is reused before the devfs instance is fully gone,
736 * devfs will panic.
737 */
738 if (periph->periph_dtor != NULL)
739 periph->periph_dtor(periph);
740
741 /*
742 * The peripheral list is protected by the topology lock. We have to
743 * remove the periph from the drv list before we call deferred_ac. The
744 * AC_FOUND_DEVICE callback won't create a new periph if it's still there.
745 */
746 xpt_lock_buses();
747
748 TAILQ_REMOVE(&drv->units, periph, unit_links);
749 drv->generation++;
750
751 xpt_remove_periph(periph);
752
753 xpt_unlock_buses();
754 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
755 xpt_print(periph->path, "Periph destroyed\n");
756 else
757 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
758
759 if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
760 union ccb ccb;
761 void *arg;
762
763 memset(&ccb, 0, sizeof(ccb));
764 switch (periph->deferred_ac) {
765 case AC_FOUND_DEVICE:
766 ccb.ccb_h.func_code = XPT_GDEV_TYPE;
767 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
768 xpt_action(&ccb);
769 arg = &ccb;
770 break;
771 case AC_PATH_REGISTERED:
772 xpt_path_inq(&ccb.cpi, periph->path);
773 arg = &ccb;
774 break;
775 default:
776 arg = NULL;
777 break;
778 }
779 periph->deferred_callback(NULL, periph->deferred_ac,
780 periph->path, arg);
781 }
782 xpt_free_path(periph->path);
783 free(periph, M_CAMPERIPH);
784 xpt_lock_buses();
785 }
786
787 /*
788 * Map user virtual pointers into kernel virtual address space, so we can
789 * access the memory. This is now a generic function that centralizes most
790 * of the sanity checks on the data flags, if any.
791 * This also only works for up to maxphys memory. Since we use
792 * buffers to map stuff in and out, we're limited to the buffer size.
793 */
794 int
cam_periph_mapmem(union ccb * ccb,struct cam_periph_map_info * mapinfo,u_int maxmap)795 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
796 u_int maxmap)
797 {
798 int numbufs, i;
799 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
800 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
801 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
802
803 bzero(mapinfo, sizeof(*mapinfo));
804 if (maxmap == 0)
805 maxmap = DFLTPHYS; /* traditional default */
806 else if (maxmap > maxphys)
807 maxmap = maxphys; /* for safety */
808 switch(ccb->ccb_h.func_code) {
809 case XPT_DEV_MATCH:
810 if (ccb->cdm.match_buf_len == 0) {
811 printf("cam_periph_mapmem: invalid match buffer "
812 "length 0\n");
813 return(EINVAL);
814 }
815 if (ccb->cdm.pattern_buf_len > 0) {
816 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
817 lengths[0] = ccb->cdm.pattern_buf_len;
818 dirs[0] = CAM_DIR_OUT;
819 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
820 lengths[1] = ccb->cdm.match_buf_len;
821 dirs[1] = CAM_DIR_IN;
822 numbufs = 2;
823 } else {
824 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
825 lengths[0] = ccb->cdm.match_buf_len;
826 dirs[0] = CAM_DIR_IN;
827 numbufs = 1;
828 }
829 /*
830 * This request will not go to the hardware, no reason
831 * to be so strict. vmapbuf() is able to map up to maxphys.
832 */
833 maxmap = maxphys;
834 break;
835 case XPT_SCSI_IO:
836 case XPT_CONT_TARGET_IO:
837 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
838 return(0);
839 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
840 return (EINVAL);
841 data_ptrs[0] = &ccb->csio.data_ptr;
842 lengths[0] = ccb->csio.dxfer_len;
843 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
844 numbufs = 1;
845 break;
846 case XPT_ATA_IO:
847 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
848 return(0);
849 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
850 return (EINVAL);
851 data_ptrs[0] = &ccb->ataio.data_ptr;
852 lengths[0] = ccb->ataio.dxfer_len;
853 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
854 numbufs = 1;
855 break;
856 case XPT_MMC_IO:
857 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
858 return(0);
859 /* Two mappings: one for cmd->data and one for cmd->data->data */
860 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
861 lengths[0] = sizeof(struct mmc_data *);
862 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
863 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
864 lengths[1] = ccb->mmcio.cmd.data->len;
865 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
866 numbufs = 2;
867 break;
868 case XPT_SMP_IO:
869 data_ptrs[0] = &ccb->smpio.smp_request;
870 lengths[0] = ccb->smpio.smp_request_len;
871 dirs[0] = CAM_DIR_OUT;
872 data_ptrs[1] = &ccb->smpio.smp_response;
873 lengths[1] = ccb->smpio.smp_response_len;
874 dirs[1] = CAM_DIR_IN;
875 numbufs = 2;
876 break;
877 case XPT_NVME_IO:
878 case XPT_NVME_ADMIN:
879 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
880 return (0);
881 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
882 return (EINVAL);
883 data_ptrs[0] = &ccb->nvmeio.data_ptr;
884 lengths[0] = ccb->nvmeio.dxfer_len;
885 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
886 numbufs = 1;
887 break;
888 case XPT_DEV_ADVINFO:
889 if (ccb->cdai.bufsiz == 0)
890 return (0);
891
892 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
893 lengths[0] = ccb->cdai.bufsiz;
894 dirs[0] = CAM_DIR_IN;
895 numbufs = 1;
896
897 /*
898 * This request will not go to the hardware, no reason
899 * to be so strict. vmapbuf() is able to map up to maxphys.
900 */
901 maxmap = maxphys;
902 break;
903 default:
904 return(EINVAL);
905 break; /* NOTREACHED */
906 }
907
908 /*
909 * Check the transfer length and permissions first, so we don't
910 * have to unmap any previously mapped buffers.
911 */
912 for (i = 0; i < numbufs; i++) {
913 if (lengths[i] > maxmap) {
914 printf("cam_periph_mapmem: attempt to map %lu bytes, "
915 "which is greater than %lu\n",
916 (long)(lengths[i]), (u_long)maxmap);
917 return (E2BIG);
918 }
919 }
920
921 /*
922 * This keeps the kernel stack of current thread from getting
923 * swapped. In low-memory situations where the kernel stack might
924 * otherwise get swapped out, this holds it and allows the thread
925 * to make progress and release the kernel mapped pages sooner.
926 *
927 * XXX KDM should I use P_NOSWAP instead?
928 */
929 PHOLD(curproc);
930
931 for (i = 0; i < numbufs; i++) {
932 /* Save the user's data address. */
933 mapinfo->orig[i] = *data_ptrs[i];
934
935 /*
936 * For small buffers use malloc+copyin/copyout instead of
937 * mapping to KVA to avoid expensive TLB shootdowns. For
938 * small allocations malloc is backed by UMA, and so much
939 * cheaper on SMP systems.
940 */
941 if (lengths[i] <= periph_mapmem_thresh &&
942 ccb->ccb_h.func_code != XPT_MMC_IO) {
943 *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
944 M_WAITOK);
945 if (dirs[i] != CAM_DIR_IN) {
946 if (copyin(mapinfo->orig[i], *data_ptrs[i],
947 lengths[i]) != 0) {
948 free(*data_ptrs[i], M_CAMPERIPH);
949 *data_ptrs[i] = mapinfo->orig[i];
950 goto fail;
951 }
952 } else
953 bzero(*data_ptrs[i], lengths[i]);
954 continue;
955 }
956
957 /*
958 * Get the buffer.
959 */
960 mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
961
962 /* set the direction */
963 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
964 BIO_WRITE : BIO_READ;
965
966 /* Map the buffer into kernel memory. */
967 if (vmapbuf(mapinfo->bp[i], *data_ptrs[i], lengths[i], 1) < 0) {
968 uma_zfree(pbuf_zone, mapinfo->bp[i]);
969 goto fail;
970 }
971
972 /* set our pointer to the new mapped area */
973 *data_ptrs[i] = mapinfo->bp[i]->b_data;
974 }
975
976 /*
977 * Now that we've gotten this far, change ownership to the kernel
978 * of the buffers so that we don't run afoul of returning to user
979 * space with locks (on the buffer) held.
980 */
981 for (i = 0; i < numbufs; i++) {
982 if (mapinfo->bp[i])
983 BUF_KERNPROC(mapinfo->bp[i]);
984 }
985
986 mapinfo->num_bufs_used = numbufs;
987 return(0);
988
989 fail:
990 for (i--; i >= 0; i--) {
991 if (mapinfo->bp[i]) {
992 vunmapbuf(mapinfo->bp[i]);
993 uma_zfree(pbuf_zone, mapinfo->bp[i]);
994 } else
995 free(*data_ptrs[i], M_CAMPERIPH);
996 *data_ptrs[i] = mapinfo->orig[i];
997 }
998 PRELE(curproc);
999 return(EACCES);
1000 }
1001
1002 /*
1003 * Unmap memory segments mapped into kernel virtual address space by
1004 * cam_periph_mapmem().
1005 */
1006 void
cam_periph_unmapmem(union ccb * ccb,struct cam_periph_map_info * mapinfo)1007 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
1008 {
1009 int numbufs, i;
1010 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1011 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
1012 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
1013
1014 if (mapinfo->num_bufs_used <= 0) {
1015 /* nothing to free and the process wasn't held. */
1016 return;
1017 }
1018
1019 switch (ccb->ccb_h.func_code) {
1020 case XPT_DEV_MATCH:
1021 if (ccb->cdm.pattern_buf_len > 0) {
1022 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1023 lengths[0] = ccb->cdm.pattern_buf_len;
1024 dirs[0] = CAM_DIR_OUT;
1025 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1026 lengths[1] = ccb->cdm.match_buf_len;
1027 dirs[1] = CAM_DIR_IN;
1028 numbufs = 2;
1029 } else {
1030 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1031 lengths[0] = ccb->cdm.match_buf_len;
1032 dirs[0] = CAM_DIR_IN;
1033 numbufs = 1;
1034 }
1035 break;
1036 case XPT_SCSI_IO:
1037 case XPT_CONT_TARGET_IO:
1038 data_ptrs[0] = &ccb->csio.data_ptr;
1039 lengths[0] = ccb->csio.dxfer_len;
1040 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1041 numbufs = 1;
1042 break;
1043 case XPT_ATA_IO:
1044 data_ptrs[0] = &ccb->ataio.data_ptr;
1045 lengths[0] = ccb->ataio.dxfer_len;
1046 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1047 numbufs = 1;
1048 break;
1049 case XPT_MMC_IO:
1050 data_ptrs[0] = (u_int8_t **)&ccb->mmcio.cmd.data;
1051 lengths[0] = sizeof(struct mmc_data *);
1052 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1053 data_ptrs[1] = (u_int8_t **)&ccb->mmcio.cmd.data->data;
1054 lengths[1] = ccb->mmcio.cmd.data->len;
1055 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1056 numbufs = 2;
1057 break;
1058 case XPT_SMP_IO:
1059 data_ptrs[0] = &ccb->smpio.smp_request;
1060 lengths[0] = ccb->smpio.smp_request_len;
1061 dirs[0] = CAM_DIR_OUT;
1062 data_ptrs[1] = &ccb->smpio.smp_response;
1063 lengths[1] = ccb->smpio.smp_response_len;
1064 dirs[1] = CAM_DIR_IN;
1065 numbufs = 2;
1066 break;
1067 case XPT_NVME_IO:
1068 case XPT_NVME_ADMIN:
1069 data_ptrs[0] = &ccb->nvmeio.data_ptr;
1070 lengths[0] = ccb->nvmeio.dxfer_len;
1071 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1072 numbufs = 1;
1073 break;
1074 case XPT_DEV_ADVINFO:
1075 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1076 lengths[0] = ccb->cdai.bufsiz;
1077 dirs[0] = CAM_DIR_IN;
1078 numbufs = 1;
1079 break;
1080 default:
1081 /* allow ourselves to be swapped once again */
1082 PRELE(curproc);
1083 return;
1084 break; /* NOTREACHED */
1085 }
1086
1087 for (i = 0; i < numbufs; i++) {
1088 if (mapinfo->bp[i]) {
1089 /* unmap the buffer */
1090 vunmapbuf(mapinfo->bp[i]);
1091
1092 /* release the buffer */
1093 uma_zfree(pbuf_zone, mapinfo->bp[i]);
1094 } else {
1095 if (dirs[i] != CAM_DIR_OUT) {
1096 copyout(*data_ptrs[i], mapinfo->orig[i],
1097 lengths[i]);
1098 }
1099 free(*data_ptrs[i], M_CAMPERIPH);
1100 }
1101
1102 /* Set the user's pointer back to the original value */
1103 *data_ptrs[i] = mapinfo->orig[i];
1104 }
1105
1106 /* allow ourselves to be swapped once again */
1107 PRELE(curproc);
1108 }
1109
1110 int
cam_periph_ioctl(struct cam_periph * periph,u_long cmd,caddr_t addr,int (* error_routine)(union ccb * ccb,cam_flags camflags,u_int32_t sense_flags))1111 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1112 int (*error_routine)(union ccb *ccb,
1113 cam_flags camflags,
1114 u_int32_t sense_flags))
1115 {
1116 union ccb *ccb;
1117 int error;
1118 int found;
1119
1120 error = found = 0;
1121
1122 switch(cmd){
1123 case CAMGETPASSTHRU_0x19:
1124 case CAMGETPASSTHRU:
1125 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1126 xpt_setup_ccb(&ccb->ccb_h,
1127 ccb->ccb_h.path,
1128 CAM_PRIORITY_NORMAL);
1129 ccb->ccb_h.func_code = XPT_GDEVLIST;
1130
1131 /*
1132 * Basically, the point of this is that we go through
1133 * getting the list of devices, until we find a passthrough
1134 * device. In the current version of the CAM code, the
1135 * only way to determine what type of device we're dealing
1136 * with is by its name.
1137 */
1138 while (found == 0) {
1139 ccb->cgdl.index = 0;
1140 ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1141 while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1142 /* we want the next device in the list */
1143 xpt_action(ccb);
1144 if (strncmp(ccb->cgdl.periph_name,
1145 "pass", 4) == 0){
1146 found = 1;
1147 break;
1148 }
1149 }
1150 if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1151 (found == 0)) {
1152 ccb->cgdl.periph_name[0] = '\0';
1153 ccb->cgdl.unit_number = 0;
1154 break;
1155 }
1156 }
1157
1158 /* copy the result back out */
1159 bcopy(ccb, addr, sizeof(union ccb));
1160
1161 /* and release the ccb */
1162 xpt_release_ccb(ccb);
1163
1164 break;
1165 default:
1166 error = ENOTTY;
1167 break;
1168 }
1169 return(error);
1170 }
1171
1172 static void
cam_periph_done_panic(struct cam_periph * periph,union ccb * done_ccb)1173 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1174 {
1175
1176 panic("%s: already done with ccb %p", __func__, done_ccb);
1177 }
1178
1179 static void
cam_periph_done(struct cam_periph * periph,union ccb * done_ccb)1180 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1181 {
1182
1183 /* Caller will release the CCB */
1184 xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1185 done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1186 wakeup(&done_ccb->ccb_h.cbfcnp);
1187 }
1188
1189 static void
cam_periph_ccbwait(union ccb * ccb)1190 cam_periph_ccbwait(union ccb *ccb)
1191 {
1192
1193 if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1194 while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1195 xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1196 PRIBIO, "cbwait", 0);
1197 }
1198 KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1199 (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1200 ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1201 "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1202 ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1203 }
1204
1205 /*
1206 * Dispatch a CCB and wait for it to complete. If the CCB has set a
1207 * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1208 */
1209 int
cam_periph_runccb(union ccb * ccb,int (* error_routine)(union ccb * ccb,cam_flags camflags,u_int32_t sense_flags),cam_flags camflags,u_int32_t sense_flags,struct devstat * ds)1210 cam_periph_runccb(union ccb *ccb,
1211 int (*error_routine)(union ccb *ccb,
1212 cam_flags camflags,
1213 u_int32_t sense_flags),
1214 cam_flags camflags, u_int32_t sense_flags,
1215 struct devstat *ds)
1216 {
1217 struct bintime *starttime;
1218 struct bintime ltime;
1219 int error;
1220 bool must_poll;
1221 uint32_t timeout = 1;
1222
1223 starttime = NULL;
1224 xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1225 KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1226 ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1227 ccb->ccb_h.func_code, ccb->ccb_h.flags));
1228
1229 /*
1230 * If the user has supplied a stats structure, and if we understand
1231 * this particular type of ccb, record the transaction start.
1232 */
1233 if (ds != NULL &&
1234 (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1235 ccb->ccb_h.func_code == XPT_ATA_IO ||
1236 ccb->ccb_h.func_code == XPT_NVME_IO)) {
1237 starttime = <ime;
1238 binuptime(starttime);
1239 devstat_start_transaction(ds, starttime);
1240 }
1241
1242 /*
1243 * We must poll the I/O while we're dumping. The scheduler is normally
1244 * stopped for dumping, except when we call doadump from ddb. While the
1245 * scheduler is running in this case, we still need to poll the I/O to
1246 * avoid sleeping waiting for the ccb to complete.
1247 *
1248 * A panic triggered dump stops the scheduler, any callback from the
1249 * shutdown_post_sync event will run with the scheduler stopped, but
1250 * before we're officially dumping. To avoid hanging in adashutdown
1251 * initiated commands (or other similar situations), we have to test for
1252 * either SCHEDULER_STOPPED() here as well.
1253 *
1254 * To avoid locking problems, dumping/polling callers must call
1255 * without a periph lock held.
1256 */
1257 must_poll = dumping || SCHEDULER_STOPPED();
1258 ccb->ccb_h.cbfcnp = cam_periph_done;
1259
1260 /*
1261 * If we're polling, then we need to ensure that we have ample resources
1262 * in the periph. cam_periph_error can reschedule the ccb by calling
1263 * xpt_action and returning ERESTART, so we have to effect the polling
1264 * in the do loop below.
1265 */
1266 if (must_poll) {
1267 if (cam_sim_pollable(ccb->ccb_h.path->bus->sim))
1268 timeout = xpt_poll_setup(ccb);
1269 else
1270 timeout = 0;
1271 }
1272
1273 if (timeout == 0) {
1274 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1275 error = EBUSY;
1276 } else {
1277 xpt_action(ccb);
1278 do {
1279 if (must_poll) {
1280 xpt_pollwait(ccb, timeout);
1281 timeout = ccb->ccb_h.timeout * 10;
1282 } else {
1283 cam_periph_ccbwait(ccb);
1284 }
1285 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1286 error = 0;
1287 else if (error_routine != NULL) {
1288 ccb->ccb_h.cbfcnp = cam_periph_done;
1289 error = (*error_routine)(ccb, camflags, sense_flags);
1290 } else
1291 error = 0;
1292 } while (error == ERESTART);
1293 }
1294
1295 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1296 cam_release_devq(ccb->ccb_h.path,
1297 /* relsim_flags */0,
1298 /* openings */0,
1299 /* timeout */0,
1300 /* getcount_only */ FALSE);
1301 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1302 }
1303
1304 if (ds != NULL) {
1305 uint32_t bytes;
1306 devstat_tag_type tag;
1307 bool valid = true;
1308
1309 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1310 bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1311 tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1312 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1313 bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1314 tag = (devstat_tag_type)0;
1315 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1316 bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1317 tag = (devstat_tag_type)0;
1318 } else {
1319 valid = false;
1320 }
1321 if (valid)
1322 devstat_end_transaction(ds, bytes, tag,
1323 ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1324 DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1325 DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1326 }
1327
1328 return(error);
1329 }
1330
1331 void
cam_freeze_devq(struct cam_path * path)1332 cam_freeze_devq(struct cam_path *path)
1333 {
1334 struct ccb_hdr ccb_h;
1335
1336 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1337 memset(&ccb_h, 0, sizeof(ccb_h));
1338 xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1339 ccb_h.func_code = XPT_NOOP;
1340 ccb_h.flags = CAM_DEV_QFREEZE;
1341 xpt_action((union ccb *)&ccb_h);
1342 }
1343
1344 u_int32_t
cam_release_devq(struct cam_path * path,u_int32_t relsim_flags,u_int32_t openings,u_int32_t arg,int getcount_only)1345 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1346 u_int32_t openings, u_int32_t arg,
1347 int getcount_only)
1348 {
1349 struct ccb_relsim crs;
1350
1351 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1352 relsim_flags, openings, arg, getcount_only));
1353 memset(&crs, 0, sizeof(crs));
1354 xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1355 crs.ccb_h.func_code = XPT_REL_SIMQ;
1356 crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1357 crs.release_flags = relsim_flags;
1358 crs.openings = openings;
1359 crs.release_timeout = arg;
1360 xpt_action((union ccb *)&crs);
1361 return (crs.qfrozen_cnt);
1362 }
1363
1364 #define saved_ccb_ptr ppriv_ptr0
1365 static void
camperiphdone(struct cam_periph * periph,union ccb * done_ccb)1366 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1367 {
1368 union ccb *saved_ccb;
1369 cam_status status;
1370 struct scsi_start_stop_unit *scsi_cmd;
1371 int error = 0, error_code, sense_key, asc, ascq;
1372
1373 scsi_cmd = (struct scsi_start_stop_unit *)
1374 &done_ccb->csio.cdb_io.cdb_bytes;
1375 status = done_ccb->ccb_h.status;
1376
1377 if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1378 if (scsi_extract_sense_ccb(done_ccb,
1379 &error_code, &sense_key, &asc, &ascq)) {
1380 /*
1381 * If the error is "invalid field in CDB",
1382 * and the load/eject flag is set, turn the
1383 * flag off and try again. This is just in
1384 * case the drive in question barfs on the
1385 * load eject flag. The CAM code should set
1386 * the load/eject flag by default for
1387 * removable media.
1388 */
1389 if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1390 ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1391 (asc == 0x24) && (ascq == 0x00)) {
1392 scsi_cmd->how &= ~SSS_LOEJ;
1393 if (status & CAM_DEV_QFRZN) {
1394 cam_release_devq(done_ccb->ccb_h.path,
1395 0, 0, 0, 0);
1396 done_ccb->ccb_h.status &=
1397 ~CAM_DEV_QFRZN;
1398 }
1399 xpt_action(done_ccb);
1400 goto out;
1401 }
1402 }
1403 error = cam_periph_error(done_ccb, 0,
1404 SF_RETRY_UA | SF_NO_PRINT);
1405 if (error == ERESTART)
1406 goto out;
1407 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1408 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1409 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1410 }
1411 } else {
1412 /*
1413 * If we have successfully taken a device from the not
1414 * ready to ready state, re-scan the device and re-get
1415 * the inquiry information. Many devices (mostly disks)
1416 * don't properly report their inquiry information unless
1417 * they are spun up.
1418 */
1419 if (scsi_cmd->opcode == START_STOP_UNIT)
1420 xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1421 }
1422
1423 /* If we tried long wait and still failed, remember that. */
1424 if ((periph->flags & CAM_PERIPH_RECOVERY_WAIT) &&
1425 (done_ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY)) {
1426 periph->flags &= ~CAM_PERIPH_RECOVERY_WAIT;
1427 if (error != 0 && done_ccb->ccb_h.retry_count == 0)
1428 periph->flags |= CAM_PERIPH_RECOVERY_WAIT_FAILED;
1429 }
1430
1431 /*
1432 * After recovery action(s) completed, return to the original CCB.
1433 * If the recovery CCB has failed, considering its own possible
1434 * retries and recovery, assume we are back in state where we have
1435 * been originally, but without recovery hopes left. In such case,
1436 * after the final attempt below, we cancel any further retries,
1437 * blocking by that also any new recovery attempts for this CCB,
1438 * and the result will be the final one returned to the CCB owher.
1439 */
1440 saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1441 saved_ccb->ccb_h.periph_links = done_ccb->ccb_h.periph_links;
1442 bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1443 xpt_free_ccb(saved_ccb);
1444 if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1445 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1446 if (error != 0)
1447 done_ccb->ccb_h.retry_count = 0;
1448 xpt_action(done_ccb);
1449
1450 out:
1451 /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1452 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1453 }
1454
1455 /*
1456 * Generic Async Event handler. Peripheral drivers usually
1457 * filter out the events that require personal attention,
1458 * and leave the rest to this function.
1459 */
1460 void
cam_periph_async(struct cam_periph * periph,u_int32_t code,struct cam_path * path,void * arg)1461 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1462 struct cam_path *path, void *arg)
1463 {
1464 switch (code) {
1465 case AC_LOST_DEVICE:
1466 cam_periph_invalidate(periph);
1467 break;
1468 default:
1469 break;
1470 }
1471 }
1472
1473 void
cam_periph_bus_settle(struct cam_periph * periph,u_int bus_settle)1474 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1475 {
1476 struct ccb_getdevstats cgds;
1477
1478 memset(&cgds, 0, sizeof(cgds));
1479 xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1480 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1481 xpt_action((union ccb *)&cgds);
1482 cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1483 }
1484
1485 void
cam_periph_freeze_after_event(struct cam_periph * periph,struct timeval * event_time,u_int duration_ms)1486 cam_periph_freeze_after_event(struct cam_periph *periph,
1487 struct timeval* event_time, u_int duration_ms)
1488 {
1489 struct timeval delta;
1490 struct timeval duration_tv;
1491
1492 if (!timevalisset(event_time))
1493 return;
1494
1495 microtime(&delta);
1496 timevalsub(&delta, event_time);
1497 duration_tv.tv_sec = duration_ms / 1000;
1498 duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1499 if (timevalcmp(&delta, &duration_tv, <)) {
1500 timevalsub(&duration_tv, &delta);
1501
1502 duration_ms = duration_tv.tv_sec * 1000;
1503 duration_ms += duration_tv.tv_usec / 1000;
1504 cam_freeze_devq(periph->path);
1505 cam_release_devq(periph->path,
1506 RELSIM_RELEASE_AFTER_TIMEOUT,
1507 /*reduction*/0,
1508 /*timeout*/duration_ms,
1509 /*getcount_only*/0);
1510 }
1511
1512 }
1513
1514 static int
camperiphscsistatuserror(union ccb * ccb,union ccb ** orig_ccb,cam_flags camflags,u_int32_t sense_flags,int * openings,u_int32_t * relsim_flags,u_int32_t * timeout,u_int32_t * action,const char ** action_string)1515 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1516 cam_flags camflags, u_int32_t sense_flags,
1517 int *openings, u_int32_t *relsim_flags,
1518 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1519 {
1520 struct cam_periph *periph;
1521 int error;
1522
1523 switch (ccb->csio.scsi_status) {
1524 case SCSI_STATUS_OK:
1525 case SCSI_STATUS_COND_MET:
1526 case SCSI_STATUS_INTERMED:
1527 case SCSI_STATUS_INTERMED_COND_MET:
1528 error = 0;
1529 break;
1530 case SCSI_STATUS_CMD_TERMINATED:
1531 case SCSI_STATUS_CHECK_COND:
1532 error = camperiphscsisenseerror(ccb, orig_ccb,
1533 camflags,
1534 sense_flags,
1535 openings,
1536 relsim_flags,
1537 timeout,
1538 action,
1539 action_string);
1540 break;
1541 case SCSI_STATUS_QUEUE_FULL:
1542 {
1543 /* no decrement */
1544 struct ccb_getdevstats cgds;
1545
1546 /*
1547 * First off, find out what the current
1548 * transaction counts are.
1549 */
1550 memset(&cgds, 0, sizeof(cgds));
1551 xpt_setup_ccb(&cgds.ccb_h,
1552 ccb->ccb_h.path,
1553 CAM_PRIORITY_NORMAL);
1554 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1555 xpt_action((union ccb *)&cgds);
1556
1557 /*
1558 * If we were the only transaction active, treat
1559 * the QUEUE FULL as if it were a BUSY condition.
1560 */
1561 if (cgds.dev_active != 0) {
1562 int total_openings;
1563
1564 /*
1565 * Reduce the number of openings to
1566 * be 1 less than the amount it took
1567 * to get a queue full bounded by the
1568 * minimum allowed tag count for this
1569 * device.
1570 */
1571 total_openings = cgds.dev_active + cgds.dev_openings;
1572 *openings = cgds.dev_active;
1573 if (*openings < cgds.mintags)
1574 *openings = cgds.mintags;
1575 if (*openings < total_openings)
1576 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1577 else {
1578 /*
1579 * Some devices report queue full for
1580 * temporary resource shortages. For
1581 * this reason, we allow a minimum
1582 * tag count to be entered via a
1583 * quirk entry to prevent the queue
1584 * count on these devices from falling
1585 * to a pessimisticly low value. We
1586 * still wait for the next successful
1587 * completion, however, before queueing
1588 * more transactions to the device.
1589 */
1590 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1591 }
1592 *timeout = 0;
1593 error = ERESTART;
1594 *action &= ~SSQ_PRINT_SENSE;
1595 break;
1596 }
1597 /* FALLTHROUGH */
1598 }
1599 case SCSI_STATUS_BUSY:
1600 /*
1601 * Restart the queue after either another
1602 * command completes or a 1 second timeout.
1603 */
1604 periph = xpt_path_periph(ccb->ccb_h.path);
1605 if (periph->flags & CAM_PERIPH_INVALID) {
1606 error = ENXIO;
1607 *action_string = "Periph was invalidated";
1608 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1609 ccb->ccb_h.retry_count > 0) {
1610 if ((sense_flags & SF_RETRY_BUSY) == 0)
1611 ccb->ccb_h.retry_count--;
1612 error = ERESTART;
1613 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1614 | RELSIM_RELEASE_AFTER_CMDCMPLT;
1615 *timeout = 1000;
1616 } else {
1617 error = EIO;
1618 *action_string = "Retries exhausted";
1619 }
1620 break;
1621 case SCSI_STATUS_RESERV_CONFLICT:
1622 default:
1623 error = EIO;
1624 break;
1625 }
1626 return (error);
1627 }
1628
1629 static int
camperiphscsisenseerror(union ccb * ccb,union ccb ** orig,cam_flags camflags,u_int32_t sense_flags,int * openings,u_int32_t * relsim_flags,u_int32_t * timeout,u_int32_t * action,const char ** action_string)1630 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1631 cam_flags camflags, u_int32_t sense_flags,
1632 int *openings, u_int32_t *relsim_flags,
1633 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1634 {
1635 struct cam_periph *periph;
1636 union ccb *orig_ccb = ccb;
1637 int error, recoveryccb;
1638
1639 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1640 if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1641 biotrack(ccb->csio.bio, __func__);
1642 #endif
1643
1644 periph = xpt_path_periph(ccb->ccb_h.path);
1645 recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1646 if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1647 /*
1648 * If error recovery is already in progress, don't attempt
1649 * to process this error, but requeue it unconditionally
1650 * and attempt to process it once error recovery has
1651 * completed. This failed command is probably related to
1652 * the error that caused the currently active error recovery
1653 * action so our current recovery efforts should also
1654 * address this command. Be aware that the error recovery
1655 * code assumes that only one recovery action is in progress
1656 * on a particular peripheral instance at any given time
1657 * (e.g. only one saved CCB for error recovery) so it is
1658 * imperitive that we don't violate this assumption.
1659 */
1660 error = ERESTART;
1661 *action &= ~SSQ_PRINT_SENSE;
1662 } else {
1663 scsi_sense_action err_action;
1664 struct ccb_getdev cgd;
1665
1666 /*
1667 * Grab the inquiry data for this device.
1668 */
1669 memset(&cgd, 0, sizeof(cgd));
1670 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1671 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1672 xpt_action((union ccb *)&cgd);
1673
1674 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1675 sense_flags);
1676 error = err_action & SS_ERRMASK;
1677
1678 /*
1679 * Do not autostart sequential access devices
1680 * to avoid unexpected tape loading.
1681 */
1682 if ((err_action & SS_MASK) == SS_START &&
1683 SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1684 *action_string = "Will not autostart a "
1685 "sequential access device";
1686 goto sense_error_done;
1687 }
1688
1689 /*
1690 * Avoid recovery recursion if recovery action is the same.
1691 */
1692 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1693 if (((err_action & SS_MASK) == SS_START &&
1694 ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1695 ((err_action & SS_MASK) == SS_TUR &&
1696 (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1697 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1698 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1699 *timeout = 500;
1700 }
1701 }
1702
1703 /*
1704 * If the recovery action will consume a retry,
1705 * make sure we actually have retries available.
1706 */
1707 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1708 if (ccb->ccb_h.retry_count > 0 &&
1709 (periph->flags & CAM_PERIPH_INVALID) == 0)
1710 ccb->ccb_h.retry_count--;
1711 else {
1712 *action_string = "Retries exhausted";
1713 goto sense_error_done;
1714 }
1715 }
1716
1717 if ((err_action & SS_MASK) >= SS_START) {
1718 /*
1719 * Do common portions of commands that
1720 * use recovery CCBs.
1721 */
1722 orig_ccb = xpt_alloc_ccb_nowait();
1723 if (orig_ccb == NULL) {
1724 *action_string = "Can't allocate recovery CCB";
1725 goto sense_error_done;
1726 }
1727 /*
1728 * Clear freeze flag for original request here, as
1729 * this freeze will be dropped as part of ERESTART.
1730 */
1731 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1732 bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1733 }
1734
1735 switch (err_action & SS_MASK) {
1736 case SS_NOP:
1737 *action_string = "No recovery action needed";
1738 error = 0;
1739 break;
1740 case SS_RETRY:
1741 *action_string = "Retrying command (per sense data)";
1742 error = ERESTART;
1743 break;
1744 case SS_FAIL:
1745 *action_string = "Unretryable error";
1746 break;
1747 case SS_START:
1748 {
1749 int le;
1750
1751 /*
1752 * Send a start unit command to the device, and
1753 * then retry the command.
1754 */
1755 *action_string = "Attempting to start unit";
1756 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1757
1758 /*
1759 * Check for removable media and set
1760 * load/eject flag appropriately.
1761 */
1762 if (SID_IS_REMOVABLE(&cgd.inq_data))
1763 le = TRUE;
1764 else
1765 le = FALSE;
1766
1767 scsi_start_stop(&ccb->csio,
1768 /*retries*/1,
1769 camperiphdone,
1770 MSG_SIMPLE_Q_TAG,
1771 /*start*/TRUE,
1772 /*load/eject*/le,
1773 /*immediate*/FALSE,
1774 SSD_FULL_SIZE,
1775 /*timeout*/50000);
1776 break;
1777 }
1778 case SS_TUR:
1779 {
1780 /*
1781 * Send a Test Unit Ready to the device.
1782 * If the 'many' flag is set, we send 120
1783 * test unit ready commands, one every half
1784 * second. Otherwise, we just send one TUR.
1785 * We only want to do this if the retry
1786 * count has not been exhausted.
1787 */
1788 int retries;
1789
1790 if ((err_action & SSQ_MANY) != 0 && (periph->flags &
1791 CAM_PERIPH_RECOVERY_WAIT_FAILED) == 0) {
1792 periph->flags |= CAM_PERIPH_RECOVERY_WAIT;
1793 *action_string = "Polling device for readiness";
1794 retries = 120;
1795 } else {
1796 *action_string = "Testing device for readiness";
1797 retries = 1;
1798 }
1799 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1800 scsi_test_unit_ready(&ccb->csio,
1801 retries,
1802 camperiphdone,
1803 MSG_SIMPLE_Q_TAG,
1804 SSD_FULL_SIZE,
1805 /*timeout*/5000);
1806
1807 /*
1808 * Accomplish our 500ms delay by deferring
1809 * the release of our device queue appropriately.
1810 */
1811 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1812 *timeout = 500;
1813 break;
1814 }
1815 default:
1816 panic("Unhandled error action %x", err_action);
1817 }
1818
1819 if ((err_action & SS_MASK) >= SS_START) {
1820 /*
1821 * Drop the priority, so that the recovery
1822 * CCB is the first to execute. Freeze the queue
1823 * after this command is sent so that we can
1824 * restore the old csio and have it queued in
1825 * the proper order before we release normal
1826 * transactions to the device.
1827 */
1828 ccb->ccb_h.pinfo.priority--;
1829 ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1830 ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1831 error = ERESTART;
1832 *orig = orig_ccb;
1833 }
1834
1835 sense_error_done:
1836 *action = err_action;
1837 }
1838 return (error);
1839 }
1840
1841 /*
1842 * Generic error handler. Peripheral drivers usually filter
1843 * out the errors that they handle in a unique manner, then
1844 * call this function.
1845 */
1846 int
cam_periph_error(union ccb * ccb,cam_flags camflags,u_int32_t sense_flags)1847 cam_periph_error(union ccb *ccb, cam_flags camflags,
1848 u_int32_t sense_flags)
1849 {
1850 struct cam_path *newpath;
1851 union ccb *orig_ccb, *scan_ccb;
1852 struct cam_periph *periph;
1853 const char *action_string;
1854 cam_status status;
1855 int frozen, error, openings, devctl_err;
1856 u_int32_t action, relsim_flags, timeout;
1857
1858 action = SSQ_PRINT_SENSE;
1859 periph = xpt_path_periph(ccb->ccb_h.path);
1860 action_string = NULL;
1861 status = ccb->ccb_h.status;
1862 frozen = (status & CAM_DEV_QFRZN) != 0;
1863 status &= CAM_STATUS_MASK;
1864 devctl_err = openings = relsim_flags = timeout = 0;
1865 orig_ccb = ccb;
1866
1867 /* Filter the errors that should be reported via devctl */
1868 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1869 case CAM_CMD_TIMEOUT:
1870 case CAM_REQ_ABORTED:
1871 case CAM_REQ_CMP_ERR:
1872 case CAM_REQ_TERMIO:
1873 case CAM_UNREC_HBA_ERROR:
1874 case CAM_DATA_RUN_ERR:
1875 case CAM_SCSI_STATUS_ERROR:
1876 case CAM_ATA_STATUS_ERROR:
1877 case CAM_SMP_STATUS_ERROR:
1878 devctl_err++;
1879 break;
1880 default:
1881 break;
1882 }
1883
1884 switch (status) {
1885 case CAM_REQ_CMP:
1886 error = 0;
1887 action &= ~SSQ_PRINT_SENSE;
1888 break;
1889 case CAM_SCSI_STATUS_ERROR:
1890 error = camperiphscsistatuserror(ccb, &orig_ccb,
1891 camflags, sense_flags, &openings, &relsim_flags,
1892 &timeout, &action, &action_string);
1893 break;
1894 case CAM_AUTOSENSE_FAIL:
1895 error = EIO; /* we have to kill the command */
1896 break;
1897 case CAM_UA_ABORT:
1898 case CAM_UA_TERMIO:
1899 case CAM_MSG_REJECT_REC:
1900 /* XXX Don't know that these are correct */
1901 error = EIO;
1902 break;
1903 case CAM_SEL_TIMEOUT:
1904 if ((camflags & CAM_RETRY_SELTO) != 0) {
1905 if (ccb->ccb_h.retry_count > 0 &&
1906 (periph->flags & CAM_PERIPH_INVALID) == 0) {
1907 ccb->ccb_h.retry_count--;
1908 error = ERESTART;
1909
1910 /*
1911 * Wait a bit to give the device
1912 * time to recover before we try again.
1913 */
1914 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1915 timeout = periph_selto_delay;
1916 break;
1917 }
1918 action_string = "Retries exhausted";
1919 }
1920 /* FALLTHROUGH */
1921 case CAM_DEV_NOT_THERE:
1922 error = ENXIO;
1923 action = SSQ_LOST;
1924 break;
1925 case CAM_REQ_INVALID:
1926 case CAM_PATH_INVALID:
1927 case CAM_NO_HBA:
1928 case CAM_PROVIDE_FAIL:
1929 case CAM_REQ_TOO_BIG:
1930 case CAM_LUN_INVALID:
1931 case CAM_TID_INVALID:
1932 case CAM_FUNC_NOTAVAIL:
1933 error = EINVAL;
1934 break;
1935 case CAM_SCSI_BUS_RESET:
1936 case CAM_BDR_SENT:
1937 /*
1938 * Commands that repeatedly timeout and cause these
1939 * kinds of error recovery actions, should return
1940 * CAM_CMD_TIMEOUT, which allows us to safely assume
1941 * that this command was an innocent bystander to
1942 * these events and should be unconditionally
1943 * retried.
1944 */
1945 case CAM_REQUEUE_REQ:
1946 /* Unconditional requeue if device is still there */
1947 if (periph->flags & CAM_PERIPH_INVALID) {
1948 action_string = "Periph was invalidated";
1949 error = ENXIO;
1950 } else if (sense_flags & SF_NO_RETRY) {
1951 error = EIO;
1952 action_string = "Retry was blocked";
1953 } else {
1954 error = ERESTART;
1955 action &= ~SSQ_PRINT_SENSE;
1956 }
1957 break;
1958 case CAM_RESRC_UNAVAIL:
1959 /* Wait a bit for the resource shortage to abate. */
1960 timeout = periph_noresrc_delay;
1961 /* FALLTHROUGH */
1962 case CAM_BUSY:
1963 if (timeout == 0) {
1964 /* Wait a bit for the busy condition to abate. */
1965 timeout = periph_busy_delay;
1966 }
1967 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1968 /* FALLTHROUGH */
1969 case CAM_ATA_STATUS_ERROR:
1970 case CAM_REQ_CMP_ERR:
1971 case CAM_CMD_TIMEOUT:
1972 case CAM_UNEXP_BUSFREE:
1973 case CAM_UNCOR_PARITY:
1974 case CAM_DATA_RUN_ERR:
1975 default:
1976 if (periph->flags & CAM_PERIPH_INVALID) {
1977 error = ENXIO;
1978 action_string = "Periph was invalidated";
1979 } else if (ccb->ccb_h.retry_count == 0) {
1980 error = EIO;
1981 action_string = "Retries exhausted";
1982 } else if (sense_flags & SF_NO_RETRY) {
1983 error = EIO;
1984 action_string = "Retry was blocked";
1985 } else {
1986 ccb->ccb_h.retry_count--;
1987 error = ERESTART;
1988 }
1989 break;
1990 }
1991
1992 if ((sense_flags & SF_PRINT_ALWAYS) ||
1993 CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1994 action |= SSQ_PRINT_SENSE;
1995 else if (sense_flags & SF_NO_PRINT)
1996 action &= ~SSQ_PRINT_SENSE;
1997 if ((action & SSQ_PRINT_SENSE) != 0)
1998 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1999 if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
2000 if (error != ERESTART) {
2001 if (action_string == NULL)
2002 action_string = "Unretryable error";
2003 xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
2004 error, action_string);
2005 } else if (action_string != NULL)
2006 xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2007 else {
2008 xpt_print(ccb->ccb_h.path,
2009 "Retrying command, %d more tries remain\n",
2010 ccb->ccb_h.retry_count);
2011 }
2012 }
2013
2014 if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2015 cam_periph_devctl_notify(orig_ccb);
2016
2017 if ((action & SSQ_LOST) != 0) {
2018 lun_id_t lun_id;
2019
2020 /*
2021 * For a selection timeout, we consider all of the LUNs on
2022 * the target to be gone. If the status is CAM_DEV_NOT_THERE,
2023 * then we only get rid of the device(s) specified by the
2024 * path in the original CCB.
2025 */
2026 if (status == CAM_SEL_TIMEOUT)
2027 lun_id = CAM_LUN_WILDCARD;
2028 else
2029 lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2030
2031 /* Should we do more if we can't create the path?? */
2032 if (xpt_create_path(&newpath, periph,
2033 xpt_path_path_id(ccb->ccb_h.path),
2034 xpt_path_target_id(ccb->ccb_h.path),
2035 lun_id) == CAM_REQ_CMP) {
2036 /*
2037 * Let peripheral drivers know that this
2038 * device has gone away.
2039 */
2040 xpt_async(AC_LOST_DEVICE, newpath, NULL);
2041 xpt_free_path(newpath);
2042 }
2043 }
2044
2045 /* Broadcast UNIT ATTENTIONs to all periphs. */
2046 if ((action & SSQ_UA) != 0)
2047 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2048
2049 /* Rescan target on "Reported LUNs data has changed" */
2050 if ((action & SSQ_RESCAN) != 0) {
2051 if (xpt_create_path(&newpath, NULL,
2052 xpt_path_path_id(ccb->ccb_h.path),
2053 xpt_path_target_id(ccb->ccb_h.path),
2054 CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2055 scan_ccb = xpt_alloc_ccb_nowait();
2056 if (scan_ccb != NULL) {
2057 scan_ccb->ccb_h.path = newpath;
2058 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2059 scan_ccb->crcn.flags = 0;
2060 xpt_rescan(scan_ccb);
2061 } else {
2062 xpt_print(newpath,
2063 "Can't allocate CCB to rescan target\n");
2064 xpt_free_path(newpath);
2065 }
2066 }
2067 }
2068
2069 /* Attempt a retry */
2070 if (error == ERESTART || error == 0) {
2071 if (frozen != 0)
2072 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2073 if (error == ERESTART)
2074 xpt_action(ccb);
2075 if (frozen != 0)
2076 cam_release_devq(ccb->ccb_h.path,
2077 relsim_flags,
2078 openings,
2079 timeout,
2080 /*getcount_only*/0);
2081 }
2082
2083 return (error);
2084 }
2085
2086 #define CAM_PERIPH_DEVD_MSG_SIZE 256
2087
2088 static void
cam_periph_devctl_notify(union ccb * ccb)2089 cam_periph_devctl_notify(union ccb *ccb)
2090 {
2091 struct cam_periph *periph;
2092 struct ccb_getdev *cgd;
2093 struct sbuf sb;
2094 int serr, sk, asc, ascq;
2095 char *sbmsg, *type;
2096
2097 sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2098 if (sbmsg == NULL)
2099 return;
2100
2101 sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2102
2103 periph = xpt_path_periph(ccb->ccb_h.path);
2104 sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2105 periph->unit_number);
2106
2107 sbuf_printf(&sb, "serial=\"");
2108 if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2109 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2110 CAM_PRIORITY_NORMAL);
2111 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2112 xpt_action((union ccb *)cgd);
2113
2114 if (cgd->ccb_h.status == CAM_REQ_CMP)
2115 sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2116 xpt_free_ccb((union ccb *)cgd);
2117 }
2118 sbuf_printf(&sb, "\" ");
2119 sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2120
2121 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2122 case CAM_CMD_TIMEOUT:
2123 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2124 type = "timeout";
2125 break;
2126 case CAM_SCSI_STATUS_ERROR:
2127 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2128 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2129 sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2130 serr, sk, asc, ascq);
2131 type = "error";
2132 break;
2133 case CAM_ATA_STATUS_ERROR:
2134 sbuf_printf(&sb, "RES=\"");
2135 ata_res_sbuf(&ccb->ataio.res, &sb);
2136 sbuf_printf(&sb, "\" ");
2137 type = "error";
2138 break;
2139 default:
2140 type = "error";
2141 break;
2142 }
2143
2144 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2145 sbuf_printf(&sb, "CDB=\"");
2146 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2147 sbuf_printf(&sb, "\" ");
2148 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2149 sbuf_printf(&sb, "ACB=\"");
2150 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2151 sbuf_printf(&sb, "\" ");
2152 }
2153
2154 if (sbuf_finish(&sb) == 0)
2155 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2156 sbuf_delete(&sb);
2157 free(sbmsg, M_CAMPERIPH);
2158 }
2159
2160 /*
2161 * Sysctl to force an invalidation of the drive right now. Can be
2162 * called with CTLFLAG_MPSAFE since we take periph lock.
2163 */
2164 int
cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)2165 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2166 {
2167 struct cam_periph *periph;
2168 int error, value;
2169
2170 periph = arg1;
2171 value = 0;
2172 error = sysctl_handle_int(oidp, &value, 0, req);
2173 if (error != 0 || req->newptr == NULL || value != 1)
2174 return (error);
2175
2176 cam_periph_lock(periph);
2177 cam_periph_invalidate(periph);
2178 cam_periph_unlock(periph);
2179
2180 return (0);
2181 }
2182