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