[SCSI] libiscsi: fix shutdown
[firefly-linux-kernel-4.4.55.git] / 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         mutex_lock(&session->eh_mutex);
1083         spin_lock_bh(&session->lock);
1084         if (session->state == ISCSI_STATE_TERMINATE) {
1085 failed:
1086                 debug_scsi("failing host reset: session terminated "
1087                            "[CID %d age %d]\n", conn->id, session->age);
1088                 spin_unlock_bh(&session->lock);
1089                 mutex_unlock(&session->eh_mutex);
1090                 return FAILED;
1091         }
1092
1093         spin_unlock_bh(&session->lock);
1094         mutex_unlock(&session->eh_mutex);
1095         /*
1096          * we drop the lock here but the leadconn cannot be destoyed while
1097          * we are in the scsi eh
1098          */
1099         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1100
1101         debug_scsi("iscsi_eh_host_reset wait for relogin\n");
1102         wait_event_interruptible(conn->ehwait,
1103                                  session->state == ISCSI_STATE_TERMINATE ||
1104                                  session->state == ISCSI_STATE_LOGGED_IN ||
1105                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
1106         if (signal_pending(current))
1107                 flush_signals(current);
1108
1109         mutex_lock(&session->eh_mutex);
1110         spin_lock_bh(&session->lock);
1111         if (session->state == ISCSI_STATE_LOGGED_IN)
1112                 printk(KERN_INFO "iscsi: host reset succeeded\n");
1113         else
1114                 goto failed;
1115         spin_unlock_bh(&session->lock);
1116         mutex_unlock(&session->eh_mutex);
1117         return SUCCESS;
1118 }
1119 EXPORT_SYMBOL_GPL(iscsi_eh_host_reset);
1120
1121 static void iscsi_tmf_timedout(unsigned long data)
1122 {
1123         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1124         struct iscsi_session *session = conn->session;
1125
1126         spin_lock(&session->lock);
1127         if (conn->tmf_state == TMF_QUEUED) {
1128                 conn->tmf_state = TMF_TIMEDOUT;
1129                 debug_scsi("tmf timedout\n");
1130                 /* unblock eh_abort() */
1131                 wake_up(&conn->ehwait);
1132         }
1133         spin_unlock(&session->lock);
1134 }
1135
1136 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1137                                    struct iscsi_tm *hdr, int age)
1138 {
1139         struct iscsi_session *session = conn->session;
1140         struct iscsi_mgmt_task *mtask;
1141
1142         mtask = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1143                                       NULL, 0);
1144         if (!mtask) {
1145                 spin_unlock_bh(&session->lock);
1146                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1147                 spin_lock_bh(&session->lock);
1148                 debug_scsi("tmf exec failure\n");
1149                 return -EPERM;
1150         }
1151         conn->tmfcmd_pdus_cnt++;
1152         conn->tmf_timer.expires = 30 * HZ + jiffies;
1153         conn->tmf_timer.function = iscsi_tmf_timedout;
1154         conn->tmf_timer.data = (unsigned long)conn;
1155         add_timer(&conn->tmf_timer);
1156         debug_scsi("tmf set timeout\n");
1157
1158         spin_unlock_bh(&session->lock);
1159         mutex_unlock(&session->eh_mutex);
1160         scsi_queue_work(session->host, &conn->xmitwork);
1161
1162         /*
1163          * block eh thread until:
1164          *
1165          * 1) tmf response
1166          * 2) tmf timeout
1167          * 3) session is terminated or restarted or userspace has
1168          * given up on recovery
1169          */
1170         wait_event_interruptible(conn->ehwait, age != session->age ||
1171                                  session->state != ISCSI_STATE_LOGGED_IN ||
1172                                  conn->tmf_state != TMF_QUEUED);
1173         if (signal_pending(current))
1174                 flush_signals(current);
1175         del_timer_sync(&conn->tmf_timer);
1176
1177         mutex_lock(&session->eh_mutex);
1178         spin_lock_bh(&session->lock);
1179         /* if the session drops it will clean up the mtask */
1180         if (age != session->age ||
1181             session->state != ISCSI_STATE_LOGGED_IN)
1182                 return -ENOTCONN;
1183         return 0;
1184 }
1185
1186 /*
1187  * Fail commands. session lock held and recv side suspended and xmit
1188  * thread flushed
1189  */
1190 static void fail_all_commands(struct iscsi_conn *conn, unsigned lun)
1191 {
1192         struct iscsi_cmd_task *ctask, *tmp;
1193
1194         if (conn->ctask && (conn->ctask->sc->device->lun == lun || lun == -1))
1195                 conn->ctask = NULL;
1196
1197         /* flush pending */
1198         list_for_each_entry_safe(ctask, tmp, &conn->xmitqueue, running) {
1199                 if (lun == ctask->sc->device->lun || lun == -1) {
1200                         debug_scsi("failing pending sc %p itt 0x%x\n",
1201                                    ctask->sc, ctask->itt);
1202                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1203                 }
1204         }
1205
1206         list_for_each_entry_safe(ctask, tmp, &conn->requeue, running) {
1207                 if (lun == ctask->sc->device->lun || lun == -1) {
1208                         debug_scsi("failing requeued sc %p itt 0x%x\n",
1209                                    ctask->sc, ctask->itt);
1210                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1211                 }
1212         }
1213
1214         /* fail all other running */
1215         list_for_each_entry_safe(ctask, tmp, &conn->run_list, running) {
1216                 if (lun == ctask->sc->device->lun || lun == -1) {
1217                         debug_scsi("failing in progress sc %p itt 0x%x\n",
1218                                    ctask->sc, ctask->itt);
1219                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1220                 }
1221         }
1222 }
1223
1224 static void iscsi_suspend_tx(struct iscsi_conn *conn)
1225 {
1226         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1227         scsi_flush_work(conn->session->host);
1228 }
1229
1230 static void iscsi_start_tx(struct iscsi_conn *conn)
1231 {
1232         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1233         scsi_queue_work(conn->session->host, &conn->xmitwork);
1234 }
1235
1236 static void iscsi_prep_abort_task_pdu(struct iscsi_cmd_task *ctask,
1237                                       struct iscsi_tm *hdr)
1238 {
1239         memset(hdr, 0, sizeof(*hdr));
1240         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1241         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
1242         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1243         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1244         hdr->rtt = ctask->hdr->itt;
1245         hdr->refcmdsn = ctask->hdr->cmdsn;
1246 }
1247
1248 int iscsi_eh_abort(struct scsi_cmnd *sc)
1249 {
1250         struct Scsi_Host *host = sc->device->host;
1251         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
1252         struct iscsi_conn *conn;
1253         struct iscsi_cmd_task *ctask;
1254         struct iscsi_tm *hdr;
1255         int rc, age;
1256
1257         mutex_lock(&session->eh_mutex);
1258         spin_lock_bh(&session->lock);
1259         /*
1260          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
1261          * got the command.
1262          */
1263         if (!sc->SCp.ptr) {
1264                 debug_scsi("sc never reached iscsi layer or it completed.\n");
1265                 spin_unlock_bh(&session->lock);
1266                 mutex_unlock(&session->eh_mutex);
1267                 return SUCCESS;
1268         }
1269
1270         /*
1271          * If we are not logged in or we have started a new session
1272          * then let the host reset code handle this
1273          */
1274         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
1275             sc->SCp.phase != session->age) {
1276                 spin_unlock_bh(&session->lock);
1277                 mutex_unlock(&session->eh_mutex);
1278                 return FAILED;
1279         }
1280
1281         conn = session->leadconn;
1282         conn->eh_abort_cnt++;
1283         age = session->age;
1284
1285         ctask = (struct iscsi_cmd_task *)sc->SCp.ptr;
1286         debug_scsi("aborting [sc %p itt 0x%x]\n", sc, ctask->itt);
1287
1288         /* ctask completed before time out */
1289         if (!ctask->sc) {
1290                 debug_scsi("sc completed while abort in progress\n");
1291                 goto success;
1292         }
1293
1294         if (ctask->state == ISCSI_TASK_PENDING) {
1295                 fail_command(conn, ctask, DID_ABORT << 16);
1296                 goto success;
1297         }
1298
1299         /* only have one tmf outstanding at a time */
1300         if (conn->tmf_state != TMF_INITIAL)
1301                 goto failed;
1302         conn->tmf_state = TMF_QUEUED;
1303
1304         hdr = &conn->tmhdr;
1305         iscsi_prep_abort_task_pdu(ctask, hdr);
1306
1307         if (iscsi_exec_task_mgmt_fn(conn, hdr, age)) {
1308                 rc = FAILED;
1309                 goto failed;
1310         }
1311
1312         switch (conn->tmf_state) {
1313         case TMF_SUCCESS:
1314                 spin_unlock_bh(&session->lock);
1315                 iscsi_suspend_tx(conn);
1316                 /*
1317                  * clean up task if aborted. grab the recv lock as a writer
1318                  */
1319                 write_lock_bh(conn->recv_lock);
1320                 spin_lock(&session->lock);
1321                 fail_command(conn, ctask, DID_ABORT << 16);
1322                 conn->tmf_state = TMF_INITIAL;
1323                 spin_unlock(&session->lock);
1324                 write_unlock_bh(conn->recv_lock);
1325                 iscsi_start_tx(conn);
1326                 goto success_unlocked;
1327         case TMF_TIMEDOUT:
1328                 spin_unlock_bh(&session->lock);
1329                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1330                 goto failed_unlocked;
1331         case TMF_NOT_FOUND:
1332                 if (!sc->SCp.ptr) {
1333                         conn->tmf_state = TMF_INITIAL;
1334                         /* ctask completed before tmf abort response */
1335                         debug_scsi("sc completed while abort in progress\n");
1336                         goto success;
1337                 }
1338                 /* fall through */
1339         default:
1340                 conn->tmf_state = TMF_INITIAL;
1341                 goto failed;
1342         }
1343
1344 success:
1345         spin_unlock_bh(&session->lock);
1346 success_unlocked:
1347         debug_scsi("abort success [sc %lx itt 0x%x]\n", (long)sc, ctask->itt);
1348         mutex_unlock(&session->eh_mutex);
1349         return SUCCESS;
1350
1351 failed:
1352         spin_unlock_bh(&session->lock);
1353 failed_unlocked:
1354         debug_scsi("abort failed [sc %p itt 0x%x]\n", sc,
1355                     ctask ? ctask->itt : 0);
1356         mutex_unlock(&session->eh_mutex);
1357         return FAILED;
1358 }
1359 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1360
1361 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
1362 {
1363         memset(hdr, 0, sizeof(*hdr));
1364         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1365         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
1366         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1367         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
1368         hdr->rtt = ISCSI_RESERVED_TAG;
1369 }
1370
1371 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
1372 {
1373         struct Scsi_Host *host = sc->device->host;
1374         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
1375         struct iscsi_conn *conn;
1376         struct iscsi_tm *hdr;
1377         int rc = FAILED;
1378
1379         debug_scsi("LU Reset [sc %p lun %u]\n", sc, sc->device->lun);
1380
1381         mutex_lock(&session->eh_mutex);
1382         spin_lock_bh(&session->lock);
1383         /*
1384          * Just check if we are not logged in. We cannot check for
1385          * the phase because the reset could come from a ioctl.
1386          */
1387         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
1388                 goto unlock;
1389         conn = session->leadconn;
1390
1391         /* only have one tmf outstanding at a time */
1392         if (conn->tmf_state != TMF_INITIAL)
1393                 goto unlock;
1394         conn->tmf_state = TMF_QUEUED;
1395
1396         hdr = &conn->tmhdr;
1397         iscsi_prep_lun_reset_pdu(sc, hdr);
1398
1399         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age)) {
1400                 rc = FAILED;
1401                 goto unlock;
1402         }
1403
1404         switch (conn->tmf_state) {
1405         case TMF_SUCCESS:
1406                 break;
1407         case TMF_TIMEDOUT:
1408                 spin_unlock_bh(&session->lock);
1409                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1410                 goto done;
1411         default:
1412                 conn->tmf_state = TMF_INITIAL;
1413                 goto unlock;
1414         }
1415
1416         rc = SUCCESS;
1417         spin_unlock_bh(&session->lock);
1418
1419         iscsi_suspend_tx(conn);
1420         /* need to grab the recv lock then session lock */
1421         write_lock_bh(conn->recv_lock);
1422         spin_lock(&session->lock);
1423         fail_all_commands(conn, sc->device->lun);
1424         conn->tmf_state = TMF_INITIAL;
1425         spin_unlock(&session->lock);
1426         write_unlock_bh(conn->recv_lock);
1427
1428         iscsi_start_tx(conn);
1429         goto done;
1430
1431 unlock:
1432         spin_unlock_bh(&session->lock);
1433 done:
1434         debug_scsi("iscsi_eh_device_reset %s\n",
1435                   rc == SUCCESS ? "SUCCESS" : "FAILED");
1436         mutex_unlock(&session->eh_mutex);
1437         return rc;
1438 }
1439 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
1440
1441 /*
1442  * Pre-allocate a pool of @max items of @item_size. By default, the pool
1443  * should be accessed via kfifo_{get,put} on q->queue.
1444  * Optionally, the caller can obtain the array of object pointers
1445  * by passing in a non-NULL @items pointer
1446  */
1447 int
1448 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
1449 {
1450         int i, num_arrays = 1;
1451
1452         memset(q, 0, sizeof(*q));
1453
1454         q->max = max;
1455
1456         /* If the user passed an items pointer, he wants a copy of
1457          * the array. */
1458         if (items)
1459                 num_arrays++;
1460         q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL);
1461         if (q->pool == NULL)
1462                 goto enomem;
1463
1464         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
1465                               GFP_KERNEL, NULL);
1466         if (q->queue == ERR_PTR(-ENOMEM))
1467                 goto enomem;
1468
1469         for (i = 0; i < max; i++) {
1470                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
1471                 if (q->pool[i] == NULL) {
1472                         q->max = i;
1473                         goto enomem;
1474                 }
1475                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
1476         }
1477
1478         if (items) {
1479                 *items = q->pool + max;
1480                 memcpy(*items, q->pool, max * sizeof(void *));
1481         }
1482
1483         return 0;
1484
1485 enomem:
1486         iscsi_pool_free(q);
1487         return -ENOMEM;
1488 }
1489 EXPORT_SYMBOL_GPL(iscsi_pool_init);
1490
1491 void iscsi_pool_free(struct iscsi_pool *q)
1492 {
1493         int i;
1494
1495         for (i = 0; i < q->max; i++)
1496                 kfree(q->pool[i]);
1497         if (q->pool)
1498                 kfree(q->pool);
1499 }
1500 EXPORT_SYMBOL_GPL(iscsi_pool_free);
1501
1502 /*
1503  * iSCSI Session's hostdata organization:
1504  *
1505  *    *------------------* <== hostdata_session(host->hostdata)
1506  *    | ptr to class sess|
1507  *    |------------------| <== iscsi_hostdata(host->hostdata)
1508  *    | iscsi_session    |
1509  *    *------------------*
1510  */
1511
1512 #define hostdata_privsize(_sz)  (sizeof(unsigned long) + _sz + \
1513                                  _sz % sizeof(unsigned long))
1514
1515 #define hostdata_session(_hostdata) (iscsi_ptr(*(unsigned long *)_hostdata))
1516
1517 /**
1518  * iscsi_session_setup - create iscsi cls session and host and session
1519  * @scsit: scsi transport template
1520  * @iscsit: iscsi transport template
1521  * @cmds_max: scsi host can queue
1522  * @qdepth: scsi host cmds per lun
1523  * @cmd_task_size: LLD ctask private data size
1524  * @mgmt_task_size: LLD mtask private data size
1525  * @initial_cmdsn: initial CmdSN
1526  * @hostno: host no allocated
1527  *
1528  * This can be used by software iscsi_transports that allocate
1529  * a session per scsi host.
1530  **/
1531 struct iscsi_cls_session *
1532 iscsi_session_setup(struct iscsi_transport *iscsit,
1533                     struct scsi_transport_template *scsit,
1534                     uint16_t cmds_max, uint16_t qdepth,
1535                     int cmd_task_size, int mgmt_task_size,
1536                     uint32_t initial_cmdsn, uint32_t *hostno)
1537 {
1538         struct Scsi_Host *shost;
1539         struct iscsi_session *session;
1540         struct iscsi_cls_session *cls_session;
1541         int cmd_i;
1542
1543         if (qdepth > ISCSI_MAX_CMD_PER_LUN || qdepth < 1) {
1544                 if (qdepth != 0)
1545                         printk(KERN_ERR "iscsi: invalid queue depth of %d. "
1546                               "Queue depth must be between 1 and %d.\n",
1547                               qdepth, ISCSI_MAX_CMD_PER_LUN);
1548                 qdepth = ISCSI_DEF_CMD_PER_LUN;
1549         }
1550
1551         if (cmds_max < 2 || (cmds_max & (cmds_max - 1)) ||
1552             cmds_max >= ISCSI_MGMT_ITT_OFFSET) {
1553                 if (cmds_max != 0)
1554                         printk(KERN_ERR "iscsi: invalid can_queue of %d. "
1555                                "can_queue must be a power of 2 and between "
1556                                "2 and %d - setting to %d.\n", cmds_max,
1557                                ISCSI_MGMT_ITT_OFFSET, ISCSI_DEF_XMIT_CMDS_MAX);
1558                 cmds_max = ISCSI_DEF_XMIT_CMDS_MAX;
1559         }
1560
1561         shost = scsi_host_alloc(iscsit->host_template,
1562                                 hostdata_privsize(sizeof(*session)));
1563         if (!shost)
1564                 return NULL;
1565
1566         /* the iscsi layer takes one task for reserve */
1567         shost->can_queue = cmds_max - 1;
1568         shost->cmd_per_lun = qdepth;
1569         shost->max_id = 1;
1570         shost->max_channel = 0;
1571         shost->max_lun = iscsit->max_lun;
1572         shost->max_cmd_len = iscsit->max_cmd_len;
1573         shost->transportt = scsit;
1574         shost->transportt->create_work_queue = 1;
1575         *hostno = shost->host_no;
1576
1577         session = iscsi_hostdata(shost->hostdata);
1578         memset(session, 0, sizeof(struct iscsi_session));
1579         session->host = shost;
1580         session->state = ISCSI_STATE_FREE;
1581         session->mgmtpool_max = ISCSI_MGMT_CMDS_MAX;
1582         session->cmds_max = cmds_max;
1583         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
1584         session->exp_cmdsn = initial_cmdsn + 1;
1585         session->max_cmdsn = initial_cmdsn + 1;
1586         session->max_r2t = 1;
1587         session->tt = iscsit;
1588         mutex_init(&session->eh_mutex);
1589
1590         /* initialize SCSI PDU commands pool */
1591         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
1592                             (void***)&session->cmds,
1593                             cmd_task_size + sizeof(struct iscsi_cmd_task)))
1594                 goto cmdpool_alloc_fail;
1595
1596         /* pre-format cmds pool with ITT */
1597         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1598                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1599
1600                 if (cmd_task_size)
1601                         ctask->dd_data = &ctask[1];
1602                 ctask->itt = cmd_i;
1603                 INIT_LIST_HEAD(&ctask->running);
1604         }
1605
1606         spin_lock_init(&session->lock);
1607
1608         /* initialize immediate command pool */
1609         if (iscsi_pool_init(&session->mgmtpool, session->mgmtpool_max,
1610                            (void***)&session->mgmt_cmds,
1611                            mgmt_task_size + sizeof(struct iscsi_mgmt_task)))
1612                 goto mgmtpool_alloc_fail;
1613
1614
1615         /* pre-format immediate cmds pool with ITT */
1616         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
1617                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
1618
1619                 if (mgmt_task_size)
1620                         mtask->dd_data = &mtask[1];
1621                 mtask->itt = ISCSI_MGMT_ITT_OFFSET + cmd_i;
1622                 INIT_LIST_HEAD(&mtask->running);
1623         }
1624
1625         if (scsi_add_host(shost, NULL))
1626                 goto add_host_fail;
1627
1628         if (!try_module_get(iscsit->owner))
1629                 goto cls_session_fail;
1630
1631         cls_session = iscsi_create_session(shost, iscsit, 0);
1632         if (!cls_session)
1633                 goto module_put;
1634         *(unsigned long*)shost->hostdata = (unsigned long)cls_session;
1635
1636         return cls_session;
1637
1638 module_put:
1639         module_put(iscsit->owner);
1640 cls_session_fail:
1641         scsi_remove_host(shost);
1642 add_host_fail:
1643         iscsi_pool_free(&session->mgmtpool);
1644 mgmtpool_alloc_fail:
1645         iscsi_pool_free(&session->cmdpool);
1646 cmdpool_alloc_fail:
1647         scsi_host_put(shost);
1648         return NULL;
1649 }
1650 EXPORT_SYMBOL_GPL(iscsi_session_setup);
1651
1652 /**
1653  * iscsi_session_teardown - destroy session, host, and cls_session
1654  * shost: scsi host
1655  *
1656  * This can be used by software iscsi_transports that allocate
1657  * a session per scsi host.
1658  **/
1659 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
1660 {
1661         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
1662         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
1663         struct module *owner = cls_session->transport->owner;
1664
1665         iscsi_remove_session(cls_session);
1666         scsi_remove_host(shost);
1667
1668         iscsi_pool_free(&session->mgmtpool);
1669         iscsi_pool_free(&session->cmdpool);
1670
1671         kfree(session->password);
1672         kfree(session->password_in);
1673         kfree(session->username);
1674         kfree(session->username_in);
1675         kfree(session->targetname);
1676         kfree(session->netdev);
1677         kfree(session->hwaddress);
1678         kfree(session->initiatorname);
1679
1680         iscsi_free_session(cls_session);
1681         scsi_host_put(shost);
1682         module_put(owner);
1683 }
1684 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
1685
1686 /**
1687  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
1688  * @cls_session: iscsi_cls_session
1689  * @conn_idx: cid
1690  **/
1691 struct iscsi_cls_conn *
1692 iscsi_conn_setup(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1693 {
1694         struct iscsi_session *session = class_to_transport_session(cls_session);
1695         struct iscsi_conn *conn;
1696         struct iscsi_cls_conn *cls_conn;
1697         char *data;
1698
1699         cls_conn = iscsi_create_conn(cls_session, conn_idx);
1700         if (!cls_conn)
1701                 return NULL;
1702         conn = cls_conn->dd_data;
1703         memset(conn, 0, sizeof(*conn));
1704
1705         conn->session = session;
1706         conn->cls_conn = cls_conn;
1707         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
1708         conn->id = conn_idx;
1709         conn->exp_statsn = 0;
1710         conn->tmf_state = TMF_INITIAL;
1711         INIT_LIST_HEAD(&conn->run_list);
1712         INIT_LIST_HEAD(&conn->mgmt_run_list);
1713         INIT_LIST_HEAD(&conn->mgmtqueue);
1714         INIT_LIST_HEAD(&conn->xmitqueue);
1715         INIT_LIST_HEAD(&conn->requeue);
1716         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
1717
1718         /* allocate login_mtask used for the login/text sequences */
1719         spin_lock_bh(&session->lock);
1720         if (!__kfifo_get(session->mgmtpool.queue,
1721                          (void*)&conn->login_mtask,
1722                          sizeof(void*))) {
1723                 spin_unlock_bh(&session->lock);
1724                 goto login_mtask_alloc_fail;
1725         }
1726         spin_unlock_bh(&session->lock);
1727
1728         data = kmalloc(ISCSI_DEF_MAX_RECV_SEG_LEN, GFP_KERNEL);
1729         if (!data)
1730                 goto login_mtask_data_alloc_fail;
1731         conn->login_mtask->data = conn->data = data;
1732
1733         init_timer(&conn->tmf_timer);
1734         init_waitqueue_head(&conn->ehwait);
1735
1736         return cls_conn;
1737
1738 login_mtask_data_alloc_fail:
1739         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1740                     sizeof(void*));
1741 login_mtask_alloc_fail:
1742         iscsi_destroy_conn(cls_conn);
1743         return NULL;
1744 }
1745 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
1746
1747 /**
1748  * iscsi_conn_teardown - teardown iscsi connection
1749  * cls_conn: iscsi class connection
1750  *
1751  * TODO: we may need to make this into a two step process
1752  * like scsi-mls remove + put host
1753  */
1754 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
1755 {
1756         struct iscsi_conn *conn = cls_conn->dd_data;
1757         struct iscsi_session *session = conn->session;
1758         unsigned long flags;
1759
1760         spin_lock_bh(&session->lock);
1761         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
1762         if (session->leadconn == conn) {
1763                 /*
1764                  * leading connection? then give up on recovery.
1765                  */
1766                 session->state = ISCSI_STATE_TERMINATE;
1767                 wake_up(&conn->ehwait);
1768         }
1769         spin_unlock_bh(&session->lock);
1770
1771         /*
1772          * Block until all in-progress commands for this connection
1773          * time out or fail.
1774          */
1775         for (;;) {
1776                 spin_lock_irqsave(session->host->host_lock, flags);
1777                 if (!session->host->host_busy) { /* OK for ERL == 0 */
1778                         spin_unlock_irqrestore(session->host->host_lock, flags);
1779                         break;
1780                 }
1781                 spin_unlock_irqrestore(session->host->host_lock, flags);
1782                 msleep_interruptible(500);
1783                 printk(KERN_INFO "iscsi: scsi conn_destroy(): host_busy %d "
1784                        "host_failed %d\n", session->host->host_busy,
1785                        session->host->host_failed);
1786                 /*
1787                  * force eh_abort() to unblock
1788                  */
1789                 wake_up(&conn->ehwait);
1790         }
1791
1792         /* flush queued up work because we free the connection below */
1793         iscsi_suspend_tx(conn);
1794
1795         spin_lock_bh(&session->lock);
1796         kfree(conn->data);
1797         kfree(conn->persistent_address);
1798         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1799                     sizeof(void*));
1800         if (session->leadconn == conn)
1801                 session->leadconn = NULL;
1802         spin_unlock_bh(&session->lock);
1803
1804         iscsi_destroy_conn(cls_conn);
1805 }
1806 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
1807
1808 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
1809 {
1810         struct iscsi_conn *conn = cls_conn->dd_data;
1811         struct iscsi_session *session = conn->session;
1812
1813         if (!session) {
1814                 printk(KERN_ERR "iscsi: can't start unbound connection\n");
1815                 return -EPERM;
1816         }
1817
1818         if ((session->imm_data_en || !session->initial_r2t_en) &&
1819              session->first_burst > session->max_burst) {
1820                 printk("iscsi: invalid burst lengths: "
1821                        "first_burst %d max_burst %d\n",
1822                        session->first_burst, session->max_burst);
1823                 return -EINVAL;
1824         }
1825
1826         spin_lock_bh(&session->lock);
1827         conn->c_stage = ISCSI_CONN_STARTED;
1828         session->state = ISCSI_STATE_LOGGED_IN;
1829         session->queued_cmdsn = session->cmdsn;
1830
1831         switch(conn->stop_stage) {
1832         case STOP_CONN_RECOVER:
1833                 /*
1834                  * unblock eh_abort() if it is blocked. re-try all
1835                  * commands after successful recovery
1836                  */
1837                 conn->stop_stage = 0;
1838                 conn->tmf_state = TMF_INITIAL;
1839                 session->age++;
1840                 spin_unlock_bh(&session->lock);
1841
1842                 iscsi_unblock_session(session_to_cls(session));
1843                 wake_up(&conn->ehwait);
1844                 return 0;
1845         case STOP_CONN_TERM:
1846                 conn->stop_stage = 0;
1847                 break;
1848         default:
1849                 break;
1850         }
1851         spin_unlock_bh(&session->lock);
1852
1853         return 0;
1854 }
1855 EXPORT_SYMBOL_GPL(iscsi_conn_start);
1856
1857 static void
1858 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
1859 {
1860         struct iscsi_mgmt_task *mtask, *tmp;
1861
1862         /* handle pending */
1863         list_for_each_entry_safe(mtask, tmp, &conn->mgmtqueue, running) {
1864                 debug_scsi("flushing pending mgmt task itt 0x%x\n", mtask->itt);
1865                 iscsi_free_mgmt_task(conn, mtask);
1866         }
1867
1868         /* handle running */
1869         list_for_each_entry_safe(mtask, tmp, &conn->mgmt_run_list, running) {
1870                 debug_scsi("flushing running mgmt task itt 0x%x\n", mtask->itt);
1871                 iscsi_free_mgmt_task(conn, mtask);
1872         }
1873
1874         conn->mtask = NULL;
1875 }
1876
1877 static void iscsi_start_session_recovery(struct iscsi_session *session,
1878                                          struct iscsi_conn *conn, int flag)
1879 {
1880         int old_stop_stage;
1881
1882         mutex_lock(&session->eh_mutex);
1883         spin_lock_bh(&session->lock);
1884         if (conn->stop_stage == STOP_CONN_TERM) {
1885                 spin_unlock_bh(&session->lock);
1886                 mutex_unlock(&session->eh_mutex);
1887                 return;
1888         }
1889
1890         /*
1891          * The LLD either freed/unset the lock on us, or userspace called
1892          * stop but did not create a proper connection (connection was never
1893          * bound or it was unbound then stop was called).
1894          */
1895         if (!conn->recv_lock) {
1896                 spin_unlock_bh(&session->lock);
1897                 mutex_unlock(&session->eh_mutex);
1898                 return;
1899         }
1900
1901         /*
1902          * When this is called for the in_login state, we only want to clean
1903          * up the login task and connection. We do not need to block and set
1904          * the recovery state again
1905          */
1906         if (flag == STOP_CONN_TERM)
1907                 session->state = ISCSI_STATE_TERMINATE;
1908         else if (conn->stop_stage != STOP_CONN_RECOVER)
1909                 session->state = ISCSI_STATE_IN_RECOVERY;
1910
1911         old_stop_stage = conn->stop_stage;
1912         conn->stop_stage = flag;
1913         conn->c_stage = ISCSI_CONN_STOPPED;
1914         spin_unlock_bh(&session->lock);
1915
1916         iscsi_suspend_tx(conn);
1917
1918         write_lock_bh(conn->recv_lock);
1919         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1920         write_unlock_bh(conn->recv_lock);
1921
1922         /*
1923          * for connection level recovery we should not calculate
1924          * header digest. conn->hdr_size used for optimization
1925          * in hdr_extract() and will be re-negotiated at
1926          * set_param() time.
1927          */
1928         if (flag == STOP_CONN_RECOVER) {
1929                 conn->hdrdgst_en = 0;
1930                 conn->datadgst_en = 0;
1931                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
1932                     old_stop_stage != STOP_CONN_RECOVER) {
1933                         debug_scsi("blocking session\n");
1934                         iscsi_block_session(session_to_cls(session));
1935                 }
1936         }
1937
1938         /*
1939          * flush queues.
1940          */
1941         spin_lock_bh(&session->lock);
1942         fail_all_commands(conn, -1);
1943         flush_control_queues(session, conn);
1944         spin_unlock_bh(&session->lock);
1945         mutex_unlock(&session->eh_mutex);
1946 }
1947
1948 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1949 {
1950         struct iscsi_conn *conn = cls_conn->dd_data;
1951         struct iscsi_session *session = conn->session;
1952
1953         switch (flag) {
1954         case STOP_CONN_RECOVER:
1955         case STOP_CONN_TERM:
1956                 iscsi_start_session_recovery(session, conn, flag);
1957                 break;
1958         default:
1959                 printk(KERN_ERR "iscsi: invalid stop flag %d\n", flag);
1960         }
1961 }
1962 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
1963
1964 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
1965                     struct iscsi_cls_conn *cls_conn, int is_leading)
1966 {
1967         struct iscsi_session *session = class_to_transport_session(cls_session);
1968         struct iscsi_conn *conn = cls_conn->dd_data;
1969
1970         spin_lock_bh(&session->lock);
1971         if (is_leading)
1972                 session->leadconn = conn;
1973         spin_unlock_bh(&session->lock);
1974
1975         /*
1976          * Unblock xmitworker(), Login Phase will pass through.
1977          */
1978         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1979         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1980         return 0;
1981 }
1982 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
1983
1984
1985 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
1986                     enum iscsi_param param, char *buf, int buflen)
1987 {
1988         struct iscsi_conn *conn = cls_conn->dd_data;
1989         struct iscsi_session *session = conn->session;
1990         uint32_t value;
1991
1992         switch(param) {
1993         case ISCSI_PARAM_FAST_ABORT:
1994                 sscanf(buf, "%d", &session->fast_abort);
1995                 break;
1996         case ISCSI_PARAM_MAX_RECV_DLENGTH:
1997                 sscanf(buf, "%d", &conn->max_recv_dlength);
1998                 break;
1999         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2000                 sscanf(buf, "%d", &conn->max_xmit_dlength);
2001                 break;
2002         case ISCSI_PARAM_HDRDGST_EN:
2003                 sscanf(buf, "%d", &conn->hdrdgst_en);
2004                 break;
2005         case ISCSI_PARAM_DATADGST_EN:
2006                 sscanf(buf, "%d", &conn->datadgst_en);
2007                 break;
2008         case ISCSI_PARAM_INITIAL_R2T_EN:
2009                 sscanf(buf, "%d", &session->initial_r2t_en);
2010                 break;
2011         case ISCSI_PARAM_MAX_R2T:
2012                 sscanf(buf, "%d", &session->max_r2t);
2013                 break;
2014         case ISCSI_PARAM_IMM_DATA_EN:
2015                 sscanf(buf, "%d", &session->imm_data_en);
2016                 break;
2017         case ISCSI_PARAM_FIRST_BURST:
2018                 sscanf(buf, "%d", &session->first_burst);
2019                 break;
2020         case ISCSI_PARAM_MAX_BURST:
2021                 sscanf(buf, "%d", &session->max_burst);
2022                 break;
2023         case ISCSI_PARAM_PDU_INORDER_EN:
2024                 sscanf(buf, "%d", &session->pdu_inorder_en);
2025                 break;
2026         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2027                 sscanf(buf, "%d", &session->dataseq_inorder_en);
2028                 break;
2029         case ISCSI_PARAM_ERL:
2030                 sscanf(buf, "%d", &session->erl);
2031                 break;
2032         case ISCSI_PARAM_IFMARKER_EN:
2033                 sscanf(buf, "%d", &value);
2034                 BUG_ON(value);
2035                 break;
2036         case ISCSI_PARAM_OFMARKER_EN:
2037                 sscanf(buf, "%d", &value);
2038                 BUG_ON(value);
2039                 break;
2040         case ISCSI_PARAM_EXP_STATSN:
2041                 sscanf(buf, "%u", &conn->exp_statsn);
2042                 break;
2043         case ISCSI_PARAM_USERNAME:
2044                 kfree(session->username);
2045                 session->username = kstrdup(buf, GFP_KERNEL);
2046                 if (!session->username)
2047                         return -ENOMEM;
2048                 break;
2049         case ISCSI_PARAM_USERNAME_IN:
2050                 kfree(session->username_in);
2051                 session->username_in = kstrdup(buf, GFP_KERNEL);
2052                 if (!session->username_in)
2053                         return -ENOMEM;
2054                 break;
2055         case ISCSI_PARAM_PASSWORD:
2056                 kfree(session->password);
2057                 session->password = kstrdup(buf, GFP_KERNEL);
2058                 if (!session->password)
2059                         return -ENOMEM;
2060                 break;
2061         case ISCSI_PARAM_PASSWORD_IN:
2062                 kfree(session->password_in);
2063                 session->password_in = kstrdup(buf, GFP_KERNEL);
2064                 if (!session->password_in)
2065                         return -ENOMEM;
2066                 break;
2067         case ISCSI_PARAM_TARGET_NAME:
2068                 /* this should not change between logins */
2069                 if (session->targetname)
2070                         break;
2071
2072                 session->targetname = kstrdup(buf, GFP_KERNEL);
2073                 if (!session->targetname)
2074                         return -ENOMEM;
2075                 break;
2076         case ISCSI_PARAM_TPGT:
2077                 sscanf(buf, "%d", &session->tpgt);
2078                 break;
2079         case ISCSI_PARAM_PERSISTENT_PORT:
2080                 sscanf(buf, "%d", &conn->persistent_port);
2081                 break;
2082         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2083                 /*
2084                  * this is the address returned in discovery so it should
2085                  * not change between logins.
2086                  */
2087                 if (conn->persistent_address)
2088                         break;
2089
2090                 conn->persistent_address = kstrdup(buf, GFP_KERNEL);
2091                 if (!conn->persistent_address)
2092                         return -ENOMEM;
2093                 break;
2094         default:
2095                 return -ENOSYS;
2096         }
2097
2098         return 0;
2099 }
2100 EXPORT_SYMBOL_GPL(iscsi_set_param);
2101
2102 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
2103                             enum iscsi_param param, char *buf)
2104 {
2105         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
2106         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2107         int len;
2108
2109         switch(param) {
2110         case ISCSI_PARAM_FAST_ABORT:
2111                 len = sprintf(buf, "%d\n", session->fast_abort);
2112                 break;
2113         case ISCSI_PARAM_INITIAL_R2T_EN:
2114                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
2115                 break;
2116         case ISCSI_PARAM_MAX_R2T:
2117                 len = sprintf(buf, "%hu\n", session->max_r2t);
2118                 break;
2119         case ISCSI_PARAM_IMM_DATA_EN:
2120                 len = sprintf(buf, "%d\n", session->imm_data_en);
2121                 break;
2122         case ISCSI_PARAM_FIRST_BURST:
2123                 len = sprintf(buf, "%u\n", session->first_burst);
2124                 break;
2125         case ISCSI_PARAM_MAX_BURST:
2126                 len = sprintf(buf, "%u\n", session->max_burst);
2127                 break;
2128         case ISCSI_PARAM_PDU_INORDER_EN:
2129                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
2130                 break;
2131         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2132                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
2133                 break;
2134         case ISCSI_PARAM_ERL:
2135                 len = sprintf(buf, "%d\n", session->erl);
2136                 break;
2137         case ISCSI_PARAM_TARGET_NAME:
2138                 len = sprintf(buf, "%s\n", session->targetname);
2139                 break;
2140         case ISCSI_PARAM_TPGT:
2141                 len = sprintf(buf, "%d\n", session->tpgt);
2142                 break;
2143         case ISCSI_PARAM_USERNAME:
2144                 len = sprintf(buf, "%s\n", session->username);
2145                 break;
2146         case ISCSI_PARAM_USERNAME_IN:
2147                 len = sprintf(buf, "%s\n", session->username_in);
2148                 break;
2149         case ISCSI_PARAM_PASSWORD:
2150                 len = sprintf(buf, "%s\n", session->password);
2151                 break;
2152         case ISCSI_PARAM_PASSWORD_IN:
2153                 len = sprintf(buf, "%s\n", session->password_in);
2154                 break;
2155         default:
2156                 return -ENOSYS;
2157         }
2158
2159         return len;
2160 }
2161 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
2162
2163 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
2164                          enum iscsi_param param, char *buf)
2165 {
2166         struct iscsi_conn *conn = cls_conn->dd_data;
2167         int len;
2168
2169         switch(param) {
2170         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2171                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
2172                 break;
2173         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2174                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
2175                 break;
2176         case ISCSI_PARAM_HDRDGST_EN:
2177                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
2178                 break;
2179         case ISCSI_PARAM_DATADGST_EN:
2180                 len = sprintf(buf, "%d\n", conn->datadgst_en);
2181                 break;
2182         case ISCSI_PARAM_IFMARKER_EN:
2183                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
2184                 break;
2185         case ISCSI_PARAM_OFMARKER_EN:
2186                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
2187                 break;
2188         case ISCSI_PARAM_EXP_STATSN:
2189                 len = sprintf(buf, "%u\n", conn->exp_statsn);
2190                 break;
2191         case ISCSI_PARAM_PERSISTENT_PORT:
2192                 len = sprintf(buf, "%d\n", conn->persistent_port);
2193                 break;
2194         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2195                 len = sprintf(buf, "%s\n", conn->persistent_address);
2196                 break;
2197         default:
2198                 return -ENOSYS;
2199         }
2200
2201         return len;
2202 }
2203 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
2204
2205 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2206                          char *buf)
2207 {
2208         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2209         int len;
2210
2211         switch (param) {
2212         case ISCSI_HOST_PARAM_NETDEV_NAME:
2213                 if (!session->netdev)
2214                         len = sprintf(buf, "%s\n", "default");
2215                 else
2216                         len = sprintf(buf, "%s\n", session->netdev);
2217                 break;
2218         case ISCSI_HOST_PARAM_HWADDRESS:
2219                 if (!session->hwaddress)
2220                         len = sprintf(buf, "%s\n", "default");
2221                 else
2222                         len = sprintf(buf, "%s\n", session->hwaddress);
2223                 break;
2224         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2225                 if (!session->initiatorname)
2226                         len = sprintf(buf, "%s\n", "unknown");
2227                 else
2228                         len = sprintf(buf, "%s\n", session->initiatorname);
2229                 break;
2230
2231         default:
2232                 return -ENOSYS;
2233         }
2234
2235         return len;
2236 }
2237 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
2238
2239 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2240                          char *buf, int buflen)
2241 {
2242         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
2243
2244         switch (param) {
2245         case ISCSI_HOST_PARAM_NETDEV_NAME:
2246                 if (!session->netdev)
2247                         session->netdev = kstrdup(buf, GFP_KERNEL);
2248                 break;
2249         case ISCSI_HOST_PARAM_HWADDRESS:
2250                 if (!session->hwaddress)
2251                         session->hwaddress = kstrdup(buf, GFP_KERNEL);
2252                 break;
2253         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2254                 if (!session->initiatorname)
2255                         session->initiatorname = kstrdup(buf, GFP_KERNEL);
2256                 break;
2257         default:
2258                 return -ENOSYS;
2259         }
2260
2261         return 0;
2262 }
2263 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
2264
2265 MODULE_AUTHOR("Mike Christie");
2266 MODULE_DESCRIPTION("iSCSI library functions");
2267 MODULE_LICENSE("GPL");