]> err.no Git - linux-2.6/blob - drivers/scsi/libiscsi.c
[SCSI] libiscsi, iscsi_tcp: add device support
[linux-2.6] / drivers / scsi / libiscsi.c
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */
24 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <asm/unaligned.h>
28 #include <net/tcp.h>
29 #include <scsi/scsi_cmnd.h>
30 #include <scsi/scsi_device.h>
31 #include <scsi/scsi_eh.h>
32 #include <scsi/scsi_tcq.h>
33 #include <scsi/scsi_host.h>
34 #include <scsi/scsi.h>
35 #include <scsi/iscsi_proto.h>
36 #include <scsi/scsi_transport.h>
37 #include <scsi/scsi_transport_iscsi.h>
38 #include <scsi/libiscsi.h>
39
40 struct iscsi_session *
41 class_to_transport_session(struct iscsi_cls_session *cls_session)
42 {
43         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
44         return iscsi_hostdata(shost->hostdata);
45 }
46 EXPORT_SYMBOL_GPL(class_to_transport_session);
47
48 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
49 #define SNA32_CHECK 2147483648UL
50
51 static int iscsi_sna_lt(u32 n1, u32 n2)
52 {
53         return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
54                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
55 }
56
57 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
58 static int iscsi_sna_lte(u32 n1, u32 n2)
59 {
60         return n1 == n2 || ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
61                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
62 }
63
64 void
65 iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
66 {
67         uint32_t max_cmdsn = be32_to_cpu(hdr->max_cmdsn);
68         uint32_t exp_cmdsn = be32_to_cpu(hdr->exp_cmdsn);
69
70         /*
71          * standard specifies this check for when to update expected and
72          * max sequence numbers
73          */
74         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
75                 return;
76
77         if (exp_cmdsn != session->exp_cmdsn &&
78             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
79                 session->exp_cmdsn = exp_cmdsn;
80
81         if (max_cmdsn != session->max_cmdsn &&
82             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) {
83                 session->max_cmdsn = max_cmdsn;
84                 /*
85                  * if the window closed with IO queued, then kick the
86                  * xmit thread
87                  */
88                 if (!list_empty(&session->leadconn->xmitqueue) ||
89                     !list_empty(&session->leadconn->mgmtqueue))
90                         scsi_queue_work(session->host,
91                                         &session->leadconn->xmitwork);
92         }
93 }
94 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
95
96 void iscsi_prep_unsolicit_data_pdu(struct iscsi_cmd_task *ctask,
97                                    struct iscsi_data *hdr)
98 {
99         struct iscsi_conn *conn = ctask->conn;
100
101         memset(hdr, 0, sizeof(struct iscsi_data));
102         hdr->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
103         hdr->datasn = cpu_to_be32(ctask->unsol_datasn);
104         ctask->unsol_datasn++;
105         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
106         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
107
108         hdr->itt = ctask->hdr->itt;
109         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
110         hdr->offset = cpu_to_be32(ctask->unsol_offset);
111
112         if (ctask->unsol_count > conn->max_xmit_dlength) {
113                 hton24(hdr->dlength, conn->max_xmit_dlength);
114                 ctask->data_count = conn->max_xmit_dlength;
115                 ctask->unsol_offset += ctask->data_count;
116                 hdr->flags = 0;
117         } else {
118                 hton24(hdr->dlength, ctask->unsol_count);
119                 ctask->data_count = ctask->unsol_count;
120                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
121         }
122 }
123 EXPORT_SYMBOL_GPL(iscsi_prep_unsolicit_data_pdu);
124
125 /**
126  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
127  * @ctask: iscsi cmd task
128  *
129  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
130  * fields like dlength or final based on how much data it sends
131  */
132 static void iscsi_prep_scsi_cmd_pdu(struct iscsi_cmd_task *ctask)
133 {
134         struct iscsi_conn *conn = ctask->conn;
135         struct iscsi_session *session = conn->session;
136         struct iscsi_cmd *hdr = ctask->hdr;
137         struct scsi_cmnd *sc = ctask->sc;
138
139         hdr->opcode = ISCSI_OP_SCSI_CMD;
140         hdr->flags = ISCSI_ATTR_SIMPLE;
141         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
142         hdr->itt = build_itt(ctask->itt, conn->id, session->age);
143         hdr->data_length = cpu_to_be32(scsi_bufflen(sc));
144         hdr->cmdsn = cpu_to_be32(session->cmdsn);
145         session->cmdsn++;
146         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
147         memcpy(hdr->cdb, sc->cmnd, sc->cmd_len);
148         if (sc->cmd_len < MAX_COMMAND_SIZE)
149                 memset(&hdr->cdb[sc->cmd_len], 0,
150                         MAX_COMMAND_SIZE - sc->cmd_len);
151
152         ctask->data_count = 0;
153         ctask->imm_count = 0;
154         if (sc->sc_data_direction == DMA_TO_DEVICE) {
155                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
156                 /*
157                  * Write counters:
158                  *
159                  *      imm_count       bytes to be sent right after
160                  *                      SCSI PDU Header
161                  *
162                  *      unsol_count     bytes(as Data-Out) to be sent
163                  *                      without R2T ack right after
164                  *                      immediate data
165                  *
166                  *      r2t_data_count  bytes to be sent via R2T ack's
167                  *
168                  *      pad_count       bytes to be sent as zero-padding
169                  */
170                 ctask->unsol_count = 0;
171                 ctask->unsol_offset = 0;
172                 ctask->unsol_datasn = 0;
173
174                 if (session->imm_data_en) {
175                         if (scsi_bufflen(sc) >= session->first_burst)
176                                 ctask->imm_count = min(session->first_burst,
177                                                         conn->max_xmit_dlength);
178                         else
179                                 ctask->imm_count = min(scsi_bufflen(sc),
180                                                         conn->max_xmit_dlength);
181                         hton24(ctask->hdr->dlength, ctask->imm_count);
182                 } else
183                         zero_data(ctask->hdr->dlength);
184
185                 if (!session->initial_r2t_en) {
186                         ctask->unsol_count = min((session->first_burst),
187                                 (scsi_bufflen(sc))) - ctask->imm_count;
188                         ctask->unsol_offset = ctask->imm_count;
189                 }
190
191                 if (!ctask->unsol_count)
192                         /* No unsolicit Data-Out's */
193                         ctask->hdr->flags |= ISCSI_FLAG_CMD_FINAL;
194         } else {
195                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
196                 zero_data(hdr->dlength);
197
198                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
199                         hdr->flags |= ISCSI_FLAG_CMD_READ;
200         }
201
202         conn->scsicmd_pdus_cnt++;
203
204         debug_scsi("iscsi prep [%s cid %d sc %p cdb 0x%x itt 0x%x len %d "
205                 "cmdsn %d win %d]\n",
206                 sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read",
207                 conn->id, sc, sc->cmnd[0], ctask->itt, scsi_bufflen(sc),
208                 session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1);
209 }
210
211 /**
212  * iscsi_complete_command - return command back to scsi-ml
213  * @ctask: iscsi cmd task
214  *
215  * Must be called with session lock.
216  * This function returns the scsi command to scsi-ml and returns
217  * the cmd task to the pool of available cmd tasks.
218  */
219 static void iscsi_complete_command(struct iscsi_cmd_task *ctask)
220 {
221         struct iscsi_session *session = ctask->conn->session;
222         struct scsi_cmnd *sc = ctask->sc;
223
224         ctask->state = ISCSI_TASK_COMPLETED;
225         ctask->sc = NULL;
226         /* SCSI eh reuses commands to verify us */
227         sc->SCp.ptr = NULL;
228         list_del_init(&ctask->running);
229         __kfifo_put(session->cmdpool.queue, (void*)&ctask, sizeof(void*));
230         sc->scsi_done(sc);
231 }
232
233 static void __iscsi_get_ctask(struct iscsi_cmd_task *ctask)
234 {
235         atomic_inc(&ctask->refcount);
236 }
237
238 static void __iscsi_put_ctask(struct iscsi_cmd_task *ctask)
239 {
240         if (atomic_dec_and_test(&ctask->refcount))
241                 iscsi_complete_command(ctask);
242 }
243
244 /**
245  * iscsi_cmd_rsp - SCSI Command Response processing
246  * @conn: iscsi connection
247  * @hdr: iscsi header
248  * @ctask: scsi command task
249  * @data: cmd data buffer
250  * @datalen: len of buffer
251  *
252  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
253  * then completes the command and task.
254  **/
255 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
256                                struct iscsi_cmd_task *ctask, char *data,
257                                int datalen)
258 {
259         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
260         struct iscsi_session *session = conn->session;
261         struct scsi_cmnd *sc = ctask->sc;
262
263         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
264         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
265
266         sc->result = (DID_OK << 16) | rhdr->cmd_status;
267
268         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
269                 sc->result = DID_ERROR << 16;
270                 goto out;
271         }
272
273         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
274                 uint16_t senselen;
275
276                 if (datalen < 2) {
277 invalid_datalen:
278                         printk(KERN_ERR "iscsi: Got CHECK_CONDITION but "
279                                "invalid data buffer size of %d\n", datalen);
280                         sc->result = DID_BAD_TARGET << 16;
281                         goto out;
282                 }
283
284                 senselen = be16_to_cpu(get_unaligned((__be16 *) data));
285                 if (datalen < senselen)
286                         goto invalid_datalen;
287
288                 memcpy(sc->sense_buffer, data + 2,
289                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
290                 debug_scsi("copied %d bytes of sense\n",
291                            min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
292         }
293
294         if (rhdr->flags & ISCSI_FLAG_CMD_UNDERFLOW) {
295                 int res_count = be32_to_cpu(rhdr->residual_count);
296
297                 if (res_count > 0 && res_count <= scsi_bufflen(sc))
298                         scsi_set_resid(sc, res_count);
299                 else
300                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
301         } else if (rhdr->flags & ISCSI_FLAG_CMD_BIDI_UNDERFLOW)
302                 sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
303         else if (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW)
304                 scsi_set_resid(sc, be32_to_cpu(rhdr->residual_count));
305
306 out:
307         debug_scsi("done [sc %lx res %d itt 0x%x]\n",
308                    (long)sc, sc->result, ctask->itt);
309         conn->scsirsp_pdus_cnt++;
310
311         __iscsi_put_ctask(ctask);
312 }
313
314 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
315 {
316         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
317
318         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
319         conn->tmfrsp_pdus_cnt++;
320
321         if (conn->tmf_state != TMF_QUEUED)
322                 return;
323
324         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
325                 conn->tmf_state = TMF_SUCCESS;
326         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
327                 conn->tmf_state = TMF_NOT_FOUND;
328         else
329                 conn->tmf_state = TMF_FAILED;
330         wake_up(&conn->ehwait);
331 }
332
333 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
334                                char *data, int datalen)
335 {
336         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
337         struct iscsi_hdr rejected_pdu;
338         uint32_t itt;
339
340         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
341
342         if (reject->reason == ISCSI_REASON_DATA_DIGEST_ERROR) {
343                 if (ntoh24(reject->dlength) > datalen)
344                         return ISCSI_ERR_PROTO;
345
346                 if (ntoh24(reject->dlength) >= sizeof(struct iscsi_hdr)) {
347                         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
348                         itt = get_itt(rejected_pdu.itt);
349                         printk(KERN_ERR "itt 0x%x had pdu (op 0x%x) rejected "
350                                 "due to DataDigest error.\n", itt,
351                                 rejected_pdu.opcode);
352                 }
353         }
354         return 0;
355 }
356
357 /**
358  * __iscsi_complete_pdu - complete pdu
359  * @conn: iscsi conn
360  * @hdr: iscsi header
361  * @data: data buffer
362  * @datalen: len of data buffer
363  *
364  * Completes pdu processing by freeing any resources allocated at
365  * queuecommand or send generic. session lock must be held and verify
366  * itt must have been called.
367  */
368 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
369                          char *data, int datalen)
370 {
371         struct iscsi_session *session = conn->session;
372         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
373         struct iscsi_cmd_task *ctask;
374         struct iscsi_mgmt_task *mtask;
375         uint32_t itt;
376
377         if (hdr->itt != RESERVED_ITT)
378                 itt = get_itt(hdr->itt);
379         else
380                 itt = ~0U;
381
382         if (itt < session->cmds_max) {
383                 ctask = session->cmds[itt];
384
385                 debug_scsi("cmdrsp [op 0x%x cid %d itt 0x%x len %d]\n",
386                            opcode, conn->id, ctask->itt, datalen);
387
388                 switch(opcode) {
389                 case ISCSI_OP_SCSI_CMD_RSP:
390                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
391                         iscsi_scsi_cmd_rsp(conn, hdr, ctask, data,
392                                            datalen);
393                         break;
394                 case ISCSI_OP_SCSI_DATA_IN:
395                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
396                         if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
397                                 conn->scsirsp_pdus_cnt++;
398                                 __iscsi_put_ctask(ctask);
399                         }
400                         break;
401                 case ISCSI_OP_R2T:
402                         /* LLD handles this for now */
403                         break;
404                 default:
405                         rc = ISCSI_ERR_BAD_OPCODE;
406                         break;
407                 }
408         } else if (itt >= ISCSI_MGMT_ITT_OFFSET &&
409                    itt < ISCSI_MGMT_ITT_OFFSET + session->mgmtpool_max) {
410                 mtask = session->mgmt_cmds[itt - ISCSI_MGMT_ITT_OFFSET];
411
412                 debug_scsi("immrsp [op 0x%x cid %d itt 0x%x len %d]\n",
413                            opcode, conn->id, mtask->itt, datalen);
414
415                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
416                 switch(opcode) {
417                 case ISCSI_OP_LOGOUT_RSP:
418                         if (datalen) {
419                                 rc = ISCSI_ERR_PROTO;
420                                 break;
421                         }
422                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
423                         /* fall through */
424                 case ISCSI_OP_LOGIN_RSP:
425                 case ISCSI_OP_TEXT_RSP:
426                         /*
427                          * login related PDU's exp_statsn is handled in
428                          * userspace
429                          */
430                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
431                                 rc = ISCSI_ERR_CONN_FAILED;
432                         list_del_init(&mtask->running);
433                         if (conn->login_mtask != mtask)
434                                 __kfifo_put(session->mgmtpool.queue,
435                                             (void*)&mtask, sizeof(void*));
436                         break;
437                 case ISCSI_OP_SCSI_TMFUNC_RSP:
438                         if (datalen) {
439                                 rc = ISCSI_ERR_PROTO;
440                                 break;
441                         }
442
443                         iscsi_tmf_rsp(conn, hdr);
444                         break;
445                 case ISCSI_OP_NOOP_IN:
446                         if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
447                                 rc = ISCSI_ERR_PROTO;
448                                 break;
449                         }
450                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
451
452                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
453                                 rc = ISCSI_ERR_CONN_FAILED;
454                         list_del_init(&mtask->running);
455                         __kfifo_put(session->mgmtpool.queue,
456                                     (void*)&mtask, sizeof(void*));
457                         break;
458                 default:
459                         rc = ISCSI_ERR_BAD_OPCODE;
460                         break;
461                 }
462         } else if (itt == ~0U) {
463                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
464
465                 switch(opcode) {
466                 case ISCSI_OP_NOOP_IN:
467                         if (datalen) {
468                                 rc = ISCSI_ERR_PROTO;
469                                 break;
470                         }
471
472                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
473                                 break;
474
475                         if (iscsi_recv_pdu(conn->cls_conn, hdr, NULL, 0))
476                                 rc = ISCSI_ERR_CONN_FAILED;
477                         break;
478                 case ISCSI_OP_REJECT:
479                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
480                         break;
481                 case ISCSI_OP_ASYNC_EVENT:
482                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
483                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
484                                 rc = ISCSI_ERR_CONN_FAILED;
485                         break;
486                 default:
487                         rc = ISCSI_ERR_BAD_OPCODE;
488                         break;
489                 }
490         } else
491                 rc = ISCSI_ERR_BAD_ITT;
492
493         return rc;
494 }
495 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
496
497 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
498                        char *data, int datalen)
499 {
500         int rc;
501
502         spin_lock(&conn->session->lock);
503         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
504         spin_unlock(&conn->session->lock);
505         return rc;
506 }
507 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
508
509 /* verify itt (itt encoding: age+cid+itt) */
510 int iscsi_verify_itt(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
511                      uint32_t *ret_itt)
512 {
513         struct iscsi_session *session = conn->session;
514         struct iscsi_cmd_task *ctask;
515         uint32_t itt;
516
517         if (hdr->itt != RESERVED_ITT) {
518                 if (((__force u32)hdr->itt & ISCSI_AGE_MASK) !=
519                     (session->age << ISCSI_AGE_SHIFT)) {
520                         printk(KERN_ERR "iscsi: received itt %x expected "
521                                 "session age (%x)\n", (__force u32)hdr->itt,
522                                 session->age & ISCSI_AGE_MASK);
523                         return ISCSI_ERR_BAD_ITT;
524                 }
525
526                 if (((__force u32)hdr->itt & ISCSI_CID_MASK) !=
527                     (conn->id << ISCSI_CID_SHIFT)) {
528                         printk(KERN_ERR "iscsi: received itt %x, expected "
529                                 "CID (%x)\n", (__force u32)hdr->itt, conn->id);
530                         return ISCSI_ERR_BAD_ITT;
531                 }
532                 itt = get_itt(hdr->itt);
533         } else
534                 itt = ~0U;
535
536         if (itt < session->cmds_max) {
537                 ctask = session->cmds[itt];
538
539                 if (!ctask->sc) {
540                         printk(KERN_INFO "iscsi: dropping ctask with "
541                                "itt 0x%x\n", ctask->itt);
542                         /* force drop */
543                         return ISCSI_ERR_NO_SCSI_CMD;
544                 }
545
546                 if (ctask->sc->SCp.phase != session->age) {
547                         printk(KERN_ERR "iscsi: ctask's session age %d, "
548                                 "expected %d\n", ctask->sc->SCp.phase,
549                                 session->age);
550                         return ISCSI_ERR_SESSION_FAILED;
551                 }
552         }
553
554         *ret_itt = itt;
555         return 0;
556 }
557 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
558
559 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
560 {
561         struct iscsi_session *session = conn->session;
562         unsigned long flags;
563
564         spin_lock_irqsave(&session->lock, flags);
565         if (session->state == ISCSI_STATE_FAILED) {
566                 spin_unlock_irqrestore(&session->lock, flags);
567                 return;
568         }
569
570         if (conn->stop_stage == 0)
571                 session->state = ISCSI_STATE_FAILED;
572         spin_unlock_irqrestore(&session->lock, flags);
573         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
574         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
575         iscsi_conn_error(conn->cls_conn, err);
576 }
577 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
578
579 static void iscsi_prep_mtask(struct iscsi_conn *conn,
580                              struct iscsi_mgmt_task *mtask)
581 {
582         struct iscsi_session *session = conn->session;
583         struct iscsi_hdr *hdr = mtask->hdr;
584         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
585
586         if (hdr->opcode != (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) &&
587             hdr->opcode != (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
588                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
589         /*
590          * pre-format CmdSN for outgoing PDU.
591          */
592         nop->cmdsn = cpu_to_be32(session->cmdsn);
593         if (hdr->itt != RESERVED_ITT) {
594                 hdr->itt = build_itt(mtask->itt, conn->id, session->age);
595                 /*
596                  * TODO: We always use immediate, so we never hit this.
597                  * If we start to send tmfs or nops as non-immediate then
598                  * we should start checking the cmdsn numbers for mgmt tasks.
599                  */
600                 if (conn->c_stage == ISCSI_CONN_STARTED &&
601                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
602                         session->queued_cmdsn++;
603                         session->cmdsn++;
604                 }
605         }
606
607         if (session->tt->init_mgmt_task)
608                 session->tt->init_mgmt_task(conn, mtask);
609
610         debug_scsi("mgmtpdu [op 0x%x hdr->itt 0x%x datalen %d]\n",
611                    hdr->opcode & ISCSI_OPCODE_MASK, hdr->itt,
612                    mtask->data_count);
613 }
614
615 static int iscsi_xmit_mtask(struct iscsi_conn *conn)
616 {
617         struct iscsi_hdr *hdr = conn->mtask->hdr;
618         int rc, was_logout = 0;
619
620         spin_unlock_bh(&conn->session->lock);
621         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT) {
622                 conn->session->state = ISCSI_STATE_IN_RECOVERY;
623                 iscsi_block_session(session_to_cls(conn->session));
624                 was_logout = 1;
625         }
626         rc = conn->session->tt->xmit_mgmt_task(conn, conn->mtask);
627         spin_lock_bh(&conn->session->lock);
628         if (rc)
629                 return rc;
630
631         /* done with this in-progress mtask */
632         conn->mtask = NULL;
633
634         if (was_logout) {
635                 set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
636                 return -ENODATA;
637         }
638         return 0;
639 }
640
641 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
642 {
643         struct iscsi_session *session = conn->session;
644
645         /*
646          * Check for iSCSI window and take care of CmdSN wrap-around
647          */
648         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
649                 debug_scsi("iSCSI CmdSN closed. ExpCmdSn %u MaxCmdSN %u "
650                            "CmdSN %u/%u\n", session->exp_cmdsn,
651                            session->max_cmdsn, session->cmdsn,
652                            session->queued_cmdsn);
653                 return -ENOSPC;
654         }
655         return 0;
656 }
657
658 static int iscsi_xmit_ctask(struct iscsi_conn *conn)
659 {
660         struct iscsi_cmd_task *ctask = conn->ctask;
661         int rc;
662
663         __iscsi_get_ctask(ctask);
664         spin_unlock_bh(&conn->session->lock);
665         rc = conn->session->tt->xmit_cmd_task(conn, ctask);
666         spin_lock_bh(&conn->session->lock);
667         __iscsi_put_ctask(ctask);
668         if (!rc)
669                 /* done with this ctask */
670                 conn->ctask = NULL;
671         return rc;
672 }
673
674 /**
675  * iscsi_requeue_ctask - requeue ctask to run from session workqueue
676  * @ctask: ctask to requeue
677  *
678  * LLDs that need to run a ctask from the session workqueue should call
679  * this. The session lock must be held.
680  */
681 void iscsi_requeue_ctask(struct iscsi_cmd_task *ctask)
682 {
683         struct iscsi_conn *conn = ctask->conn;
684
685         list_move_tail(&ctask->running, &conn->requeue);
686         scsi_queue_work(conn->session->host, &conn->xmitwork);
687 }
688 EXPORT_SYMBOL_GPL(iscsi_requeue_ctask);
689
690 /**
691  * iscsi_data_xmit - xmit any command into the scheduled connection
692  * @conn: iscsi connection
693  *
694  * Notes:
695  *      The function can return -EAGAIN in which case the caller must
696  *      re-schedule it again later or recover. '0' return code means
697  *      successful xmit.
698  **/
699 static int iscsi_data_xmit(struct iscsi_conn *conn)
700 {
701         int rc = 0;
702
703         spin_lock_bh(&conn->session->lock);
704         if (unlikely(conn->suspend_tx)) {
705                 debug_scsi("conn %d Tx suspended!\n", conn->id);
706                 spin_unlock_bh(&conn->session->lock);
707                 return -ENODATA;
708         }
709
710         if (conn->ctask) {
711                 rc = iscsi_xmit_ctask(conn);
712                 if (rc)
713                         goto again;
714         }
715
716         if (conn->mtask) {
717                 rc = iscsi_xmit_mtask(conn);
718                 if (rc)
719                         goto again;
720         }
721
722         /*
723          * process mgmt pdus like nops before commands since we should
724          * only have one nop-out as a ping from us and targets should not
725          * overflow us with nop-ins
726          */
727 check_mgmt:
728         while (!list_empty(&conn->mgmtqueue)) {
729                 conn->mtask = list_entry(conn->mgmtqueue.next,
730                                          struct iscsi_mgmt_task, running);
731                 iscsi_prep_mtask(conn, conn->mtask);
732                 list_move_tail(conn->mgmtqueue.next, &conn->mgmt_run_list);
733                 rc = iscsi_xmit_mtask(conn);
734                 if (rc)
735                         goto again;
736         }
737
738         /* process pending command queue */
739         while (!list_empty(&conn->xmitqueue)) {
740                 if (conn->tmf_state == TMF_QUEUED)
741                         break;
742
743                 conn->ctask = list_entry(conn->xmitqueue.next,
744                                          struct iscsi_cmd_task, running);
745                 iscsi_prep_scsi_cmd_pdu(conn->ctask);
746                 conn->session->tt->init_cmd_task(conn->ctask);
747                 conn->ctask->state = ISCSI_TASK_RUNNING;
748                 list_move_tail(conn->xmitqueue.next, &conn->run_list);
749                 rc = iscsi_xmit_ctask(conn);
750                 if (rc)
751                         goto again;
752                 /*
753                  * we could continuously get new ctask requests so
754                  * we need to check the mgmt queue for nops that need to
755                  * be sent to aviod starvation
756                  */
757                 if (!list_empty(&conn->mgmtqueue))
758                         goto check_mgmt;
759         }
760
761         while (!list_empty(&conn->requeue)) {
762                 if (conn->session->fast_abort && conn->tmf_state != TMF_INITIAL)
763                         break;
764
765                 conn->ctask = list_entry(conn->requeue.next,
766                                          struct iscsi_cmd_task, running);
767                 conn->ctask->state = ISCSI_TASK_RUNNING;
768                 list_move_tail(conn->requeue.next, &conn->run_list);
769                 rc = iscsi_xmit_ctask(conn);
770                 if (rc)
771                         goto again;
772                 if (!list_empty(&conn->mgmtqueue))
773                         goto check_mgmt;
774         }
775         spin_unlock_bh(&conn->session->lock);
776         return -ENODATA;
777
778 again:
779         if (unlikely(conn->suspend_tx))
780                 rc = -ENODATA;
781         spin_unlock_bh(&conn->session->lock);
782         return rc;
783 }
784
785 static void iscsi_xmitworker(struct work_struct *work)
786 {
787         struct iscsi_conn *conn =
788                 container_of(work, struct iscsi_conn, xmitwork);
789         int rc;
790         /*
791          * serialize Xmit worker on a per-connection basis.
792          */
793         do {
794                 rc = iscsi_data_xmit(conn);
795         } while (rc >= 0 || rc == -EAGAIN);
796 }
797
798 enum {
799         FAILURE_BAD_HOST = 1,
800         FAILURE_SESSION_FAILED,
801         FAILURE_SESSION_FREED,
802         FAILURE_WINDOW_CLOSED,
803         FAILURE_OOM,
804         FAILURE_SESSION_TERMINATE,
805         FAILURE_SESSION_IN_RECOVERY,
806         FAILURE_SESSION_RECOVERY_TIMEOUT,
807 };
808
809 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
810 {
811         struct Scsi_Host *host;
812         int reason = 0;
813         struct iscsi_session *session;
814         struct iscsi_conn *conn;
815         struct iscsi_cmd_task *ctask = NULL;
816
817         sc->scsi_done = done;
818         sc->result = 0;
819         sc->SCp.ptr = NULL;
820
821         host = sc->device->host;
822         session = iscsi_hostdata(host->hostdata);
823
824         spin_lock(&session->lock);
825
826         /*
827          * ISCSI_STATE_FAILED is a temp. state. The recovery
828          * code will decide what is best to do with command queued
829          * during this time
830          */
831         if (session->state != ISCSI_STATE_LOGGED_IN &&
832             session->state != ISCSI_STATE_FAILED) {
833                 /*
834                  * to handle the race between when we set the recovery state
835                  * and block the session we requeue here (commands could
836                  * be entering our queuecommand while a block is starting
837                  * up because the block code is not locked)
838                  */
839                 if (session->state == ISCSI_STATE_IN_RECOVERY) {
840                         reason = FAILURE_SESSION_IN_RECOVERY;
841                         goto reject;
842                 }
843
844                 if (session->state == ISCSI_STATE_RECOVERY_FAILED)
845                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
846                 else if (session->state == ISCSI_STATE_TERMINATE)
847                         reason = FAILURE_SESSION_TERMINATE;
848                 else
849                         reason = FAILURE_SESSION_FREED;
850                 goto fault;
851         }
852
853         conn = session->leadconn;
854         if (!conn) {
855                 reason = FAILURE_SESSION_FREED;
856                 goto fault;
857         }
858
859         if (iscsi_check_cmdsn_window_closed(conn)) {
860                 reason = FAILURE_WINDOW_CLOSED;
861                 goto reject;
862         }
863
864         if (!__kfifo_get(session->cmdpool.queue, (void*)&ctask,
865                          sizeof(void*))) {
866                 reason = FAILURE_OOM;
867                 goto reject;
868         }
869         session->queued_cmdsn++;
870
871         sc->SCp.phase = session->age;
872         sc->SCp.ptr = (char *)ctask;
873
874         atomic_set(&ctask->refcount, 1);
875         ctask->state = ISCSI_TASK_PENDING;
876         ctask->conn = conn;
877         ctask->sc = sc;
878         INIT_LIST_HEAD(&ctask->running);
879
880         list_add_tail(&ctask->running, &conn->xmitqueue);
881         spin_unlock(&session->lock);
882
883         scsi_queue_work(host, &conn->xmitwork);
884         return 0;
885
886 reject:
887         spin_unlock(&session->lock);
888         debug_scsi("cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason);
889         return SCSI_MLQUEUE_HOST_BUSY;
890
891 fault:
892         spin_unlock(&session->lock);
893         printk(KERN_ERR "iscsi: cmd 0x%x is not queued (%d)\n",
894                sc->cmnd[0], reason);
895         sc->result = (DID_NO_CONNECT << 16);
896         scsi_set_resid(sc, scsi_bufflen(sc));
897         sc->scsi_done(sc);
898         return 0;
899 }
900 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
901
902 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth)
903 {
904         if (depth > ISCSI_MAX_CMD_PER_LUN)
905                 depth = ISCSI_MAX_CMD_PER_LUN;
906         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
907         return sdev->queue_depth;
908 }
909 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
910
911 static struct iscsi_mgmt_task *
912 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
913                       char *data, uint32_t data_size)
914 {
915         struct iscsi_session *session = conn->session;
916         struct iscsi_mgmt_task *mtask;
917
918         if (session->state == ISCSI_STATE_TERMINATE)
919                 return NULL;
920
921         if (hdr->opcode == (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) ||
922             hdr->opcode == (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
923                 /*
924                  * Login and Text are sent serially, in
925                  * request-followed-by-response sequence.
926                  * Same mtask can be used. Same ITT must be used.
927                  * Note that login_mtask is preallocated at conn_create().
928                  */
929                 mtask = conn->login_mtask;
930         else {
931                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
932                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
933
934                 if (!__kfifo_get(session->mgmtpool.queue,
935                                  (void*)&mtask, sizeof(void*)))
936                         return NULL;
937         }
938
939         if (data_size) {
940                 memcpy(mtask->data, data, data_size);
941                 mtask->data_count = data_size;
942         } else
943                 mtask->data_count = 0;
944
945         memcpy(mtask->hdr, hdr, sizeof(struct iscsi_hdr));
946         INIT_LIST_HEAD(&mtask->running);
947         list_add_tail(&mtask->running, &conn->mgmtqueue);
948         return mtask;
949 }
950
951 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
952                         char *data, uint32_t data_size)
953 {
954         struct iscsi_conn *conn = cls_conn->dd_data;
955         struct iscsi_session *session = conn->session;
956         int err = 0;
957
958         spin_lock_bh(&session->lock);
959         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
960                 err = -EPERM;
961         spin_unlock_bh(&session->lock);
962         scsi_queue_work(session->host, &conn->xmitwork);
963         return err;
964 }
965 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
966
967 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
968 {
969         struct iscsi_session *session = class_to_transport_session(cls_session);
970
971         spin_lock_bh(&session->lock);
972         if (session->state != ISCSI_STATE_LOGGED_IN) {
973                 session->state = ISCSI_STATE_RECOVERY_FAILED;
974                 if (session->leadconn)
975                         wake_up(&session->leadconn->ehwait);
976         }
977         spin_unlock_bh(&session->lock);
978 }
979 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
980
981 int iscsi_eh_host_reset(struct scsi_cmnd *sc)
982 {
983         struct Scsi_Host *host = sc->device->host;
984         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
985         struct iscsi_conn *conn = session->leadconn;
986
987         spin_lock_bh(&session->lock);
988         if (session->state == ISCSI_STATE_TERMINATE) {
989 failed:
990                 debug_scsi("failing host reset: session terminated "
991                            "[CID %d age %d]\n", conn->id, session->age);
992                 spin_unlock_bh(&session->lock);
993                 return FAILED;
994         }
995
996         spin_unlock_bh(&session->lock);
997
998         /*
999          * we drop the lock here but the leadconn cannot be destoyed while
1000          * we are in the scsi eh
1001          */
1002         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1003
1004         debug_scsi("iscsi_eh_host_reset wait for relogin\n");
1005         wait_event_interruptible(conn->ehwait,
1006                                  session->state == ISCSI_STATE_TERMINATE ||
1007                                  session->state == ISCSI_STATE_LOGGED_IN ||
1008                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
1009         if (signal_pending(current))
1010                 flush_signals(current);
1011
1012         spin_lock_bh(&session->lock);
1013         if (session->state == ISCSI_STATE_LOGGED_IN)
1014                 printk(KERN_INFO "iscsi: host reset succeeded\n");
1015         else
1016                 goto failed;
1017         spin_unlock_bh(&session->lock);
1018
1019         return SUCCESS;
1020 }
1021 EXPORT_SYMBOL_GPL(iscsi_eh_host_reset);
1022
1023 static void iscsi_tmf_timedout(unsigned long data)
1024 {
1025         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1026         struct iscsi_session *session = conn->session;
1027
1028         spin_lock(&session->lock);
1029         if (conn->tmf_state == TMF_QUEUED) {
1030                 conn->tmf_state = TMF_TIMEDOUT;
1031                 debug_scsi("tmf timedout\n");
1032                 /* unblock eh_abort() */
1033                 wake_up(&conn->ehwait);
1034         }
1035         spin_unlock(&session->lock);
1036 }
1037
1038 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1039                                    struct iscsi_tm *hdr, int age)
1040 {
1041         struct iscsi_session *session = conn->session;
1042         struct iscsi_mgmt_task *mtask;
1043
1044         mtask = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1045                                       NULL, 0);
1046         if (!mtask) {
1047                 spin_unlock_bh(&session->lock);
1048                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1049                 spin_lock_bh(&session->lock);
1050                 debug_scsi("tmf exec failure\n");
1051                 return -EPERM;
1052         }
1053         conn->tmfcmd_pdus_cnt++;
1054         conn->tmf_timer.expires = 30 * HZ + jiffies;
1055         conn->tmf_timer.function = iscsi_tmf_timedout;
1056         conn->tmf_timer.data = (unsigned long)conn;
1057         add_timer(&conn->tmf_timer);
1058         debug_scsi("tmf set timeout\n");
1059
1060         spin_unlock_bh(&session->lock);
1061         mutex_unlock(&session->eh_mutex);
1062         scsi_queue_work(session->host, &conn->xmitwork);
1063
1064         /*
1065          * block eh thread until:
1066          *
1067          * 1) tmf response
1068          * 2) tmf timeout
1069          * 3) session is terminated or restarted or userspace has
1070          * given up on recovery
1071          */
1072         wait_event_interruptible(conn->ehwait, age != session->age ||
1073                                  session->state != ISCSI_STATE_LOGGED_IN ||
1074                                  conn->tmf_state != TMF_QUEUED);
1075         if (signal_pending(current))
1076                 flush_signals(current);
1077         del_timer_sync(&conn->tmf_timer);
1078
1079         mutex_lock(&session->eh_mutex);
1080         spin_lock_bh(&session->lock);
1081         /* if the session drops it will clean up the mtask */
1082         if (age != session->age ||
1083             session->state != ISCSI_STATE_LOGGED_IN)
1084                 return -ENOTCONN;
1085
1086         if (!list_empty(&mtask->running)) {
1087                 list_del_init(&mtask->running);
1088                 __kfifo_put(session->mgmtpool.queue, (void*)&mtask,
1089                             sizeof(void*));
1090         }
1091         return 0;
1092 }
1093
1094 /*
1095  * session lock must be held
1096  */
1097 static void fail_command(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1098                          int err)
1099 {
1100         struct scsi_cmnd *sc;
1101
1102         sc = ctask->sc;
1103         if (!sc)
1104                 return;
1105
1106         if (ctask->state == ISCSI_TASK_PENDING)
1107                 /*
1108                  * cmd never made it to the xmit thread, so we should not count
1109                  * the cmd in the sequencing
1110                  */
1111                 conn->session->queued_cmdsn--;
1112         else
1113                 conn->session->tt->cleanup_cmd_task(conn, ctask);
1114
1115         sc->result = err;
1116         scsi_set_resid(sc, scsi_bufflen(sc));
1117         if (conn->ctask == ctask)
1118                 conn->ctask = NULL;
1119         /* release ref from queuecommand */
1120         __iscsi_put_ctask(ctask);
1121 }
1122
1123 /*
1124  * Fail commands. session lock held and recv side suspended and xmit
1125  * thread flushed
1126  */
1127 static void fail_all_commands(struct iscsi_conn *conn, unsigned lun)
1128 {
1129         struct iscsi_cmd_task *ctask, *tmp;
1130
1131         if (conn->ctask && (conn->ctask->sc->device->lun == lun || lun == -1))
1132                 conn->ctask = NULL;
1133
1134         /* flush pending */
1135         list_for_each_entry_safe(ctask, tmp, &conn->xmitqueue, running) {
1136                 if (lun == ctask->sc->device->lun || lun == -1) {
1137                         debug_scsi("failing pending sc %p itt 0x%x\n",
1138                                    ctask->sc, ctask->itt);
1139                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1140                 }
1141         }
1142
1143         list_for_each_entry_safe(ctask, tmp, &conn->requeue, running) {
1144                 if (lun == ctask->sc->device->lun || lun == -1) {
1145                         debug_scsi("failing requeued sc %p itt 0x%x\n",
1146                                    ctask->sc, ctask->itt);
1147                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1148                 }
1149         }
1150
1151         /* fail all other running */
1152         list_for_each_entry_safe(ctask, tmp, &conn->run_list, running) {
1153                 if (lun == ctask->sc->device->lun || lun == -1) {
1154                         debug_scsi("failing in progress sc %p itt 0x%x\n",
1155                                    ctask->sc, ctask->itt);
1156                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1157                 }
1158         }
1159 }
1160
1161 static void iscsi_suspend_tx(struct iscsi_conn *conn)
1162 {
1163         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1164         scsi_flush_work(conn->session->host);
1165 }
1166
1167 static void iscsi_start_tx(struct iscsi_conn *conn)
1168 {
1169         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1170         scsi_queue_work(conn->session->host, &conn->xmitwork);
1171 }
1172
1173 static void iscsi_prep_abort_task_pdu(struct iscsi_cmd_task *ctask,
1174                                       struct iscsi_tm *hdr)
1175 {
1176         memset(hdr, 0, sizeof(*hdr));
1177         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1178         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
1179         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1180         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1181         hdr->rtt = ctask->hdr->itt;
1182         hdr->refcmdsn = ctask->hdr->cmdsn;
1183 }
1184
1185 int iscsi_eh_abort(struct scsi_cmnd *sc)
1186 {
1187         struct Scsi_Host *host = sc->device->host;
1188         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
1189         struct iscsi_conn *conn;
1190         struct iscsi_cmd_task *ctask;
1191         struct iscsi_tm *hdr;
1192         int rc, age;
1193
1194         mutex_lock(&session->eh_mutex);
1195         spin_lock_bh(&session->lock);
1196         /*
1197          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
1198          * got the command.
1199          */
1200         if (!sc->SCp.ptr) {
1201                 debug_scsi("sc never reached iscsi layer or it completed.\n");
1202                 spin_unlock_bh(&session->lock);
1203                 mutex_unlock(&session->eh_mutex);
1204                 return SUCCESS;
1205         }
1206
1207         /*
1208          * If we are not logged in or we have started a new session
1209          * then let the host reset code handle this
1210          */
1211         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
1212             sc->SCp.phase != session->age) {
1213                 spin_unlock_bh(&session->lock);
1214                 mutex_unlock(&session->eh_mutex);
1215                 return FAILED;
1216         }
1217
1218         conn = session->leadconn;
1219         conn->eh_abort_cnt++;
1220         age = session->age;
1221
1222         ctask = (struct iscsi_cmd_task *)sc->SCp.ptr;
1223         debug_scsi("aborting [sc %p itt 0x%x]\n", sc, ctask->itt);
1224
1225         /* ctask completed before time out */
1226         if (!ctask->sc) {
1227                 debug_scsi("sc completed while abort in progress\n");
1228                 goto success;
1229         }
1230
1231         if (ctask->state == ISCSI_TASK_PENDING) {
1232                 fail_command(conn, ctask, DID_ABORT << 16);
1233                 goto success;
1234         }
1235
1236         /* only have one tmf outstanding at a time */
1237         if (conn->tmf_state != TMF_INITIAL)
1238                 goto failed;
1239         conn->tmf_state = TMF_QUEUED;
1240
1241         hdr = &conn->tmhdr;
1242         iscsi_prep_abort_task_pdu(ctask, hdr);
1243
1244         if (iscsi_exec_task_mgmt_fn(conn, hdr, age)) {
1245                 rc = FAILED;
1246                 goto failed;
1247         }
1248
1249         switch (conn->tmf_state) {
1250         case TMF_SUCCESS:
1251                 spin_unlock_bh(&session->lock);
1252                 iscsi_suspend_tx(conn);
1253                 /*
1254                  * clean up task if aborted. grab the recv lock as a writer
1255                  */
1256                 write_lock_bh(conn->recv_lock);
1257                 spin_lock(&session->lock);
1258                 fail_command(conn, ctask, DID_ABORT << 16);
1259                 conn->tmf_state = TMF_INITIAL;
1260                 spin_unlock(&session->lock);
1261                 write_unlock_bh(conn->recv_lock);
1262                 iscsi_start_tx(conn);
1263                 goto success_unlocked;
1264         case TMF_TIMEDOUT:
1265                 spin_unlock_bh(&session->lock);
1266                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1267                 goto failed_unlocked;
1268         case TMF_NOT_FOUND:
1269                 if (!sc->SCp.ptr) {
1270                         conn->tmf_state = TMF_INITIAL;
1271                         /* ctask completed before tmf abort response */
1272                         debug_scsi("sc completed while abort in progress\n");
1273                         goto success;
1274                 }
1275                 /* fall through */
1276         default:
1277                 conn->tmf_state = TMF_INITIAL;
1278                 goto failed;
1279         }
1280
1281 success:
1282         spin_unlock_bh(&session->lock);
1283 success_unlocked:
1284         debug_scsi("abort success [sc %lx itt 0x%x]\n", (long)sc, ctask->itt);
1285         mutex_unlock(&session->eh_mutex);
1286         return SUCCESS;
1287
1288 failed:
1289         spin_unlock_bh(&session->lock);
1290 failed_unlocked:
1291         debug_scsi("abort failed [sc %p itt 0x%x]\n", sc,
1292                     ctask ? ctask->itt : 0);
1293         mutex_unlock(&session->eh_mutex);
1294         return FAILED;
1295 }
1296 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1297
1298 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
1299 {
1300         memset(hdr, 0, sizeof(*hdr));
1301         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1302         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
1303         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1304         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
1305         hdr->rtt = ISCSI_RESERVED_TAG;
1306 }
1307
1308 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
1309 {
1310         struct Scsi_Host *host = sc->device->host;
1311         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
1312         struct iscsi_conn *conn;
1313         struct iscsi_tm *hdr;
1314         int rc = FAILED;
1315
1316         debug_scsi("LU Reset [sc %p lun %u]\n", sc, sc->device->lun);
1317
1318         mutex_lock(&session->eh_mutex);
1319         spin_lock_bh(&session->lock);
1320         /*
1321          * Just check if we are not logged in. We cannot check for
1322          * the phase because the reset could come from a ioctl.
1323          */
1324         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
1325                 goto unlock;
1326         conn = session->leadconn;
1327
1328         /* only have one tmf outstanding at a time */
1329         if (conn->tmf_state != TMF_INITIAL)
1330                 goto unlock;
1331         conn->tmf_state = TMF_QUEUED;
1332
1333         hdr = &conn->tmhdr;
1334         iscsi_prep_lun_reset_pdu(sc, hdr);
1335
1336         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age)) {
1337                 rc = FAILED;
1338                 goto unlock;
1339         }
1340
1341         switch (conn->tmf_state) {
1342         case TMF_SUCCESS:
1343                 break;
1344         case TMF_TIMEDOUT:
1345                 spin_unlock_bh(&session->lock);
1346                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1347                 goto done;
1348         default:
1349                 conn->tmf_state = TMF_INITIAL;
1350                 goto unlock;
1351         }
1352
1353         rc = SUCCESS;
1354         spin_unlock_bh(&session->lock);
1355
1356         iscsi_suspend_tx(conn);
1357         /* need to grab the recv lock then session lock */
1358         write_lock_bh(conn->recv_lock);
1359         spin_lock(&session->lock);
1360         fail_all_commands(conn, sc->device->lun);
1361         conn->tmf_state = TMF_INITIAL;
1362         spin_unlock(&session->lock);
1363         write_unlock_bh(conn->recv_lock);
1364
1365         iscsi_start_tx(conn);
1366         goto done;
1367
1368 unlock:
1369         spin_unlock_bh(&session->lock);
1370 done:
1371         debug_scsi("iscsi_eh_device_reset %s\n",
1372                   rc == SUCCESS ? "SUCCESS" : "FAILED");
1373         mutex_unlock(&session->eh_mutex);
1374         return rc;
1375 }
1376 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
1377
1378 int
1379 iscsi_pool_init(struct iscsi_queue *q, int max, void ***items, int item_size)
1380 {
1381         int i;
1382
1383         *items = kmalloc(max * sizeof(void*), GFP_KERNEL);
1384         if (*items == NULL)
1385                 return -ENOMEM;
1386
1387         q->max = max;
1388         q->pool = kmalloc(max * sizeof(void*), GFP_KERNEL);
1389         if (q->pool == NULL) {
1390                 kfree(*items);
1391                 return -ENOMEM;
1392         }
1393
1394         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
1395                               GFP_KERNEL, NULL);
1396         if (q->queue == ERR_PTR(-ENOMEM)) {
1397                 kfree(q->pool);
1398                 kfree(*items);
1399                 return -ENOMEM;
1400         }
1401
1402         for (i = 0; i < max; i++) {
1403                 q->pool[i] = kmalloc(item_size, GFP_KERNEL);
1404                 if (q->pool[i] == NULL) {
1405                         int j;
1406
1407                         for (j = 0; j < i; j++)
1408                                 kfree(q->pool[j]);
1409
1410                         kfifo_free(q->queue);
1411                         kfree(q->pool);
1412                         kfree(*items);
1413                         return -ENOMEM;
1414                 }
1415                 memset(q->pool[i], 0, item_size);
1416                 (*items)[i] = q->pool[i];
1417                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
1418         }
1419         return 0;
1420 }
1421 EXPORT_SYMBOL_GPL(iscsi_pool_init);
1422
1423 void iscsi_pool_free(struct iscsi_queue *q, void **items)
1424 {
1425         int i;
1426
1427         for (i = 0; i < q->max; i++)
1428                 kfree(items[i]);
1429         kfree(q->pool);
1430         kfree(items);
1431 }
1432 EXPORT_SYMBOL_GPL(iscsi_pool_free);
1433
1434 /*
1435  * iSCSI Session's hostdata organization:
1436  *
1437  *    *------------------* <== hostdata_session(host->hostdata)
1438  *    | ptr to class sess|
1439  *    |------------------| <== iscsi_hostdata(host->hostdata)
1440  *    | iscsi_session    |
1441  *    *------------------*
1442  */
1443
1444 #define hostdata_privsize(_sz)  (sizeof(unsigned long) + _sz + \
1445                                  _sz % sizeof(unsigned long))
1446
1447 #define hostdata_session(_hostdata) (iscsi_ptr(*(unsigned long *)_hostdata))
1448
1449 /**
1450  * iscsi_session_setup - create iscsi cls session and host and session
1451  * @scsit: scsi transport template
1452  * @iscsit: iscsi transport template
1453  * @cmds_max: scsi host can queue
1454  * @qdepth: scsi host cmds per lun
1455  * @cmd_task_size: LLD ctask private data size
1456  * @mgmt_task_size: LLD mtask private data size
1457  * @initial_cmdsn: initial CmdSN
1458  * @hostno: host no allocated
1459  *
1460  * This can be used by software iscsi_transports that allocate
1461  * a session per scsi host.
1462  **/
1463 struct iscsi_cls_session *
1464 iscsi_session_setup(struct iscsi_transport *iscsit,
1465                     struct scsi_transport_template *scsit,
1466                     uint16_t cmds_max, uint16_t qdepth,
1467                     int cmd_task_size, int mgmt_task_size,
1468                     uint32_t initial_cmdsn, uint32_t *hostno)
1469 {
1470         struct Scsi_Host *shost;
1471         struct iscsi_session *session;
1472         struct iscsi_cls_session *cls_session;
1473         int cmd_i;
1474
1475         if (qdepth > ISCSI_MAX_CMD_PER_LUN || qdepth < 1) {
1476                 if (qdepth != 0)
1477                         printk(KERN_ERR "iscsi: invalid queue depth of %d. "
1478                               "Queue depth must be between 1 and %d.\n",
1479                               qdepth, ISCSI_MAX_CMD_PER_LUN);
1480                 qdepth = ISCSI_DEF_CMD_PER_LUN;
1481         }
1482
1483         if (cmds_max < 2 || (cmds_max & (cmds_max - 1)) ||
1484             cmds_max >= ISCSI_MGMT_ITT_OFFSET) {
1485                 if (cmds_max != 0)
1486                         printk(KERN_ERR "iscsi: invalid can_queue of %d. "
1487                                "can_queue must be a power of 2 and between "
1488                                "2 and %d - setting to %d.\n", cmds_max,
1489                                ISCSI_MGMT_ITT_OFFSET, ISCSI_DEF_XMIT_CMDS_MAX);
1490                 cmds_max = ISCSI_DEF_XMIT_CMDS_MAX;
1491         }
1492
1493         shost = scsi_host_alloc(iscsit->host_template,
1494                                 hostdata_privsize(sizeof(*session)));
1495         if (!shost)
1496                 return NULL;
1497
1498         /* the iscsi layer takes one task for reserve */
1499         shost->can_queue = cmds_max - 1;
1500         shost->cmd_per_lun = qdepth;
1501         shost->max_id = 1;
1502         shost->max_channel = 0;
1503         shost->max_lun = iscsit->max_lun;
1504         shost->max_cmd_len = iscsit->max_cmd_len;
1505         shost->transportt = scsit;
1506         shost->transportt->create_work_queue = 1;
1507         *hostno = shost->host_no;
1508
1509         session = iscsi_hostdata(shost->hostdata);
1510         memset(session, 0, sizeof(struct iscsi_session));
1511         session->host = shost;
1512         session->state = ISCSI_STATE_FREE;
1513         session->mgmtpool_max = ISCSI_MGMT_CMDS_MAX;
1514         session->cmds_max = cmds_max;
1515         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
1516         session->exp_cmdsn = initial_cmdsn + 1;
1517         session->max_cmdsn = initial_cmdsn + 1;
1518         session->max_r2t = 1;
1519         session->tt = iscsit;
1520         mutex_init(&session->eh_mutex);
1521
1522         /* initialize SCSI PDU commands pool */
1523         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
1524                             (void***)&session->cmds,
1525                             cmd_task_size + sizeof(struct iscsi_cmd_task)))
1526                 goto cmdpool_alloc_fail;
1527
1528         /* pre-format cmds pool with ITT */
1529         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1530                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1531
1532                 if (cmd_task_size)
1533                         ctask->dd_data = &ctask[1];
1534                 ctask->itt = cmd_i;
1535                 INIT_LIST_HEAD(&ctask->running);
1536         }
1537
1538         spin_lock_init(&session->lock);
1539
1540         /* initialize immediate command pool */
1541         if (iscsi_pool_init(&session->mgmtpool, session->mgmtpool_max,
1542                            (void***)&session->mgmt_cmds,
1543                            mgmt_task_size + sizeof(struct iscsi_mgmt_task)))
1544                 goto mgmtpool_alloc_fail;
1545
1546
1547         /* pre-format immediate cmds pool with ITT */
1548         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
1549                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
1550
1551                 if (mgmt_task_size)
1552                         mtask->dd_data = &mtask[1];
1553                 mtask->itt = ISCSI_MGMT_ITT_OFFSET + cmd_i;
1554                 INIT_LIST_HEAD(&mtask->running);
1555         }
1556
1557         if (scsi_add_host(shost, NULL))
1558                 goto add_host_fail;
1559
1560         if (!try_module_get(iscsit->owner))
1561                 goto cls_session_fail;
1562
1563         cls_session = iscsi_create_session(shost, iscsit, 0);
1564         if (!cls_session)
1565                 goto module_put;
1566         *(unsigned long*)shost->hostdata = (unsigned long)cls_session;
1567
1568         return cls_session;
1569
1570 module_put:
1571         module_put(iscsit->owner);
1572 cls_session_fail:
1573         scsi_remove_host(shost);
1574 add_host_fail:
1575         iscsi_pool_free(&session->mgmtpool, (void**)session->mgmt_cmds);
1576 mgmtpool_alloc_fail:
1577         iscsi_pool_free(&session->cmdpool, (void**)session->cmds);
1578 cmdpool_alloc_fail:
1579         scsi_host_put(shost);
1580         return NULL;
1581 }
1582 EXPORT_SYMBOL_GPL(iscsi_session_setup);
1583
1584 /**
1585  * iscsi_session_teardown - destroy session, host, and cls_session
1586  * shost: scsi host
1587  *
1588  * This can be used by software iscsi_transports that allocate
1589  * a session per scsi host.
1590  **/
1591 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
1592 {
1593         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
1594         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
1595         struct module *owner = cls_session->transport->owner;
1596
1597         iscsi_unblock_session(cls_session);
1598         scsi_remove_host(shost);
1599
1600         iscsi_pool_free(&session->mgmtpool, (void**)session->mgmt_cmds);
1601         iscsi_pool_free(&session->cmdpool, (void**)session->cmds);
1602
1603         kfree(session->password);
1604         kfree(session->password_in);
1605         kfree(session->username);
1606         kfree(session->username_in);
1607         kfree(session->targetname);
1608         kfree(session->netdev);
1609         kfree(session->hwaddress);
1610         kfree(session->initiatorname);
1611
1612         iscsi_destroy_session(cls_session);
1613         scsi_host_put(shost);
1614         module_put(owner);
1615 }
1616 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
1617
1618 /**
1619  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
1620  * @cls_session: iscsi_cls_session
1621  * @conn_idx: cid
1622  **/
1623 struct iscsi_cls_conn *
1624 iscsi_conn_setup(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1625 {
1626         struct iscsi_session *session = class_to_transport_session(cls_session);
1627         struct iscsi_conn *conn;
1628         struct iscsi_cls_conn *cls_conn;
1629         char *data;
1630
1631         cls_conn = iscsi_create_conn(cls_session, conn_idx);
1632         if (!cls_conn)
1633                 return NULL;
1634         conn = cls_conn->dd_data;
1635         memset(conn, 0, sizeof(*conn));
1636
1637         conn->session = session;
1638         conn->cls_conn = cls_conn;
1639         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
1640         conn->id = conn_idx;
1641         conn->exp_statsn = 0;
1642         conn->tmf_state = TMF_INITIAL;
1643         INIT_LIST_HEAD(&conn->run_list);
1644         INIT_LIST_HEAD(&conn->mgmt_run_list);
1645         INIT_LIST_HEAD(&conn->mgmtqueue);
1646         INIT_LIST_HEAD(&conn->xmitqueue);
1647         INIT_LIST_HEAD(&conn->requeue);
1648         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
1649
1650         /* allocate login_mtask used for the login/text sequences */
1651         spin_lock_bh(&session->lock);
1652         if (!__kfifo_get(session->mgmtpool.queue,
1653                          (void*)&conn->login_mtask,
1654                          sizeof(void*))) {
1655                 spin_unlock_bh(&session->lock);
1656                 goto login_mtask_alloc_fail;
1657         }
1658         spin_unlock_bh(&session->lock);
1659
1660         data = kmalloc(ISCSI_DEF_MAX_RECV_SEG_LEN, GFP_KERNEL);
1661         if (!data)
1662                 goto login_mtask_data_alloc_fail;
1663         conn->login_mtask->data = conn->data = data;
1664
1665         init_timer(&conn->tmf_timer);
1666         init_waitqueue_head(&conn->ehwait);
1667
1668         return cls_conn;
1669
1670 login_mtask_data_alloc_fail:
1671         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1672                     sizeof(void*));
1673 login_mtask_alloc_fail:
1674         iscsi_destroy_conn(cls_conn);
1675         return NULL;
1676 }
1677 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
1678
1679 /**
1680  * iscsi_conn_teardown - teardown iscsi connection
1681  * cls_conn: iscsi class connection
1682  *
1683  * TODO: we may need to make this into a two step process
1684  * like scsi-mls remove + put host
1685  */
1686 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
1687 {
1688         struct iscsi_conn *conn = cls_conn->dd_data;
1689         struct iscsi_session *session = conn->session;
1690         unsigned long flags;
1691
1692         spin_lock_bh(&session->lock);
1693         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
1694         if (session->leadconn == conn) {
1695                 /*
1696                  * leading connection? then give up on recovery.
1697                  */
1698                 session->state = ISCSI_STATE_TERMINATE;
1699                 wake_up(&conn->ehwait);
1700         }
1701         spin_unlock_bh(&session->lock);
1702
1703         /*
1704          * Block until all in-progress commands for this connection
1705          * time out or fail.
1706          */
1707         for (;;) {
1708                 spin_lock_irqsave(session->host->host_lock, flags);
1709                 if (!session->host->host_busy) { /* OK for ERL == 0 */
1710                         spin_unlock_irqrestore(session->host->host_lock, flags);
1711                         break;
1712                 }
1713                 spin_unlock_irqrestore(session->host->host_lock, flags);
1714                 msleep_interruptible(500);
1715                 printk(KERN_INFO "iscsi: scsi conn_destroy(): host_busy %d "
1716                        "host_failed %d\n", session->host->host_busy,
1717                        session->host->host_failed);
1718                 /*
1719                  * force eh_abort() to unblock
1720                  */
1721                 wake_up(&conn->ehwait);
1722         }
1723
1724         /* flush queued up work because we free the connection below */
1725         iscsi_suspend_tx(conn);
1726
1727         spin_lock_bh(&session->lock);
1728         kfree(conn->data);
1729         kfree(conn->persistent_address);
1730         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1731                     sizeof(void*));
1732         if (session->leadconn == conn)
1733                 session->leadconn = NULL;
1734         spin_unlock_bh(&session->lock);
1735
1736         iscsi_destroy_conn(cls_conn);
1737 }
1738 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
1739
1740 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
1741 {
1742         struct iscsi_conn *conn = cls_conn->dd_data;
1743         struct iscsi_session *session = conn->session;
1744
1745         if (!session) {
1746                 printk(KERN_ERR "iscsi: can't start unbound connection\n");
1747                 return -EPERM;
1748         }
1749
1750         if ((session->imm_data_en || !session->initial_r2t_en) &&
1751              session->first_burst > session->max_burst) {
1752                 printk("iscsi: invalid burst lengths: "
1753                        "first_burst %d max_burst %d\n",
1754                        session->first_burst, session->max_burst);
1755                 return -EINVAL;
1756         }
1757
1758         spin_lock_bh(&session->lock);
1759         conn->c_stage = ISCSI_CONN_STARTED;
1760         session->state = ISCSI_STATE_LOGGED_IN;
1761         session->queued_cmdsn = session->cmdsn;
1762
1763         switch(conn->stop_stage) {
1764         case STOP_CONN_RECOVER:
1765                 /*
1766                  * unblock eh_abort() if it is blocked. re-try all
1767                  * commands after successful recovery
1768                  */
1769                 conn->stop_stage = 0;
1770                 conn->tmf_state = TMF_INITIAL;
1771                 session->age++;
1772                 spin_unlock_bh(&session->lock);
1773
1774                 iscsi_unblock_session(session_to_cls(session));
1775                 wake_up(&conn->ehwait);
1776                 return 0;
1777         case STOP_CONN_TERM:
1778                 conn->stop_stage = 0;
1779                 break;
1780         default:
1781                 break;
1782         }
1783         spin_unlock_bh(&session->lock);
1784
1785         return 0;
1786 }
1787 EXPORT_SYMBOL_GPL(iscsi_conn_start);
1788
1789 static void
1790 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
1791 {
1792         struct iscsi_mgmt_task *mtask, *tmp;
1793
1794         /* handle pending */
1795         list_for_each_entry_safe(mtask, tmp, &conn->mgmtqueue, running) {
1796                 debug_scsi("flushing pending mgmt task itt 0x%x\n", mtask->itt);
1797                 list_del_init(&mtask->running);
1798                 if (mtask == conn->login_mtask)
1799                         continue;
1800                 __kfifo_put(session->mgmtpool.queue, (void*)&mtask,
1801                             sizeof(void*));
1802         }
1803
1804         /* handle running */
1805         list_for_each_entry_safe(mtask, tmp, &conn->mgmt_run_list, running) {
1806                 debug_scsi("flushing running mgmt task itt 0x%x\n", mtask->itt);
1807                 list_del_init(&mtask->running);
1808
1809                 if (mtask == conn->login_mtask)
1810                         continue;
1811                 __kfifo_put(session->mgmtpool.queue, (void*)&mtask,
1812                            sizeof(void*));
1813         }
1814
1815         conn->mtask = NULL;
1816 }
1817
1818 static void iscsi_start_session_recovery(struct iscsi_session *session,
1819                                          struct iscsi_conn *conn, int flag)
1820 {
1821         int old_stop_stage;
1822
1823         mutex_lock(&session->eh_mutex);
1824         spin_lock_bh(&session->lock);
1825         if (conn->stop_stage == STOP_CONN_TERM) {
1826                 spin_unlock_bh(&session->lock);
1827                 mutex_unlock(&session->eh_mutex);
1828                 return;
1829         }
1830
1831         /*
1832          * The LLD either freed/unset the lock on us, or userspace called
1833          * stop but did not create a proper connection (connection was never
1834          * bound or it was unbound then stop was called).
1835          */
1836         if (!conn->recv_lock) {
1837                 spin_unlock_bh(&session->lock);
1838                 mutex_unlock(&session->eh_mutex);
1839                 return;
1840         }
1841
1842         /*
1843          * When this is called for the in_login state, we only want to clean
1844          * up the login task and connection. We do not need to block and set
1845          * the recovery state again
1846          */
1847         if (flag == STOP_CONN_TERM)
1848                 session->state = ISCSI_STATE_TERMINATE;
1849         else if (conn->stop_stage != STOP_CONN_RECOVER)
1850                 session->state = ISCSI_STATE_IN_RECOVERY;
1851
1852         old_stop_stage = conn->stop_stage;
1853         conn->stop_stage = flag;
1854         conn->c_stage = ISCSI_CONN_STOPPED;
1855         spin_unlock_bh(&session->lock);
1856
1857         iscsi_suspend_tx(conn);
1858
1859         write_lock_bh(conn->recv_lock);
1860         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1861         write_unlock_bh(conn->recv_lock);
1862
1863         /*
1864          * for connection level recovery we should not calculate
1865          * header digest. conn->hdr_size used for optimization
1866          * in hdr_extract() and will be re-negotiated at
1867          * set_param() time.
1868          */
1869         if (flag == STOP_CONN_RECOVER) {
1870                 conn->hdrdgst_en = 0;
1871                 conn->datadgst_en = 0;
1872                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
1873                     old_stop_stage != STOP_CONN_RECOVER) {
1874                         debug_scsi("blocking session\n");
1875                         iscsi_block_session(session_to_cls(session));
1876                 }
1877         }
1878
1879         /*
1880          * flush queues.
1881          */
1882         spin_lock_bh(&session->lock);
1883         fail_all_commands(conn, -1);
1884         flush_control_queues(session, conn);
1885         spin_unlock_bh(&session->lock);
1886         mutex_unlock(&session->eh_mutex);
1887 }
1888
1889 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1890 {
1891         struct iscsi_conn *conn = cls_conn->dd_data;
1892         struct iscsi_session *session = conn->session;
1893
1894         switch (flag) {
1895         case STOP_CONN_RECOVER:
1896         case STOP_CONN_TERM:
1897                 iscsi_start_session_recovery(session, conn, flag);
1898                 break;
1899         default:
1900                 printk(KERN_ERR "iscsi: invalid stop flag %d\n", flag);
1901         }
1902 }
1903 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
1904
1905 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
1906                     struct iscsi_cls_conn *cls_conn, int is_leading)
1907 {
1908         struct iscsi_session *session = class_to_transport_session(cls_session);
1909         struct iscsi_conn *conn = cls_conn->dd_data;
1910
1911         spin_lock_bh(&session->lock);
1912         if (is_leading)
1913                 session->leadconn = conn;
1914         spin_unlock_bh(&session->lock);
1915
1916         /*
1917          * Unblock xmitworker(), Login Phase will pass through.
1918          */
1919         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1920         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1921         return 0;
1922 }
1923 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
1924
1925
1926 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
1927                     enum iscsi_param param, char *buf, int buflen)
1928 {
1929         struct iscsi_conn *conn = cls_conn->dd_data;
1930         struct iscsi_session *session = conn->session;
1931         uint32_t value;
1932
1933         switch(param) {
1934         case ISCSI_PARAM_FAST_ABORT:
1935                 sscanf(buf, "%d", &session->fast_abort);
1936                 break;
1937         case ISCSI_PARAM_MAX_RECV_DLENGTH:
1938                 sscanf(buf, "%d", &conn->max_recv_dlength);
1939                 break;
1940         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
1941                 sscanf(buf, "%d", &conn->max_xmit_dlength);
1942                 break;
1943         case ISCSI_PARAM_HDRDGST_EN:
1944                 sscanf(buf, "%d", &conn->hdrdgst_en);
1945                 break;
1946         case ISCSI_PARAM_DATADGST_EN:
1947                 sscanf(buf, "%d", &conn->datadgst_en);
1948                 break;
1949         case ISCSI_PARAM_INITIAL_R2T_EN:
1950                 sscanf(buf, "%d", &session->initial_r2t_en);
1951                 break;
1952         case ISCSI_PARAM_MAX_R2T:
1953                 sscanf(buf, "%d", &session->max_r2t);
1954                 break;
1955         case ISCSI_PARAM_IMM_DATA_EN:
1956                 sscanf(buf, "%d", &session->imm_data_en);
1957                 break;
1958         case ISCSI_PARAM_FIRST_BURST:
1959                 sscanf(buf, "%d", &session->first_burst);
1960                 break;
1961         case ISCSI_PARAM_MAX_BURST:
1962                 sscanf(buf, "%d", &session->max_burst);
1963                 break;
1964         case ISCSI_PARAM_PDU_INORDER_EN:
1965                 sscanf(buf, "%d", &session->pdu_inorder_en);
1966                 break;
1967         case ISCSI_PARAM_DATASEQ_INORDER_EN:
1968                 sscanf(buf, "%d", &session->dataseq_inorder_en);
1969                 break;
1970         case ISCSI_PARAM_ERL:
1971                 sscanf(buf, "%d", &session->erl);
1972                 break;
1973         case ISCSI_PARAM_IFMARKER_EN:
1974                 sscanf(buf, "%d", &value);
1975                 BUG_ON(value);
1976                 break;
1977         case ISCSI_PARAM_OFMARKER_EN:
1978                 sscanf(buf, "%d", &value);
1979                 BUG_ON(value);
1980                 break;
1981         case ISCSI_PARAM_EXP_STATSN:
1982                 sscanf(buf, "%u", &conn->exp_statsn);
1983                 break;
1984         case ISCSI_PARAM_USERNAME:
1985                 kfree(session->username);
1986                 session->username = kstrdup(buf, GFP_KERNEL);
1987                 if (!session->username)
1988                         return -ENOMEM;
1989                 break;
1990         case ISCSI_PARAM_USERNAME_IN:
1991                 kfree(session->username_in);
1992                 session->username_in = kstrdup(buf, GFP_KERNEL);
1993                 if (!session->username_in)
1994                         return -ENOMEM;
1995                 break;
1996         case ISCSI_PARAM_PASSWORD:
1997                 kfree(session->password);
1998                 session->password = kstrdup(buf, GFP_KERNEL);
1999                 if (!session->password)
2000                         return -ENOMEM;
2001                 break;
2002         case ISCSI_PARAM_PASSWORD_IN:
2003                 kfree(session->password_in);
2004                 session->password_in = kstrdup(buf, GFP_KERNEL);
2005                 if (!session->password_in)
2006                         return -ENOMEM;
2007                 break;
2008         case ISCSI_PARAM_TARGET_NAME:
2009                 /* this should not change between logins */
2010                 if (session->targetname)
2011                         break;
2012
2013                 session->targetname = kstrdup(buf, GFP_KERNEL);
2014                 if (!session->targetname)
2015                         return -ENOMEM;
2016                 break;
2017         case ISCSI_PARAM_TPGT:
2018                 sscanf(buf, "%d", &session->tpgt);
2019                 break;
2020         case ISCSI_PARAM_PERSISTENT_PORT:
2021                 sscanf(buf, "%d", &conn->persistent_port);
2022                 break;
2023         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2024                 /*
2025                  * this is the address returned in discovery so it should
2026                  * not change between logins.
2027                  */
2028                 if (conn->persistent_address)
2029                         break;
2030
2031                 conn->persistent_address = kstrdup(buf, GFP_KERNEL);
2032                 if (!conn->persistent_address)
2033                         return -ENOMEM;
2034                 break;
2035         default:
2036                 return -ENOSYS;
2037         }
2038
2039         return 0;
2040 }
2041 EXPORT_SYMBOL_GPL(iscsi_set_param);
2042
2043 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
2044                             enum iscsi_param param, char *buf)
2045 {
2046         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
2047         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2048         int len;
2049
2050         switch(param) {
2051         case ISCSI_PARAM_FAST_ABORT:
2052                 len = sprintf(buf, "%d\n", session->fast_abort);
2053                 break;
2054         case ISCSI_PARAM_INITIAL_R2T_EN:
2055                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
2056                 break;
2057         case ISCSI_PARAM_MAX_R2T:
2058                 len = sprintf(buf, "%hu\n", session->max_r2t);
2059                 break;
2060         case ISCSI_PARAM_IMM_DATA_EN:
2061                 len = sprintf(buf, "%d\n", session->imm_data_en);
2062                 break;
2063         case ISCSI_PARAM_FIRST_BURST:
2064                 len = sprintf(buf, "%u\n", session->first_burst);
2065                 break;
2066         case ISCSI_PARAM_MAX_BURST:
2067                 len = sprintf(buf, "%u\n", session->max_burst);
2068                 break;
2069         case ISCSI_PARAM_PDU_INORDER_EN:
2070                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
2071                 break;
2072         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2073                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
2074                 break;
2075         case ISCSI_PARAM_ERL:
2076                 len = sprintf(buf, "%d\n", session->erl);
2077                 break;
2078         case ISCSI_PARAM_TARGET_NAME:
2079                 len = sprintf(buf, "%s\n", session->targetname);
2080                 break;
2081         case ISCSI_PARAM_TPGT:
2082                 len = sprintf(buf, "%d\n", session->tpgt);
2083                 break;
2084         case ISCSI_PARAM_USERNAME:
2085                 len = sprintf(buf, "%s\n", session->username);
2086                 break;
2087         case ISCSI_PARAM_USERNAME_IN:
2088                 len = sprintf(buf, "%s\n", session->username_in);
2089                 break;
2090         case ISCSI_PARAM_PASSWORD:
2091                 len = sprintf(buf, "%s\n", session->password);
2092                 break;
2093         case ISCSI_PARAM_PASSWORD_IN:
2094                 len = sprintf(buf, "%s\n", session->password_in);
2095                 break;
2096         default:
2097                 return -ENOSYS;
2098         }
2099
2100         return len;
2101 }
2102 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
2103
2104 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
2105                          enum iscsi_param param, char *buf)
2106 {
2107         struct iscsi_conn *conn = cls_conn->dd_data;
2108         int len;
2109
2110         switch(param) {
2111         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2112                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
2113                 break;
2114         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2115                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
2116                 break;
2117         case ISCSI_PARAM_HDRDGST_EN:
2118                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
2119                 break;
2120         case ISCSI_PARAM_DATADGST_EN:
2121                 len = sprintf(buf, "%d\n", conn->datadgst_en);
2122                 break;
2123         case ISCSI_PARAM_IFMARKER_EN:
2124                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
2125                 break;
2126         case ISCSI_PARAM_OFMARKER_EN:
2127                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
2128                 break;
2129         case ISCSI_PARAM_EXP_STATSN:
2130                 len = sprintf(buf, "%u\n", conn->exp_statsn);
2131                 break;
2132         case ISCSI_PARAM_PERSISTENT_PORT:
2133                 len = sprintf(buf, "%d\n", conn->persistent_port);
2134                 break;
2135         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2136                 len = sprintf(buf, "%s\n", conn->persistent_address);
2137                 break;
2138         default:
2139                 return -ENOSYS;
2140         }
2141
2142         return len;
2143 }
2144 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
2145
2146 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2147                          char *buf)
2148 {
2149         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2150         int len;
2151
2152         switch (param) {
2153         case ISCSI_HOST_PARAM_NETDEV_NAME:
2154                 if (!session->netdev)
2155                         len = sprintf(buf, "%s\n", "default");
2156                 else
2157                         len = sprintf(buf, "%s\n", session->netdev);
2158                 break;
2159         case ISCSI_HOST_PARAM_HWADDRESS:
2160                 if (!session->hwaddress)
2161                         len = sprintf(buf, "%s\n", "default");
2162                 else
2163                         len = sprintf(buf, "%s\n", session->hwaddress);
2164                 break;
2165         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2166                 if (!session->initiatorname)
2167                         len = sprintf(buf, "%s\n", "unknown");
2168                 else
2169                         len = sprintf(buf, "%s\n", session->initiatorname);
2170                 break;
2171
2172         default:
2173                 return -ENOSYS;
2174         }
2175
2176         return len;
2177 }
2178 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
2179
2180 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2181                          char *buf, int buflen)
2182 {
2183         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2184
2185         switch (param) {
2186         case ISCSI_HOST_PARAM_NETDEV_NAME:
2187                 if (!session->netdev)
2188                         session->netdev = kstrdup(buf, GFP_KERNEL);
2189                 break;
2190         case ISCSI_HOST_PARAM_HWADDRESS:
2191                 if (!session->hwaddress)
2192                         session->hwaddress = kstrdup(buf, GFP_KERNEL);
2193                 break;
2194         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2195                 if (!session->initiatorname)
2196                         session->initiatorname = kstrdup(buf, GFP_KERNEL);
2197                 break;
2198         default:
2199                 return -ENOSYS;
2200         }
2201
2202         return 0;
2203 }
2204 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
2205
2206 MODULE_AUTHOR("Mike Christie");
2207 MODULE_DESCRIPTION("iSCSI library functions");
2208 MODULE_LICENSE("GPL");