[SCSI] libiscsi: change login data buffer allocation
[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 <linux/log2.h>
28 #include <asm/unaligned.h>
29 #include <net/tcp.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_tcq.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi.h>
36 #include <scsi/iscsi_proto.h>
37 #include <scsi/scsi_transport.h>
38 #include <scsi/scsi_transport_iscsi.h>
39 #include <scsi/libiscsi.h>
40
41 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
42 #define SNA32_CHECK 2147483648UL
43
44 static int iscsi_sna_lt(u32 n1, u32 n2)
45 {
46         return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
47                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
48 }
49
50 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
51 static int iscsi_sna_lte(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 void
58 iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
59 {
60         uint32_t max_cmdsn = be32_to_cpu(hdr->max_cmdsn);
61         uint32_t exp_cmdsn = be32_to_cpu(hdr->exp_cmdsn);
62
63         /*
64          * standard specifies this check for when to update expected and
65          * max sequence numbers
66          */
67         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
68                 return;
69
70         if (exp_cmdsn != session->exp_cmdsn &&
71             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
72                 session->exp_cmdsn = exp_cmdsn;
73
74         if (max_cmdsn != session->max_cmdsn &&
75             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) {
76                 session->max_cmdsn = max_cmdsn;
77                 /*
78                  * if the window closed with IO queued, then kick the
79                  * xmit thread
80                  */
81                 if (!list_empty(&session->leadconn->xmitqueue) ||
82                     !list_empty(&session->leadconn->mgmtqueue)) {
83                         if (!(session->tt->caps & CAP_DATA_PATH_OFFLOAD))
84                                 scsi_queue_work(session->host,
85                                                 &session->leadconn->xmitwork);
86                 }
87         }
88 }
89 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
90
91 /**
92  * iscsi_prep_data_out_pdu - initialize Data-Out
93  * @task: scsi command task
94  * @r2t: R2T info
95  * @hdr: iscsi data in pdu
96  *
97  * Notes:
98  *      Initialize Data-Out within this R2T sequence and finds
99  *      proper data_offset within this SCSI command.
100  *
101  *      This function is called with connection lock taken.
102  **/
103 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
104                            struct iscsi_data *hdr)
105 {
106         struct iscsi_conn *conn = task->conn;
107         unsigned int left = r2t->data_length - r2t->sent;
108
109         task->hdr_len = sizeof(struct iscsi_data);
110
111         memset(hdr, 0, sizeof(struct iscsi_data));
112         hdr->ttt = r2t->ttt;
113         hdr->datasn = cpu_to_be32(r2t->datasn);
114         r2t->datasn++;
115         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
116         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
117         hdr->itt = task->hdr_itt;
118         hdr->exp_statsn = r2t->exp_statsn;
119         hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
120         if (left > conn->max_xmit_dlength) {
121                 hton24(hdr->dlength, conn->max_xmit_dlength);
122                 r2t->data_count = conn->max_xmit_dlength;
123                 hdr->flags = 0;
124         } else {
125                 hton24(hdr->dlength, left);
126                 r2t->data_count = left;
127                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
128         }
129         conn->dataout_pdus_cnt++;
130 }
131 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
132
133 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
134 {
135         unsigned exp_len = task->hdr_len + len;
136
137         if (exp_len > task->hdr_max) {
138                 WARN_ON(1);
139                 return -EINVAL;
140         }
141
142         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
143         task->hdr_len = exp_len;
144         return 0;
145 }
146
147 /*
148  * make an extended cdb AHS
149  */
150 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
151 {
152         struct scsi_cmnd *cmd = task->sc;
153         unsigned rlen, pad_len;
154         unsigned short ahslength;
155         struct iscsi_ecdb_ahdr *ecdb_ahdr;
156         int rc;
157
158         ecdb_ahdr = iscsi_next_hdr(task);
159         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
160
161         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
162         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
163
164         pad_len = iscsi_padding(rlen);
165
166         rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
167                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
168         if (rc)
169                 return rc;
170
171         if (pad_len)
172                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
173
174         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
175         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
176         ecdb_ahdr->reserved = 0;
177         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
178
179         debug_scsi("iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
180                    "rlen %d pad_len %d ahs_length %d iscsi_headers_size %u\n",
181                    cmd->cmd_len, rlen, pad_len, ahslength, task->hdr_len);
182
183         return 0;
184 }
185
186 static int iscsi_prep_bidi_ahs(struct iscsi_task *task)
187 {
188         struct scsi_cmnd *sc = task->sc;
189         struct iscsi_rlength_ahdr *rlen_ahdr;
190         int rc;
191
192         rlen_ahdr = iscsi_next_hdr(task);
193         rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr));
194         if (rc)
195                 return rc;
196
197         rlen_ahdr->ahslength =
198                 cpu_to_be16(sizeof(rlen_ahdr->read_length) +
199                                                   sizeof(rlen_ahdr->reserved));
200         rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
201         rlen_ahdr->reserved = 0;
202         rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
203
204         debug_scsi("bidi-in rlen_ahdr->read_length(%d) "
205                    "rlen_ahdr->ahslength(%d)\n",
206                    be32_to_cpu(rlen_ahdr->read_length),
207                    be16_to_cpu(rlen_ahdr->ahslength));
208         return 0;
209 }
210
211 /**
212  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
213  * @task: iscsi task
214  *
215  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
216  * fields like dlength or final based on how much data it sends
217  */
218 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
219 {
220         struct iscsi_conn *conn = task->conn;
221         struct iscsi_session *session = conn->session;
222         struct scsi_cmnd *sc = task->sc;
223         struct iscsi_cmd *hdr;
224         unsigned hdrlength, cmd_len;
225         int rc;
226
227         rc = conn->session->tt->alloc_pdu(task);
228         if (rc)
229                 return rc;
230         hdr = (struct iscsi_cmd *) task->hdr;
231         memset(hdr, 0, sizeof(*hdr));
232
233         task->hdr_len = 0;
234         rc = iscsi_add_hdr(task, sizeof(*hdr));
235         if (rc)
236                 return rc;
237         hdr->opcode = ISCSI_OP_SCSI_CMD;
238         hdr->flags = ISCSI_ATTR_SIMPLE;
239         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
240         memcpy(task->lun, hdr->lun, sizeof(task->lun));
241         hdr->itt = task->hdr_itt = build_itt(task->itt, session->age);
242         hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
243         session->cmdsn++;
244         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
245         cmd_len = sc->cmd_len;
246         if (cmd_len < ISCSI_CDB_SIZE)
247                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
248         else if (cmd_len > ISCSI_CDB_SIZE) {
249                 rc = iscsi_prep_ecdb_ahs(task);
250                 if (rc)
251                         return rc;
252                 cmd_len = ISCSI_CDB_SIZE;
253         }
254         memcpy(hdr->cdb, sc->cmnd, cmd_len);
255
256         task->imm_count = 0;
257         if (scsi_bidi_cmnd(sc)) {
258                 hdr->flags |= ISCSI_FLAG_CMD_READ;
259                 rc = iscsi_prep_bidi_ahs(task);
260                 if (rc)
261                         return rc;
262         }
263         if (sc->sc_data_direction == DMA_TO_DEVICE) {
264                 unsigned out_len = scsi_out(sc)->length;
265                 struct iscsi_r2t_info *r2t = &task->unsol_r2t;
266
267                 hdr->data_length = cpu_to_be32(out_len);
268                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
269                 /*
270                  * Write counters:
271                  *
272                  *      imm_count       bytes to be sent right after
273                  *                      SCSI PDU Header
274                  *
275                  *      unsol_count     bytes(as Data-Out) to be sent
276                  *                      without R2T ack right after
277                  *                      immediate data
278                  *
279                  *      r2t data_length bytes to be sent via R2T ack's
280                  *
281                  *      pad_count       bytes to be sent as zero-padding
282                  */
283                 memset(r2t, 0, sizeof(*r2t));
284
285                 if (session->imm_data_en) {
286                         if (out_len >= session->first_burst)
287                                 task->imm_count = min(session->first_burst,
288                                                         conn->max_xmit_dlength);
289                         else
290                                 task->imm_count = min(out_len,
291                                                         conn->max_xmit_dlength);
292                         hton24(hdr->dlength, task->imm_count);
293                 } else
294                         zero_data(hdr->dlength);
295
296                 if (!session->initial_r2t_en) {
297                         r2t->data_length = min(session->first_burst, out_len) -
298                                                task->imm_count;
299                         r2t->data_offset = task->imm_count;
300                         r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
301                         r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
302                 }
303
304                 if (!task->unsol_r2t.data_length)
305                         /* No unsolicit Data-Out's */
306                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
307         } else {
308                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
309                 zero_data(hdr->dlength);
310                 hdr->data_length = cpu_to_be32(scsi_in(sc)->length);
311
312                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
313                         hdr->flags |= ISCSI_FLAG_CMD_READ;
314         }
315
316         /* calculate size of additional header segments (AHSs) */
317         hdrlength = task->hdr_len - sizeof(*hdr);
318
319         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
320         hdrlength /= ISCSI_PAD_LEN;
321
322         WARN_ON(hdrlength >= 256);
323         hdr->hlength = hdrlength & 0xFF;
324
325         if (session->tt->init_task && session->tt->init_task(task))
326                 return -EIO;
327
328         task->state = ISCSI_TASK_RUNNING;
329         list_move_tail(&task->running, &conn->run_list);
330
331         conn->scsicmd_pdus_cnt++;
332         debug_scsi("iscsi prep [%s cid %d sc %p cdb 0x%x itt 0x%x len %d "
333                    "bidi_len %d cmdsn %d win %d]\n", scsi_bidi_cmnd(sc) ?
334                    "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ?
335                    "write" : "read", conn->id, sc, sc->cmnd[0], task->itt,
336                    scsi_bufflen(sc),
337                    scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
338                    session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1);
339         return 0;
340 }
341
342 /**
343  * iscsi_complete_command - finish a task
344  * @task: iscsi cmd task
345  *
346  * Must be called with session lock.
347  * This function returns the scsi command to scsi-ml or cleans
348  * up mgmt tasks then returns the task to the pool.
349  */
350 static void iscsi_complete_command(struct iscsi_task *task)
351 {
352         struct iscsi_conn *conn = task->conn;
353         struct iscsi_session *session = conn->session;
354         struct scsi_cmnd *sc = task->sc;
355
356         session->tt->cleanup_task(task);
357         list_del_init(&task->running);
358         task->state = ISCSI_TASK_COMPLETED;
359         task->sc = NULL;
360
361         if (conn->task == task)
362                 conn->task = NULL;
363         /*
364          * login task is preallocated so do not free
365          */
366         if (conn->login_task == task)
367                 return;
368
369         __kfifo_put(session->cmdpool.queue, (void*)&task, sizeof(void*));
370
371         if (conn->ping_task == task)
372                 conn->ping_task = NULL;
373
374         if (sc) {
375                 task->sc = NULL;
376                 /* SCSI eh reuses commands to verify us */
377                 sc->SCp.ptr = NULL;
378                 /*
379                  * queue command may call this to free the task, but
380                  * not have setup the sc callback
381                  */
382                 if (sc->scsi_done)
383                         sc->scsi_done(sc);
384         }
385 }
386
387 void __iscsi_get_task(struct iscsi_task *task)
388 {
389         atomic_inc(&task->refcount);
390 }
391 EXPORT_SYMBOL_GPL(__iscsi_get_task);
392
393 static void __iscsi_put_task(struct iscsi_task *task)
394 {
395         if (atomic_dec_and_test(&task->refcount))
396                 iscsi_complete_command(task);
397 }
398
399 void iscsi_put_task(struct iscsi_task *task)
400 {
401         struct iscsi_session *session = task->conn->session;
402
403         spin_lock_bh(&session->lock);
404         __iscsi_put_task(task);
405         spin_unlock_bh(&session->lock);
406 }
407 EXPORT_SYMBOL_GPL(iscsi_put_task);
408
409 /*
410  * session lock must be held
411  */
412 static void fail_command(struct iscsi_conn *conn, struct iscsi_task *task,
413                          int err)
414 {
415         struct scsi_cmnd *sc;
416
417         sc = task->sc;
418         if (!sc)
419                 return;
420
421         if (task->state == ISCSI_TASK_PENDING)
422                 /*
423                  * cmd never made it to the xmit thread, so we should not count
424                  * the cmd in the sequencing
425                  */
426                 conn->session->queued_cmdsn--;
427
428         sc->result = err;
429         if (!scsi_bidi_cmnd(sc))
430                 scsi_set_resid(sc, scsi_bufflen(sc));
431         else {
432                 scsi_out(sc)->resid = scsi_out(sc)->length;
433                 scsi_in(sc)->resid = scsi_in(sc)->length;
434         }
435
436         if (conn->task == task)
437                 conn->task = NULL;
438         /* release ref from queuecommand */
439         __iscsi_put_task(task);
440 }
441
442 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
443                                 struct iscsi_task *task)
444 {
445         struct iscsi_session *session = conn->session;
446         struct iscsi_hdr *hdr = task->hdr;
447         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
448
449         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
450                 return -ENOTCONN;
451
452         if (hdr->opcode != (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) &&
453             hdr->opcode != (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
454                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
455         /*
456          * pre-format CmdSN for outgoing PDU.
457          */
458         nop->cmdsn = cpu_to_be32(session->cmdsn);
459         if (hdr->itt != RESERVED_ITT) {
460                 hdr->itt = build_itt(task->itt, session->age);
461                 /*
462                  * TODO: We always use immediate, so we never hit this.
463                  * If we start to send tmfs or nops as non-immediate then
464                  * we should start checking the cmdsn numbers for mgmt tasks.
465                  */
466                 if (conn->c_stage == ISCSI_CONN_STARTED &&
467                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
468                         session->queued_cmdsn++;
469                         session->cmdsn++;
470                 }
471         }
472
473         if (session->tt->init_task)
474                 session->tt->init_task(task);
475
476         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
477                 session->state = ISCSI_STATE_LOGGING_OUT;
478
479         task->state = ISCSI_TASK_RUNNING;
480         list_move_tail(&task->running, &conn->mgmt_run_list);
481         debug_scsi("mgmtpdu [op 0x%x hdr->itt 0x%x datalen %d]\n",
482                    hdr->opcode & ISCSI_OPCODE_MASK, hdr->itt,
483                    task->data_count);
484         return 0;
485 }
486
487 static struct iscsi_task *
488 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
489                       char *data, uint32_t data_size)
490 {
491         struct iscsi_session *session = conn->session;
492         struct iscsi_task *task;
493
494         if (session->state == ISCSI_STATE_TERMINATE)
495                 return NULL;
496
497         if (hdr->opcode == (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) ||
498             hdr->opcode == (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
499                 /*
500                  * Login and Text are sent serially, in
501                  * request-followed-by-response sequence.
502                  * Same task can be used. Same ITT must be used.
503                  * Note that login_task is preallocated at conn_create().
504                  */
505                 task = conn->login_task;
506         else {
507                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
508                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
509
510                 if (!__kfifo_get(session->cmdpool.queue,
511                                  (void*)&task, sizeof(void*)))
512                         return NULL;
513         }
514         /*
515          * released in complete pdu for task we expect a response for, and
516          * released by the lld when it has transmitted the task for
517          * pdus we do not expect a response for.
518          */
519         atomic_set(&task->refcount, 1);
520         task->conn = conn;
521         task->sc = NULL;
522
523         if (data_size) {
524                 memcpy(task->data, data, data_size);
525                 task->data_count = data_size;
526         } else
527                 task->data_count = 0;
528
529         if (conn->session->tt->alloc_pdu(task)) {
530                 iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
531                                  "pdu for mgmt task.\n");
532                 goto requeue_task;
533         }
534         task->hdr_len = sizeof(struct iscsi_hdr);
535
536         memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
537         INIT_LIST_HEAD(&task->running);
538         list_add_tail(&task->running, &conn->mgmtqueue);
539
540         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
541                 if (iscsi_prep_mgmt_task(conn, task))
542                         goto free_task;
543
544                 if (session->tt->xmit_task(task))
545                         goto free_task;
546
547         } else
548                 scsi_queue_work(conn->session->host, &conn->xmitwork);
549
550         return task;
551
552 free_task:
553         __iscsi_put_task(task);
554         return NULL;
555
556 requeue_task:
557         if (task != conn->login_task)
558                 __kfifo_put(session->cmdpool.queue, (void*)&task,
559                             sizeof(void*));
560         return NULL;
561 }
562
563 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
564                         char *data, uint32_t data_size)
565 {
566         struct iscsi_conn *conn = cls_conn->dd_data;
567         struct iscsi_session *session = conn->session;
568         int err = 0;
569
570         spin_lock_bh(&session->lock);
571         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
572                 err = -EPERM;
573         spin_unlock_bh(&session->lock);
574         return err;
575 }
576 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
577
578 /**
579  * iscsi_cmd_rsp - SCSI Command Response processing
580  * @conn: iscsi connection
581  * @hdr: iscsi header
582  * @task: scsi command task
583  * @data: cmd data buffer
584  * @datalen: len of buffer
585  *
586  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
587  * then completes the command and task.
588  **/
589 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
590                                struct iscsi_task *task, char *data,
591                                int datalen)
592 {
593         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
594         struct iscsi_session *session = conn->session;
595         struct scsi_cmnd *sc = task->sc;
596
597         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
598         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
599
600         sc->result = (DID_OK << 16) | rhdr->cmd_status;
601
602         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
603                 sc->result = DID_ERROR << 16;
604                 goto out;
605         }
606
607         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
608                 uint16_t senselen;
609
610                 if (datalen < 2) {
611 invalid_datalen:
612                         iscsi_conn_printk(KERN_ERR,  conn,
613                                          "Got CHECK_CONDITION but invalid data "
614                                          "buffer size of %d\n", datalen);
615                         sc->result = DID_BAD_TARGET << 16;
616                         goto out;
617                 }
618
619                 senselen = get_unaligned_be16(data);
620                 if (datalen < senselen)
621                         goto invalid_datalen;
622
623                 memcpy(sc->sense_buffer, data + 2,
624                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
625                 debug_scsi("copied %d bytes of sense\n",
626                            min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
627         }
628
629         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
630                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
631                 int res_count = be32_to_cpu(rhdr->bi_residual_count);
632
633                 if (scsi_bidi_cmnd(sc) && res_count > 0 &&
634                                 (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
635                                  res_count <= scsi_in(sc)->length))
636                         scsi_in(sc)->resid = res_count;
637                 else
638                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
639         }
640
641         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
642                            ISCSI_FLAG_CMD_OVERFLOW)) {
643                 int res_count = be32_to_cpu(rhdr->residual_count);
644
645                 if (res_count > 0 &&
646                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
647                      res_count <= scsi_bufflen(sc)))
648                         /* write side for bidi or uni-io set_resid */
649                         scsi_set_resid(sc, res_count);
650                 else
651                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
652         }
653 out:
654         debug_scsi("done [sc %lx res %d itt 0x%x]\n",
655                    (long)sc, sc->result, task->itt);
656         conn->scsirsp_pdus_cnt++;
657
658         __iscsi_put_task(task);
659 }
660
661 /**
662  * iscsi_data_in_rsp - SCSI Data-In Response processing
663  * @conn: iscsi connection
664  * @hdr:  iscsi pdu
665  * @task: scsi command task
666  **/
667 static void
668 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
669                   struct iscsi_task *task)
670 {
671         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
672         struct scsi_cmnd *sc = task->sc;
673
674         if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
675                 return;
676
677         sc->result = (DID_OK << 16) | rhdr->cmd_status;
678         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
679         if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
680                            ISCSI_FLAG_DATA_OVERFLOW)) {
681                 int res_count = be32_to_cpu(rhdr->residual_count);
682
683                 if (res_count > 0 &&
684                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
685                      res_count <= scsi_in(sc)->length))
686                         scsi_in(sc)->resid = res_count;
687                 else
688                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
689         }
690
691         conn->scsirsp_pdus_cnt++;
692         __iscsi_put_task(task);
693 }
694
695 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
696 {
697         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
698
699         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
700         conn->tmfrsp_pdus_cnt++;
701
702         if (conn->tmf_state != TMF_QUEUED)
703                 return;
704
705         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
706                 conn->tmf_state = TMF_SUCCESS;
707         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
708                 conn->tmf_state = TMF_NOT_FOUND;
709         else
710                 conn->tmf_state = TMF_FAILED;
711         wake_up(&conn->ehwait);
712 }
713
714 static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
715 {
716         struct iscsi_nopout hdr;
717         struct iscsi_task *task;
718
719         if (!rhdr && conn->ping_task)
720                 return;
721
722         memset(&hdr, 0, sizeof(struct iscsi_nopout));
723         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
724         hdr.flags = ISCSI_FLAG_CMD_FINAL;
725
726         if (rhdr) {
727                 memcpy(hdr.lun, rhdr->lun, 8);
728                 hdr.ttt = rhdr->ttt;
729                 hdr.itt = RESERVED_ITT;
730         } else
731                 hdr.ttt = RESERVED_ITT;
732
733         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
734         if (!task)
735                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
736         else if (!rhdr) {
737                 /* only track our nops */
738                 conn->ping_task = task;
739                 conn->last_ping = jiffies;
740         }
741 }
742
743 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
744                                char *data, int datalen)
745 {
746         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
747         struct iscsi_hdr rejected_pdu;
748         uint32_t itt;
749
750         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
751
752         if (reject->reason == ISCSI_REASON_DATA_DIGEST_ERROR) {
753                 if (ntoh24(reject->dlength) > datalen)
754                         return ISCSI_ERR_PROTO;
755
756                 if (ntoh24(reject->dlength) >= sizeof(struct iscsi_hdr)) {
757                         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
758                         itt = get_itt(rejected_pdu.itt);
759                         iscsi_conn_printk(KERN_ERR, conn,
760                                           "itt 0x%x had pdu (op 0x%x) rejected "
761                                           "due to DataDigest error.\n", itt,
762                                           rejected_pdu.opcode);
763                 }
764         }
765         return 0;
766 }
767
768 /**
769  * iscsi_itt_to_task - look up task by itt
770  * @conn: iscsi connection
771  * @itt: itt
772  *
773  * This should be used for mgmt tasks like login and nops, or if
774  * the LDD's itt space does not include the session age.
775  *
776  * The session lock must be held.
777  */
778 static struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
779 {
780         struct iscsi_session *session = conn->session;
781         uint32_t i;
782
783         if (itt == RESERVED_ITT)
784                 return NULL;
785
786         i = get_itt(itt);
787         if (i >= session->cmds_max)
788                 return NULL;
789
790         return session->cmds[i];
791 }
792
793 /**
794  * __iscsi_complete_pdu - complete pdu
795  * @conn: iscsi conn
796  * @hdr: iscsi header
797  * @data: data buffer
798  * @datalen: len of data buffer
799  *
800  * Completes pdu processing by freeing any resources allocated at
801  * queuecommand or send generic. session lock must be held and verify
802  * itt must have been called.
803  */
804 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
805                          char *data, int datalen)
806 {
807         struct iscsi_session *session = conn->session;
808         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
809         struct iscsi_task *task;
810         uint32_t itt;
811
812         conn->last_recv = jiffies;
813         rc = iscsi_verify_itt(conn, hdr->itt);
814         if (rc)
815                 return rc;
816
817         if (hdr->itt != RESERVED_ITT)
818                 itt = get_itt(hdr->itt);
819         else
820                 itt = ~0U;
821
822         debug_scsi("[op 0x%x cid %d itt 0x%x len %d]\n",
823                    opcode, conn->id, itt, datalen);
824
825         if (itt == ~0U) {
826                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
827
828                 switch(opcode) {
829                 case ISCSI_OP_NOOP_IN:
830                         if (datalen) {
831                                 rc = ISCSI_ERR_PROTO;
832                                 break;
833                         }
834
835                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
836                                 break;
837
838                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
839                         break;
840                 case ISCSI_OP_REJECT:
841                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
842                         break;
843                 case ISCSI_OP_ASYNC_EVENT:
844                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
845                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
846                                 rc = ISCSI_ERR_CONN_FAILED;
847                         break;
848                 default:
849                         rc = ISCSI_ERR_BAD_OPCODE;
850                         break;
851                 }
852                 goto out;
853         }
854
855         switch(opcode) {
856         case ISCSI_OP_SCSI_CMD_RSP:
857         case ISCSI_OP_SCSI_DATA_IN:
858                 task = iscsi_itt_to_ctask(conn, hdr->itt);
859                 if (!task)
860                         return ISCSI_ERR_BAD_ITT;
861                 break;
862         case ISCSI_OP_R2T:
863                 /*
864                  * LLD handles R2Ts if they need to.
865                  */
866                 return 0;
867         case ISCSI_OP_LOGOUT_RSP:
868         case ISCSI_OP_LOGIN_RSP:
869         case ISCSI_OP_TEXT_RSP:
870         case ISCSI_OP_SCSI_TMFUNC_RSP:
871         case ISCSI_OP_NOOP_IN:
872                 task = iscsi_itt_to_task(conn, hdr->itt);
873                 if (!task)
874                         return ISCSI_ERR_BAD_ITT;
875                 break;
876         default:
877                 return ISCSI_ERR_BAD_OPCODE;
878         }
879
880         switch(opcode) {
881         case ISCSI_OP_SCSI_CMD_RSP:
882                 iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
883                 break;
884         case ISCSI_OP_SCSI_DATA_IN:
885                 iscsi_data_in_rsp(conn, hdr, task);
886                 break;
887         case ISCSI_OP_LOGOUT_RSP:
888                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
889                 if (datalen) {
890                         rc = ISCSI_ERR_PROTO;
891                         break;
892                 }
893                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
894                 goto recv_pdu;
895         case ISCSI_OP_LOGIN_RSP:
896         case ISCSI_OP_TEXT_RSP:
897                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
898                 /*
899                  * login related PDU's exp_statsn is handled in
900                  * userspace
901                  */
902                 goto recv_pdu;
903         case ISCSI_OP_SCSI_TMFUNC_RSP:
904                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
905                 if (datalen) {
906                         rc = ISCSI_ERR_PROTO;
907                         break;
908                 }
909
910                 iscsi_tmf_rsp(conn, hdr);
911                 __iscsi_put_task(task);
912                 break;
913         case ISCSI_OP_NOOP_IN:
914                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
915                 if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
916                         rc = ISCSI_ERR_PROTO;
917                         break;
918                 }
919                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
920
921                 if (conn->ping_task != task)
922                         /*
923                          * If this is not in response to one of our
924                          * nops then it must be from userspace.
925                          */
926                         goto recv_pdu;
927
928                 mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
929                 __iscsi_put_task(task);
930                 break;
931         default:
932                 rc = ISCSI_ERR_BAD_OPCODE;
933                 break;
934         }
935
936 out:
937         return rc;
938 recv_pdu:
939         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
940                 rc = ISCSI_ERR_CONN_FAILED;
941         __iscsi_put_task(task);
942         return rc;
943 }
944 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
945
946 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
947                        char *data, int datalen)
948 {
949         int rc;
950
951         spin_lock(&conn->session->lock);
952         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
953         spin_unlock(&conn->session->lock);
954         return rc;
955 }
956 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
957
958 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
959 {
960         struct iscsi_session *session = conn->session;
961         uint32_t i;
962
963         if (itt == RESERVED_ITT)
964                 return 0;
965
966         if (((__force u32)itt & ISCSI_AGE_MASK) !=
967             (session->age << ISCSI_AGE_SHIFT)) {
968                 iscsi_conn_printk(KERN_ERR, conn,
969                                   "received itt %x expected session age (%x)\n",
970                                   (__force u32)itt, session->age);
971                 return ISCSI_ERR_BAD_ITT;
972         }
973
974         i = get_itt(itt);
975         if (i >= session->cmds_max) {
976                 iscsi_conn_printk(KERN_ERR, conn,
977                                   "received invalid itt index %u (max cmds "
978                                    "%u.\n", i, session->cmds_max);
979                 return ISCSI_ERR_BAD_ITT;
980         }
981         return 0;
982 }
983 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
984
985 /**
986  * iscsi_itt_to_ctask - look up ctask by itt
987  * @conn: iscsi connection
988  * @itt: itt
989  *
990  * This should be used for cmd tasks.
991  *
992  * The session lock must be held.
993  */
994 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
995 {
996         struct iscsi_task *task;
997
998         if (iscsi_verify_itt(conn, itt))
999                 return NULL;
1000
1001         task = iscsi_itt_to_task(conn, itt);
1002         if (!task || !task->sc)
1003                 return NULL;
1004
1005         if (task->sc->SCp.phase != conn->session->age) {
1006                 iscsi_session_printk(KERN_ERR, conn->session,
1007                                   "task's session age %d, expected %d\n",
1008                                   task->sc->SCp.phase, conn->session->age);
1009                 return NULL;
1010         }
1011
1012         return task;
1013 }
1014 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1015
1016 void iscsi_session_failure(struct iscsi_cls_session *cls_session,
1017                            enum iscsi_err err)
1018 {
1019         struct iscsi_session *session = cls_session->dd_data;
1020         struct iscsi_conn *conn;
1021         struct device *dev;
1022         unsigned long flags;
1023
1024         spin_lock_irqsave(&session->lock, flags);
1025         conn = session->leadconn;
1026         if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1027                 spin_unlock_irqrestore(&session->lock, flags);
1028                 return;
1029         }
1030
1031         dev = get_device(&conn->cls_conn->dev);
1032         spin_unlock_irqrestore(&session->lock, flags);
1033         if (!dev)
1034                 return;
1035         /*
1036          * if the host is being removed bypass the connection
1037          * recovery initialization because we are going to kill
1038          * the session.
1039          */
1040         if (err == ISCSI_ERR_INVALID_HOST)
1041                 iscsi_conn_error_event(conn->cls_conn, err);
1042         else
1043                 iscsi_conn_failure(conn, err);
1044         put_device(dev);
1045 }
1046 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1047
1048 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1049 {
1050         struct iscsi_session *session = conn->session;
1051         unsigned long flags;
1052
1053         spin_lock_irqsave(&session->lock, flags);
1054         if (session->state == ISCSI_STATE_FAILED) {
1055                 spin_unlock_irqrestore(&session->lock, flags);
1056                 return;
1057         }
1058
1059         if (conn->stop_stage == 0)
1060                 session->state = ISCSI_STATE_FAILED;
1061         spin_unlock_irqrestore(&session->lock, flags);
1062
1063         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1064         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1065         iscsi_conn_error_event(conn->cls_conn, err);
1066 }
1067 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1068
1069 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1070 {
1071         struct iscsi_session *session = conn->session;
1072
1073         /*
1074          * Check for iSCSI window and take care of CmdSN wrap-around
1075          */
1076         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1077                 debug_scsi("iSCSI CmdSN closed. ExpCmdSn %u MaxCmdSN %u "
1078                            "CmdSN %u/%u\n", session->exp_cmdsn,
1079                            session->max_cmdsn, session->cmdsn,
1080                            session->queued_cmdsn);
1081                 return -ENOSPC;
1082         }
1083         return 0;
1084 }
1085
1086 static int iscsi_xmit_task(struct iscsi_conn *conn)
1087 {
1088         struct iscsi_task *task = conn->task;
1089         int rc;
1090
1091         __iscsi_get_task(task);
1092         spin_unlock_bh(&conn->session->lock);
1093         rc = conn->session->tt->xmit_task(task);
1094         spin_lock_bh(&conn->session->lock);
1095         __iscsi_put_task(task);
1096         if (!rc)
1097                 /* done with this task */
1098                 conn->task = NULL;
1099         return rc;
1100 }
1101
1102 /**
1103  * iscsi_requeue_task - requeue task to run from session workqueue
1104  * @task: task to requeue
1105  *
1106  * LLDs that need to run a task from the session workqueue should call
1107  * this. The session lock must be held. This should only be called
1108  * by software drivers.
1109  */
1110 void iscsi_requeue_task(struct iscsi_task *task)
1111 {
1112         struct iscsi_conn *conn = task->conn;
1113
1114         list_move_tail(&task->running, &conn->requeue);
1115         scsi_queue_work(conn->session->host, &conn->xmitwork);
1116 }
1117 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1118
1119 /**
1120  * iscsi_data_xmit - xmit any command into the scheduled connection
1121  * @conn: iscsi connection
1122  *
1123  * Notes:
1124  *      The function can return -EAGAIN in which case the caller must
1125  *      re-schedule it again later or recover. '0' return code means
1126  *      successful xmit.
1127  **/
1128 static int iscsi_data_xmit(struct iscsi_conn *conn)
1129 {
1130         int rc = 0;
1131
1132         spin_lock_bh(&conn->session->lock);
1133         if (unlikely(conn->suspend_tx)) {
1134                 debug_scsi("conn %d Tx suspended!\n", conn->id);
1135                 spin_unlock_bh(&conn->session->lock);
1136                 return -ENODATA;
1137         }
1138
1139         if (conn->task) {
1140                 rc = iscsi_xmit_task(conn);
1141                 if (rc)
1142                         goto again;
1143         }
1144
1145         /*
1146          * process mgmt pdus like nops before commands since we should
1147          * only have one nop-out as a ping from us and targets should not
1148          * overflow us with nop-ins
1149          */
1150 check_mgmt:
1151         while (!list_empty(&conn->mgmtqueue)) {
1152                 conn->task = list_entry(conn->mgmtqueue.next,
1153                                          struct iscsi_task, running);
1154                 if (iscsi_prep_mgmt_task(conn, conn->task)) {
1155                         __iscsi_put_task(conn->task);
1156                         conn->task = NULL;
1157                         continue;
1158                 }
1159                 rc = iscsi_xmit_task(conn);
1160                 if (rc)
1161                         goto again;
1162         }
1163
1164         /* process pending command queue */
1165         while (!list_empty(&conn->xmitqueue)) {
1166                 if (conn->tmf_state == TMF_QUEUED)
1167                         break;
1168
1169                 conn->task = list_entry(conn->xmitqueue.next,
1170                                          struct iscsi_task, running);
1171                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1172                         fail_command(conn, conn->task, DID_IMM_RETRY << 16);
1173                         continue;
1174                 }
1175                 rc = iscsi_prep_scsi_cmd_pdu(conn->task);
1176                 if (rc) {
1177                         if (rc == -ENOMEM) {
1178                                 conn->task = NULL;
1179                                 goto again;
1180                         } else
1181                                 fail_command(conn, conn->task, DID_ABORT << 16);
1182                         continue;
1183                 }
1184                 rc = iscsi_xmit_task(conn);
1185                 if (rc)
1186                         goto again;
1187                 /*
1188                  * we could continuously get new task requests so
1189                  * we need to check the mgmt queue for nops that need to
1190                  * be sent to aviod starvation
1191                  */
1192                 if (!list_empty(&conn->mgmtqueue))
1193                         goto check_mgmt;
1194         }
1195
1196         while (!list_empty(&conn->requeue)) {
1197                 if (conn->session->fast_abort && conn->tmf_state != TMF_INITIAL)
1198                         break;
1199
1200                 /*
1201                  * we always do fastlogout - conn stop code will clean up.
1202                  */
1203                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1204                         break;
1205
1206                 conn->task = list_entry(conn->requeue.next,
1207                                          struct iscsi_task, running);
1208                 conn->task->state = ISCSI_TASK_RUNNING;
1209                 list_move_tail(conn->requeue.next, &conn->run_list);
1210                 rc = iscsi_xmit_task(conn);
1211                 if (rc)
1212                         goto again;
1213                 if (!list_empty(&conn->mgmtqueue))
1214                         goto check_mgmt;
1215         }
1216         spin_unlock_bh(&conn->session->lock);
1217         return -ENODATA;
1218
1219 again:
1220         if (unlikely(conn->suspend_tx))
1221                 rc = -ENODATA;
1222         spin_unlock_bh(&conn->session->lock);
1223         return rc;
1224 }
1225
1226 static void iscsi_xmitworker(struct work_struct *work)
1227 {
1228         struct iscsi_conn *conn =
1229                 container_of(work, struct iscsi_conn, xmitwork);
1230         int rc;
1231         /*
1232          * serialize Xmit worker on a per-connection basis.
1233          */
1234         do {
1235                 rc = iscsi_data_xmit(conn);
1236         } while (rc >= 0 || rc == -EAGAIN);
1237 }
1238
1239 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1240                                                   struct scsi_cmnd *sc)
1241 {
1242         struct iscsi_task *task;
1243
1244         if (!__kfifo_get(conn->session->cmdpool.queue,
1245                          (void *) &task, sizeof(void *)))
1246                 return NULL;
1247
1248         sc->SCp.phase = conn->session->age;
1249         sc->SCp.ptr = (char *) task;
1250
1251         atomic_set(&task->refcount, 1);
1252         task->state = ISCSI_TASK_PENDING;
1253         task->conn = conn;
1254         task->sc = sc;
1255         INIT_LIST_HEAD(&task->running);
1256         return task;
1257 }
1258
1259 enum {
1260         FAILURE_BAD_HOST = 1,
1261         FAILURE_SESSION_FAILED,
1262         FAILURE_SESSION_FREED,
1263         FAILURE_WINDOW_CLOSED,
1264         FAILURE_OOM,
1265         FAILURE_SESSION_TERMINATE,
1266         FAILURE_SESSION_IN_RECOVERY,
1267         FAILURE_SESSION_RECOVERY_TIMEOUT,
1268         FAILURE_SESSION_LOGGING_OUT,
1269         FAILURE_SESSION_NOT_READY,
1270 };
1271
1272 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
1273 {
1274         struct iscsi_cls_session *cls_session;
1275         struct Scsi_Host *host;
1276         int reason = 0;
1277         struct iscsi_session *session;
1278         struct iscsi_conn *conn;
1279         struct iscsi_task *task = NULL;
1280
1281         sc->scsi_done = done;
1282         sc->result = 0;
1283         sc->SCp.ptr = NULL;
1284
1285         host = sc->device->host;
1286         spin_unlock(host->host_lock);
1287
1288         cls_session = starget_to_session(scsi_target(sc->device));
1289         session = cls_session->dd_data;
1290         spin_lock(&session->lock);
1291
1292         reason = iscsi_session_chkready(cls_session);
1293         if (reason) {
1294                 sc->result = reason;
1295                 goto fault;
1296         }
1297
1298         /*
1299          * ISCSI_STATE_FAILED is a temp. state. The recovery
1300          * code will decide what is best to do with command queued
1301          * during this time
1302          */
1303         if (session->state != ISCSI_STATE_LOGGED_IN &&
1304             session->state != ISCSI_STATE_FAILED) {
1305                 /*
1306                  * to handle the race between when we set the recovery state
1307                  * and block the session we requeue here (commands could
1308                  * be entering our queuecommand while a block is starting
1309                  * up because the block code is not locked)
1310                  */
1311                 switch (session->state) {
1312                 case ISCSI_STATE_IN_RECOVERY:
1313                         reason = FAILURE_SESSION_IN_RECOVERY;
1314                         goto reject;
1315                 case ISCSI_STATE_LOGGING_OUT:
1316                         reason = FAILURE_SESSION_LOGGING_OUT;
1317                         goto reject;
1318                 case ISCSI_STATE_RECOVERY_FAILED:
1319                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1320                         sc->result = DID_TRANSPORT_FAILFAST << 16;
1321                         break;
1322                 case ISCSI_STATE_TERMINATE:
1323                         reason = FAILURE_SESSION_TERMINATE;
1324                         sc->result = DID_NO_CONNECT << 16;
1325                         break;
1326                 default:
1327                         reason = FAILURE_SESSION_FREED;
1328                         sc->result = DID_NO_CONNECT << 16;
1329                 }
1330                 goto fault;
1331         }
1332
1333         conn = session->leadconn;
1334         if (!conn) {
1335                 reason = FAILURE_SESSION_FREED;
1336                 sc->result = DID_NO_CONNECT << 16;
1337                 goto fault;
1338         }
1339
1340         if (iscsi_check_cmdsn_window_closed(conn)) {
1341                 reason = FAILURE_WINDOW_CLOSED;
1342                 goto reject;
1343         }
1344
1345         task = iscsi_alloc_task(conn, sc);
1346         if (!task) {
1347                 reason = FAILURE_OOM;
1348                 goto reject;
1349         }
1350         list_add_tail(&task->running, &conn->xmitqueue);
1351
1352         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
1353                 reason = iscsi_prep_scsi_cmd_pdu(task);
1354                 if (reason) {
1355                         if (reason == -ENOMEM) {
1356                                 reason = FAILURE_OOM;
1357                                 goto prepd_reject;
1358                         } else {
1359                                 sc->result = DID_ABORT << 16;
1360                                 goto prepd_fault;
1361                         }
1362                 }
1363                 if (session->tt->xmit_task(task)) {
1364                         reason = FAILURE_SESSION_NOT_READY;
1365                         goto prepd_reject;
1366                 }
1367         } else
1368                 scsi_queue_work(session->host, &conn->xmitwork);
1369
1370         session->queued_cmdsn++;
1371         spin_unlock(&session->lock);
1372         spin_lock(host->host_lock);
1373         return 0;
1374
1375 prepd_reject:
1376         sc->scsi_done = NULL;
1377         iscsi_complete_command(task);
1378 reject:
1379         spin_unlock(&session->lock);
1380         debug_scsi("cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason);
1381         spin_lock(host->host_lock);
1382         return SCSI_MLQUEUE_TARGET_BUSY;
1383
1384 prepd_fault:
1385         sc->scsi_done = NULL;
1386         iscsi_complete_command(task);
1387 fault:
1388         spin_unlock(&session->lock);
1389         debug_scsi("iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason);
1390         if (!scsi_bidi_cmnd(sc))
1391                 scsi_set_resid(sc, scsi_bufflen(sc));
1392         else {
1393                 scsi_out(sc)->resid = scsi_out(sc)->length;
1394                 scsi_in(sc)->resid = scsi_in(sc)->length;
1395         }
1396         done(sc);
1397         spin_lock(host->host_lock);
1398         return 0;
1399 }
1400 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1401
1402 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth)
1403 {
1404         if (depth > ISCSI_MAX_CMD_PER_LUN)
1405                 depth = ISCSI_MAX_CMD_PER_LUN;
1406         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
1407         return sdev->queue_depth;
1408 }
1409 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
1410
1411 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
1412 {
1413         struct iscsi_session *session = cls_session->dd_data;
1414
1415         spin_lock_bh(&session->lock);
1416         if (session->state != ISCSI_STATE_LOGGED_IN) {
1417                 session->state = ISCSI_STATE_RECOVERY_FAILED;
1418                 if (session->leadconn)
1419                         wake_up(&session->leadconn->ehwait);
1420         }
1421         spin_unlock_bh(&session->lock);
1422 }
1423 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
1424
1425 int iscsi_eh_target_reset(struct scsi_cmnd *sc)
1426 {
1427         struct iscsi_cls_session *cls_session;
1428         struct iscsi_session *session;
1429         struct iscsi_conn *conn;
1430
1431         cls_session = starget_to_session(scsi_target(sc->device));
1432         session = cls_session->dd_data;
1433         conn = session->leadconn;
1434
1435         mutex_lock(&session->eh_mutex);
1436         spin_lock_bh(&session->lock);
1437         if (session->state == ISCSI_STATE_TERMINATE) {
1438 failed:
1439                 debug_scsi("failing target reset: session terminated "
1440                            "[CID %d age %d]\n", conn->id, session->age);
1441                 spin_unlock_bh(&session->lock);
1442                 mutex_unlock(&session->eh_mutex);
1443                 return FAILED;
1444         }
1445
1446         spin_unlock_bh(&session->lock);
1447         mutex_unlock(&session->eh_mutex);
1448         /*
1449          * we drop the lock here but the leadconn cannot be destoyed while
1450          * we are in the scsi eh
1451          */
1452         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1453
1454         debug_scsi("iscsi_eh_target_reset wait for relogin\n");
1455         wait_event_interruptible(conn->ehwait,
1456                                  session->state == ISCSI_STATE_TERMINATE ||
1457                                  session->state == ISCSI_STATE_LOGGED_IN ||
1458                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
1459         if (signal_pending(current))
1460                 flush_signals(current);
1461
1462         mutex_lock(&session->eh_mutex);
1463         spin_lock_bh(&session->lock);
1464         if (session->state == ISCSI_STATE_LOGGED_IN)
1465                 iscsi_session_printk(KERN_INFO, session,
1466                                      "target reset succeeded\n");
1467         else
1468                 goto failed;
1469         spin_unlock_bh(&session->lock);
1470         mutex_unlock(&session->eh_mutex);
1471         return SUCCESS;
1472 }
1473 EXPORT_SYMBOL_GPL(iscsi_eh_target_reset);
1474
1475 static void iscsi_tmf_timedout(unsigned long data)
1476 {
1477         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1478         struct iscsi_session *session = conn->session;
1479
1480         spin_lock(&session->lock);
1481         if (conn->tmf_state == TMF_QUEUED) {
1482                 conn->tmf_state = TMF_TIMEDOUT;
1483                 debug_scsi("tmf timedout\n");
1484                 /* unblock eh_abort() */
1485                 wake_up(&conn->ehwait);
1486         }
1487         spin_unlock(&session->lock);
1488 }
1489
1490 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1491                                    struct iscsi_tm *hdr, int age,
1492                                    int timeout)
1493 {
1494         struct iscsi_session *session = conn->session;
1495         struct iscsi_task *task;
1496
1497         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1498                                       NULL, 0);
1499         if (!task) {
1500                 spin_unlock_bh(&session->lock);
1501                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1502                 spin_lock_bh(&session->lock);
1503                 debug_scsi("tmf exec failure\n");
1504                 return -EPERM;
1505         }
1506         conn->tmfcmd_pdus_cnt++;
1507         conn->tmf_timer.expires = timeout * HZ + jiffies;
1508         conn->tmf_timer.function = iscsi_tmf_timedout;
1509         conn->tmf_timer.data = (unsigned long)conn;
1510         add_timer(&conn->tmf_timer);
1511         debug_scsi("tmf set timeout\n");
1512
1513         spin_unlock_bh(&session->lock);
1514         mutex_unlock(&session->eh_mutex);
1515
1516         /*
1517          * block eh thread until:
1518          *
1519          * 1) tmf response
1520          * 2) tmf timeout
1521          * 3) session is terminated or restarted or userspace has
1522          * given up on recovery
1523          */
1524         wait_event_interruptible(conn->ehwait, age != session->age ||
1525                                  session->state != ISCSI_STATE_LOGGED_IN ||
1526                                  conn->tmf_state != TMF_QUEUED);
1527         if (signal_pending(current))
1528                 flush_signals(current);
1529         del_timer_sync(&conn->tmf_timer);
1530
1531         mutex_lock(&session->eh_mutex);
1532         spin_lock_bh(&session->lock);
1533         /* if the session drops it will clean up the task */
1534         if (age != session->age ||
1535             session->state != ISCSI_STATE_LOGGED_IN)
1536                 return -ENOTCONN;
1537         return 0;
1538 }
1539
1540 /*
1541  * Fail commands. session lock held and recv side suspended and xmit
1542  * thread flushed
1543  */
1544 static void fail_all_commands(struct iscsi_conn *conn, unsigned lun,
1545                               int error)
1546 {
1547         struct iscsi_task *task, *tmp;
1548
1549         if (conn->task && (conn->task->sc->device->lun == lun || lun == -1))
1550                 conn->task = NULL;
1551
1552         /* flush pending */
1553         list_for_each_entry_safe(task, tmp, &conn->xmitqueue, running) {
1554                 if (lun == task->sc->device->lun || lun == -1) {
1555                         debug_scsi("failing pending sc %p itt 0x%x\n",
1556                                    task->sc, task->itt);
1557                         fail_command(conn, task, error << 16);
1558                 }
1559         }
1560
1561         list_for_each_entry_safe(task, tmp, &conn->requeue, running) {
1562                 if (lun == task->sc->device->lun || lun == -1) {
1563                         debug_scsi("failing requeued sc %p itt 0x%x\n",
1564                                    task->sc, task->itt);
1565                         fail_command(conn, task, error << 16);
1566                 }
1567         }
1568
1569         /* fail all other running */
1570         list_for_each_entry_safe(task, tmp, &conn->run_list, running) {
1571                 if (lun == task->sc->device->lun || lun == -1) {
1572                         debug_scsi("failing in progress sc %p itt 0x%x\n",
1573                                    task->sc, task->itt);
1574                         fail_command(conn, task, error << 16);
1575                 }
1576         }
1577 }
1578
1579 void iscsi_suspend_tx(struct iscsi_conn *conn)
1580 {
1581         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1582         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1583                 scsi_flush_work(conn->session->host);
1584 }
1585 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1586
1587 static void iscsi_start_tx(struct iscsi_conn *conn)
1588 {
1589         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1590         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1591                 scsi_queue_work(conn->session->host, &conn->xmitwork);
1592 }
1593
1594 static enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *scmd)
1595 {
1596         struct iscsi_cls_session *cls_session;
1597         struct iscsi_session *session;
1598         struct iscsi_conn *conn;
1599         enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED;
1600
1601         cls_session = starget_to_session(scsi_target(scmd->device));
1602         session = cls_session->dd_data;
1603
1604         debug_scsi("scsi cmd %p timedout\n", scmd);
1605
1606         spin_lock(&session->lock);
1607         if (session->state != ISCSI_STATE_LOGGED_IN) {
1608                 /*
1609                  * We are probably in the middle of iscsi recovery so let
1610                  * that complete and handle the error.
1611                  */
1612                 rc = BLK_EH_RESET_TIMER;
1613                 goto done;
1614         }
1615
1616         conn = session->leadconn;
1617         if (!conn) {
1618                 /* In the middle of shuting down */
1619                 rc = BLK_EH_RESET_TIMER;
1620                 goto done;
1621         }
1622
1623         if (!conn->recv_timeout && !conn->ping_timeout)
1624                 goto done;
1625         /*
1626          * if the ping timedout then we are in the middle of cleaning up
1627          * and can let the iscsi eh handle it
1628          */
1629         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1630                             (conn->ping_timeout * HZ), jiffies))
1631                 rc = BLK_EH_RESET_TIMER;
1632         /*
1633          * if we are about to check the transport then give the command
1634          * more time
1635          */
1636         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ),
1637                            jiffies))
1638                 rc = BLK_EH_RESET_TIMER;
1639         /* if in the middle of checking the transport then give us more time */
1640         if (conn->ping_task)
1641                 rc = BLK_EH_RESET_TIMER;
1642 done:
1643         spin_unlock(&session->lock);
1644         debug_scsi("return %s\n", rc == BLK_EH_RESET_TIMER ?
1645                                         "timer reset" : "nh");
1646         return rc;
1647 }
1648
1649 static void iscsi_check_transport_timeouts(unsigned long data)
1650 {
1651         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1652         struct iscsi_session *session = conn->session;
1653         unsigned long recv_timeout, next_timeout = 0, last_recv;
1654
1655         spin_lock(&session->lock);
1656         if (session->state != ISCSI_STATE_LOGGED_IN)
1657                 goto done;
1658
1659         recv_timeout = conn->recv_timeout;
1660         if (!recv_timeout)
1661                 goto done;
1662
1663         recv_timeout *= HZ;
1664         last_recv = conn->last_recv;
1665         if (conn->ping_task &&
1666             time_before_eq(conn->last_ping + (conn->ping_timeout * HZ),
1667                            jiffies)) {
1668                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
1669                                   "expired, last rx %lu, last ping %lu, "
1670                                   "now %lu\n", conn->ping_timeout, last_recv,
1671                                   conn->last_ping, jiffies);
1672                 spin_unlock(&session->lock);
1673                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1674                 return;
1675         }
1676
1677         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
1678                 /* send a ping to try to provoke some traffic */
1679                 debug_scsi("Sending nopout as ping on conn %p\n", conn);
1680                 iscsi_send_nopout(conn, NULL);
1681                 next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
1682         } else
1683                 next_timeout = last_recv + recv_timeout;
1684
1685         debug_scsi("Setting next tmo %lu\n", next_timeout);
1686         mod_timer(&conn->transport_timer, next_timeout);
1687 done:
1688         spin_unlock(&session->lock);
1689 }
1690
1691 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
1692                                       struct iscsi_tm *hdr)
1693 {
1694         memset(hdr, 0, sizeof(*hdr));
1695         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1696         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
1697         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1698         memcpy(hdr->lun, task->lun, sizeof(hdr->lun));
1699         hdr->rtt = task->hdr_itt;
1700         hdr->refcmdsn = task->cmdsn;
1701 }
1702
1703 int iscsi_eh_abort(struct scsi_cmnd *sc)
1704 {
1705         struct iscsi_cls_session *cls_session;
1706         struct iscsi_session *session;
1707         struct iscsi_conn *conn;
1708         struct iscsi_task *task;
1709         struct iscsi_tm *hdr;
1710         int rc, age;
1711
1712         cls_session = starget_to_session(scsi_target(sc->device));
1713         session = cls_session->dd_data;
1714
1715         mutex_lock(&session->eh_mutex);
1716         spin_lock_bh(&session->lock);
1717         /*
1718          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
1719          * got the command.
1720          */
1721         if (!sc->SCp.ptr) {
1722                 debug_scsi("sc never reached iscsi layer or it completed.\n");
1723                 spin_unlock_bh(&session->lock);
1724                 mutex_unlock(&session->eh_mutex);
1725                 return SUCCESS;
1726         }
1727
1728         /*
1729          * If we are not logged in or we have started a new session
1730          * then let the host reset code handle this
1731          */
1732         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
1733             sc->SCp.phase != session->age) {
1734                 spin_unlock_bh(&session->lock);
1735                 mutex_unlock(&session->eh_mutex);
1736                 return FAILED;
1737         }
1738
1739         conn = session->leadconn;
1740         conn->eh_abort_cnt++;
1741         age = session->age;
1742
1743         task = (struct iscsi_task *)sc->SCp.ptr;
1744         debug_scsi("aborting [sc %p itt 0x%x]\n", sc, task->itt);
1745
1746         /* task completed before time out */
1747         if (!task->sc) {
1748                 debug_scsi("sc completed while abort in progress\n");
1749                 goto success;
1750         }
1751
1752         if (task->state == ISCSI_TASK_PENDING) {
1753                 fail_command(conn, task, DID_ABORT << 16);
1754                 goto success;
1755         }
1756
1757         /* only have one tmf outstanding at a time */
1758         if (conn->tmf_state != TMF_INITIAL)
1759                 goto failed;
1760         conn->tmf_state = TMF_QUEUED;
1761
1762         hdr = &conn->tmhdr;
1763         iscsi_prep_abort_task_pdu(task, hdr);
1764
1765         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) {
1766                 rc = FAILED;
1767                 goto failed;
1768         }
1769
1770         switch (conn->tmf_state) {
1771         case TMF_SUCCESS:
1772                 spin_unlock_bh(&session->lock);
1773                 /*
1774                  * stop tx side incase the target had sent a abort rsp but
1775                  * the initiator was still writing out data.
1776                  */
1777                 iscsi_suspend_tx(conn);
1778                 /*
1779                  * we do not stop the recv side because targets have been
1780                  * good and have never sent us a successful tmf response
1781                  * then sent more data for the cmd.
1782                  */
1783                 spin_lock(&session->lock);
1784                 fail_command(conn, task, DID_ABORT << 16);
1785                 conn->tmf_state = TMF_INITIAL;
1786                 spin_unlock(&session->lock);
1787                 iscsi_start_tx(conn);
1788                 goto success_unlocked;
1789         case TMF_TIMEDOUT:
1790                 spin_unlock_bh(&session->lock);
1791                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1792                 goto failed_unlocked;
1793         case TMF_NOT_FOUND:
1794                 if (!sc->SCp.ptr) {
1795                         conn->tmf_state = TMF_INITIAL;
1796                         /* task completed before tmf abort response */
1797                         debug_scsi("sc completed while abort in progress\n");
1798                         goto success;
1799                 }
1800                 /* fall through */
1801         default:
1802                 conn->tmf_state = TMF_INITIAL;
1803                 goto failed;
1804         }
1805
1806 success:
1807         spin_unlock_bh(&session->lock);
1808 success_unlocked:
1809         debug_scsi("abort success [sc %lx itt 0x%x]\n", (long)sc, task->itt);
1810         mutex_unlock(&session->eh_mutex);
1811         return SUCCESS;
1812
1813 failed:
1814         spin_unlock_bh(&session->lock);
1815 failed_unlocked:
1816         debug_scsi("abort failed [sc %p itt 0x%x]\n", sc,
1817                     task ? task->itt : 0);
1818         mutex_unlock(&session->eh_mutex);
1819         return FAILED;
1820 }
1821 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1822
1823 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
1824 {
1825         memset(hdr, 0, sizeof(*hdr));
1826         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1827         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
1828         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1829         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
1830         hdr->rtt = RESERVED_ITT;
1831 }
1832
1833 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
1834 {
1835         struct iscsi_cls_session *cls_session;
1836         struct iscsi_session *session;
1837         struct iscsi_conn *conn;
1838         struct iscsi_tm *hdr;
1839         int rc = FAILED;
1840
1841         cls_session = starget_to_session(scsi_target(sc->device));
1842         session = cls_session->dd_data;
1843
1844         debug_scsi("LU Reset [sc %p lun %u]\n", sc, sc->device->lun);
1845
1846         mutex_lock(&session->eh_mutex);
1847         spin_lock_bh(&session->lock);
1848         /*
1849          * Just check if we are not logged in. We cannot check for
1850          * the phase because the reset could come from a ioctl.
1851          */
1852         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
1853                 goto unlock;
1854         conn = session->leadconn;
1855
1856         /* only have one tmf outstanding at a time */
1857         if (conn->tmf_state != TMF_INITIAL)
1858                 goto unlock;
1859         conn->tmf_state = TMF_QUEUED;
1860
1861         hdr = &conn->tmhdr;
1862         iscsi_prep_lun_reset_pdu(sc, hdr);
1863
1864         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
1865                                     session->lu_reset_timeout)) {
1866                 rc = FAILED;
1867                 goto unlock;
1868         }
1869
1870         switch (conn->tmf_state) {
1871         case TMF_SUCCESS:
1872                 break;
1873         case TMF_TIMEDOUT:
1874                 spin_unlock_bh(&session->lock);
1875                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1876                 goto done;
1877         default:
1878                 conn->tmf_state = TMF_INITIAL;
1879                 goto unlock;
1880         }
1881
1882         rc = SUCCESS;
1883         spin_unlock_bh(&session->lock);
1884
1885         iscsi_suspend_tx(conn);
1886
1887         spin_lock_bh(&session->lock);
1888         fail_all_commands(conn, sc->device->lun, DID_ERROR);
1889         conn->tmf_state = TMF_INITIAL;
1890         spin_unlock_bh(&session->lock);
1891
1892         iscsi_start_tx(conn);
1893         goto done;
1894
1895 unlock:
1896         spin_unlock_bh(&session->lock);
1897 done:
1898         debug_scsi("iscsi_eh_device_reset %s\n",
1899                   rc == SUCCESS ? "SUCCESS" : "FAILED");
1900         mutex_unlock(&session->eh_mutex);
1901         return rc;
1902 }
1903 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
1904
1905 /*
1906  * Pre-allocate a pool of @max items of @item_size. By default, the pool
1907  * should be accessed via kfifo_{get,put} on q->queue.
1908  * Optionally, the caller can obtain the array of object pointers
1909  * by passing in a non-NULL @items pointer
1910  */
1911 int
1912 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
1913 {
1914         int i, num_arrays = 1;
1915
1916         memset(q, 0, sizeof(*q));
1917
1918         q->max = max;
1919
1920         /* If the user passed an items pointer, he wants a copy of
1921          * the array. */
1922         if (items)
1923                 num_arrays++;
1924         q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL);
1925         if (q->pool == NULL)
1926                 goto enomem;
1927
1928         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
1929                               GFP_KERNEL, NULL);
1930         if (q->queue == ERR_PTR(-ENOMEM))
1931                 goto enomem;
1932
1933         for (i = 0; i < max; i++) {
1934                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
1935                 if (q->pool[i] == NULL) {
1936                         q->max = i;
1937                         goto enomem;
1938                 }
1939                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
1940         }
1941
1942         if (items) {
1943                 *items = q->pool + max;
1944                 memcpy(*items, q->pool, max * sizeof(void *));
1945         }
1946
1947         return 0;
1948
1949 enomem:
1950         iscsi_pool_free(q);
1951         return -ENOMEM;
1952 }
1953 EXPORT_SYMBOL_GPL(iscsi_pool_init);
1954
1955 void iscsi_pool_free(struct iscsi_pool *q)
1956 {
1957         int i;
1958
1959         for (i = 0; i < q->max; i++)
1960                 kfree(q->pool[i]);
1961         if (q->pool)
1962                 kfree(q->pool);
1963 }
1964 EXPORT_SYMBOL_GPL(iscsi_pool_free);
1965
1966 /**
1967  * iscsi_host_add - add host to system
1968  * @shost: scsi host
1969  * @pdev: parent device
1970  *
1971  * This should be called by partial offload and software iscsi drivers
1972  * to add a host to the system.
1973  */
1974 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
1975 {
1976         if (!shost->can_queue)
1977                 shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
1978
1979         return scsi_add_host(shost, pdev);
1980 }
1981 EXPORT_SYMBOL_GPL(iscsi_host_add);
1982
1983 /**
1984  * iscsi_host_alloc - allocate a host and driver data
1985  * @sht: scsi host template
1986  * @dd_data_size: driver host data size
1987  * @qdepth: default device queue depth
1988  *
1989  * This should be called by partial offload and software iscsi drivers.
1990  * To access the driver specific memory use the iscsi_host_priv() macro.
1991  */
1992 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
1993                                    int dd_data_size, uint16_t qdepth)
1994 {
1995         struct Scsi_Host *shost;
1996         struct iscsi_host *ihost;
1997
1998         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
1999         if (!shost)
2000                 return NULL;
2001         shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out;
2002
2003         if (qdepth > ISCSI_MAX_CMD_PER_LUN || qdepth < 1) {
2004                 if (qdepth != 0)
2005                         printk(KERN_ERR "iscsi: invalid queue depth of %d. "
2006                                "Queue depth must be between 1 and %d.\n",
2007                                qdepth, ISCSI_MAX_CMD_PER_LUN);
2008                 qdepth = ISCSI_DEF_CMD_PER_LUN;
2009         }
2010         shost->cmd_per_lun = qdepth;
2011
2012         ihost = shost_priv(shost);
2013         spin_lock_init(&ihost->lock);
2014         ihost->state = ISCSI_HOST_SETUP;
2015         ihost->num_sessions = 0;
2016         init_waitqueue_head(&ihost->session_removal_wq);
2017         return shost;
2018 }
2019 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2020
2021 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2022 {
2023         iscsi_session_failure(cls_session, ISCSI_ERR_INVALID_HOST);
2024 }
2025
2026 /**
2027  * iscsi_host_remove - remove host and sessions
2028  * @shost: scsi host
2029  *
2030  * If there are any sessions left, this will initiate the removal and wait
2031  * for the completion.
2032  */
2033 void iscsi_host_remove(struct Scsi_Host *shost)
2034 {
2035         struct iscsi_host *ihost = shost_priv(shost);
2036         unsigned long flags;
2037
2038         spin_lock_irqsave(&ihost->lock, flags);
2039         ihost->state = ISCSI_HOST_REMOVED;
2040         spin_unlock_irqrestore(&ihost->lock, flags);
2041
2042         iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2043         wait_event_interruptible(ihost->session_removal_wq,
2044                                  ihost->num_sessions == 0);
2045         if (signal_pending(current))
2046                 flush_signals(current);
2047
2048         scsi_remove_host(shost);
2049 }
2050 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2051
2052 void iscsi_host_free(struct Scsi_Host *shost)
2053 {
2054         struct iscsi_host *ihost = shost_priv(shost);
2055
2056         kfree(ihost->netdev);
2057         kfree(ihost->hwaddress);
2058         kfree(ihost->initiatorname);
2059         scsi_host_put(shost);
2060 }
2061 EXPORT_SYMBOL_GPL(iscsi_host_free);
2062
2063 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2064 {
2065         struct iscsi_host *ihost = shost_priv(shost);
2066         unsigned long flags;
2067
2068         shost = scsi_host_get(shost);
2069         if (!shost) {
2070                 printk(KERN_ERR "Invalid state. Cannot notify host removal "
2071                       "of session teardown event because host already "
2072                       "removed.\n");
2073                 return;
2074         }
2075
2076         spin_lock_irqsave(&ihost->lock, flags);
2077         ihost->num_sessions--;
2078         if (ihost->num_sessions == 0)
2079                 wake_up(&ihost->session_removal_wq);
2080         spin_unlock_irqrestore(&ihost->lock, flags);
2081         scsi_host_put(shost);
2082 }
2083
2084 /**
2085  * iscsi_session_setup - create iscsi cls session and host and session
2086  * @iscsit: iscsi transport template
2087  * @shost: scsi host
2088  * @cmds_max: session can queue
2089  * @cmd_task_size: LLD task private data size
2090  * @initial_cmdsn: initial CmdSN
2091  *
2092  * This can be used by software iscsi_transports that allocate
2093  * a session per scsi host.
2094  *
2095  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2096  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2097  * for nop handling and login/logout requests.
2098  */
2099 struct iscsi_cls_session *
2100 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2101                     uint16_t cmds_max, int cmd_task_size,
2102                     uint32_t initial_cmdsn, unsigned int id)
2103 {
2104         struct iscsi_host *ihost = shost_priv(shost);
2105         struct iscsi_session *session;
2106         struct iscsi_cls_session *cls_session;
2107         int cmd_i, scsi_cmds, total_cmds = cmds_max;
2108         unsigned long flags;
2109
2110         spin_lock_irqsave(&ihost->lock, flags);
2111         if (ihost->state == ISCSI_HOST_REMOVED) {
2112                 spin_unlock_irqrestore(&ihost->lock, flags);
2113                 return NULL;
2114         }
2115         ihost->num_sessions++;
2116         spin_unlock_irqrestore(&ihost->lock, flags);
2117
2118         if (!total_cmds)
2119                 total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2120         /*
2121          * The iscsi layer needs some tasks for nop handling and tmfs,
2122          * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2123          * + 1 command for scsi IO.
2124          */
2125         if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2126                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2127                        "must be a power of two that is at least %d.\n",
2128                        total_cmds, ISCSI_TOTAL_CMDS_MIN);
2129                 goto dec_session_count;
2130         }
2131
2132         if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2133                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2134                        "must be a power of 2 less than or equal to %d.\n",
2135                        cmds_max, ISCSI_TOTAL_CMDS_MAX);
2136                 total_cmds = ISCSI_TOTAL_CMDS_MAX;
2137         }
2138
2139         if (!is_power_of_2(total_cmds)) {
2140                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2141                        "must be a power of 2.\n", total_cmds);
2142                 total_cmds = rounddown_pow_of_two(total_cmds);
2143                 if (total_cmds < ISCSI_TOTAL_CMDS_MIN)
2144                         return NULL;
2145                 printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n",
2146                        total_cmds);
2147         }
2148         scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2149
2150         cls_session = iscsi_alloc_session(shost, iscsit,
2151                                           sizeof(struct iscsi_session));
2152         if (!cls_session)
2153                 goto dec_session_count;
2154         session = cls_session->dd_data;
2155         session->cls_session = cls_session;
2156         session->host = shost;
2157         session->state = ISCSI_STATE_FREE;
2158         session->fast_abort = 1;
2159         session->lu_reset_timeout = 15;
2160         session->abort_timeout = 10;
2161         session->scsi_cmds_max = scsi_cmds;
2162         session->cmds_max = total_cmds;
2163         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2164         session->exp_cmdsn = initial_cmdsn + 1;
2165         session->max_cmdsn = initial_cmdsn + 1;
2166         session->max_r2t = 1;
2167         session->tt = iscsit;
2168         mutex_init(&session->eh_mutex);
2169         spin_lock_init(&session->lock);
2170
2171         /* initialize SCSI PDU commands pool */
2172         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2173                             (void***)&session->cmds,
2174                             cmd_task_size + sizeof(struct iscsi_task)))
2175                 goto cmdpool_alloc_fail;
2176
2177         /* pre-format cmds pool with ITT */
2178         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2179                 struct iscsi_task *task = session->cmds[cmd_i];
2180
2181                 if (cmd_task_size)
2182                         task->dd_data = &task[1];
2183                 task->itt = cmd_i;
2184                 INIT_LIST_HEAD(&task->running);
2185         }
2186
2187         if (!try_module_get(iscsit->owner))
2188                 goto module_get_fail;
2189
2190         if (iscsi_add_session(cls_session, id))
2191                 goto cls_session_fail;
2192
2193         return cls_session;
2194
2195 cls_session_fail:
2196         module_put(iscsit->owner);
2197 module_get_fail:
2198         iscsi_pool_free(&session->cmdpool);
2199 cmdpool_alloc_fail:
2200         iscsi_free_session(cls_session);
2201 dec_session_count:
2202         iscsi_host_dec_session_cnt(shost);
2203         return NULL;
2204 }
2205 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2206
2207 /**
2208  * iscsi_session_teardown - destroy session, host, and cls_session
2209  * @cls_session: iscsi session
2210  *
2211  * The driver must have called iscsi_remove_session before
2212  * calling this.
2213  */
2214 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2215 {
2216         struct iscsi_session *session = cls_session->dd_data;
2217         struct module *owner = cls_session->transport->owner;
2218         struct Scsi_Host *shost = session->host;
2219
2220         iscsi_pool_free(&session->cmdpool);
2221
2222         kfree(session->password);
2223         kfree(session->password_in);
2224         kfree(session->username);
2225         kfree(session->username_in);
2226         kfree(session->targetname);
2227         kfree(session->initiatorname);
2228         kfree(session->ifacename);
2229
2230         iscsi_destroy_session(cls_session);
2231         iscsi_host_dec_session_cnt(shost);
2232         module_put(owner);
2233 }
2234 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2235
2236 /**
2237  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2238  * @cls_session: iscsi_cls_session
2239  * @dd_size: private driver data size
2240  * @conn_idx: cid
2241  */
2242 struct iscsi_cls_conn *
2243 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2244                  uint32_t conn_idx)
2245 {
2246         struct iscsi_session *session = cls_session->dd_data;
2247         struct iscsi_conn *conn;
2248         struct iscsi_cls_conn *cls_conn;
2249         char *data;
2250
2251         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2252                                      conn_idx);
2253         if (!cls_conn)
2254                 return NULL;
2255         conn = cls_conn->dd_data;
2256         memset(conn, 0, sizeof(*conn) + dd_size);
2257
2258         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2259         conn->session = session;
2260         conn->cls_conn = cls_conn;
2261         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2262         conn->id = conn_idx;
2263         conn->exp_statsn = 0;
2264         conn->tmf_state = TMF_INITIAL;
2265
2266         init_timer(&conn->transport_timer);
2267         conn->transport_timer.data = (unsigned long)conn;
2268         conn->transport_timer.function = iscsi_check_transport_timeouts;
2269
2270         INIT_LIST_HEAD(&conn->run_list);
2271         INIT_LIST_HEAD(&conn->mgmt_run_list);
2272         INIT_LIST_HEAD(&conn->mgmtqueue);
2273         INIT_LIST_HEAD(&conn->xmitqueue);
2274         INIT_LIST_HEAD(&conn->requeue);
2275         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2276
2277         /* allocate login_task used for the login/text sequences */
2278         spin_lock_bh(&session->lock);
2279         if (!__kfifo_get(session->cmdpool.queue,
2280                          (void*)&conn->login_task,
2281                          sizeof(void*))) {
2282                 spin_unlock_bh(&session->lock);
2283                 goto login_task_alloc_fail;
2284         }
2285         spin_unlock_bh(&session->lock);
2286
2287         data = (char *) __get_free_pages(GFP_KERNEL,
2288                                          get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2289         if (!data)
2290                 goto login_task_data_alloc_fail;
2291         conn->login_task->data = conn->data = data;
2292
2293         init_timer(&conn->tmf_timer);
2294         init_waitqueue_head(&conn->ehwait);
2295
2296         return cls_conn;
2297
2298 login_task_data_alloc_fail:
2299         __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task,
2300                     sizeof(void*));
2301 login_task_alloc_fail:
2302         iscsi_destroy_conn(cls_conn);
2303         return NULL;
2304 }
2305 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2306
2307 /**
2308  * iscsi_conn_teardown - teardown iscsi connection
2309  * cls_conn: iscsi class connection
2310  *
2311  * TODO: we may need to make this into a two step process
2312  * like scsi-mls remove + put host
2313  */
2314 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2315 {
2316         struct iscsi_conn *conn = cls_conn->dd_data;
2317         struct iscsi_session *session = conn->session;
2318         unsigned long flags;
2319
2320         del_timer_sync(&conn->transport_timer);
2321
2322         spin_lock_bh(&session->lock);
2323         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
2324         if (session->leadconn == conn) {
2325                 /*
2326                  * leading connection? then give up on recovery.
2327                  */
2328                 session->state = ISCSI_STATE_TERMINATE;
2329                 wake_up(&conn->ehwait);
2330         }
2331         spin_unlock_bh(&session->lock);
2332
2333         /*
2334          * Block until all in-progress commands for this connection
2335          * time out or fail.
2336          */
2337         for (;;) {
2338                 spin_lock_irqsave(session->host->host_lock, flags);
2339                 if (!session->host->host_busy) { /* OK for ERL == 0 */
2340                         spin_unlock_irqrestore(session->host->host_lock, flags);
2341                         break;
2342                 }
2343                 spin_unlock_irqrestore(session->host->host_lock, flags);
2344                 msleep_interruptible(500);
2345                 iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): "
2346                                   "host_busy %d host_failed %d\n",
2347                                   session->host->host_busy,
2348                                   session->host->host_failed);
2349                 /*
2350                  * force eh_abort() to unblock
2351                  */
2352                 wake_up(&conn->ehwait);
2353         }
2354
2355         /* flush queued up work because we free the connection below */
2356         iscsi_suspend_tx(conn);
2357
2358         spin_lock_bh(&session->lock);
2359         free_pages((unsigned long) conn->data,
2360                    get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2361         kfree(conn->persistent_address);
2362         __kfifo_put(session->cmdpool.queue, (void*)&conn->login_task,
2363                     sizeof(void*));
2364         if (session->leadconn == conn)
2365                 session->leadconn = NULL;
2366         spin_unlock_bh(&session->lock);
2367
2368         iscsi_destroy_conn(cls_conn);
2369 }
2370 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
2371
2372 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
2373 {
2374         struct iscsi_conn *conn = cls_conn->dd_data;
2375         struct iscsi_session *session = conn->session;
2376
2377         if (!session) {
2378                 iscsi_conn_printk(KERN_ERR, conn,
2379                                   "can't start unbound connection\n");
2380                 return -EPERM;
2381         }
2382
2383         if ((session->imm_data_en || !session->initial_r2t_en) &&
2384              session->first_burst > session->max_burst) {
2385                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
2386                                   "first_burst %d max_burst %d\n",
2387                                   session->first_burst, session->max_burst);
2388                 return -EINVAL;
2389         }
2390
2391         if (conn->ping_timeout && !conn->recv_timeout) {
2392                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
2393                                   "zero. Using 5 seconds\n.");
2394                 conn->recv_timeout = 5;
2395         }
2396
2397         if (conn->recv_timeout && !conn->ping_timeout) {
2398                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
2399                                   "zero. Using 5 seconds.\n");
2400                 conn->ping_timeout = 5;
2401         }
2402
2403         spin_lock_bh(&session->lock);
2404         conn->c_stage = ISCSI_CONN_STARTED;
2405         session->state = ISCSI_STATE_LOGGED_IN;
2406         session->queued_cmdsn = session->cmdsn;
2407
2408         conn->last_recv = jiffies;
2409         conn->last_ping = jiffies;
2410         if (conn->recv_timeout && conn->ping_timeout)
2411                 mod_timer(&conn->transport_timer,
2412                           jiffies + (conn->recv_timeout * HZ));
2413
2414         switch(conn->stop_stage) {
2415         case STOP_CONN_RECOVER:
2416                 /*
2417                  * unblock eh_abort() if it is blocked. re-try all
2418                  * commands after successful recovery
2419                  */
2420                 conn->stop_stage = 0;
2421                 conn->tmf_state = TMF_INITIAL;
2422                 session->age++;
2423                 if (session->age == 16)
2424                         session->age = 0;
2425                 break;
2426         case STOP_CONN_TERM:
2427                 conn->stop_stage = 0;
2428                 break;
2429         default:
2430                 break;
2431         }
2432         spin_unlock_bh(&session->lock);
2433
2434         iscsi_unblock_session(session->cls_session);
2435         wake_up(&conn->ehwait);
2436         return 0;
2437 }
2438 EXPORT_SYMBOL_GPL(iscsi_conn_start);
2439
2440 static void
2441 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
2442 {
2443         struct iscsi_task *task, *tmp;
2444
2445         /* handle pending */
2446         list_for_each_entry_safe(task, tmp, &conn->mgmtqueue, running) {
2447                 debug_scsi("flushing pending mgmt task itt 0x%x\n", task->itt);
2448                 /* release ref from prep task */
2449                 __iscsi_put_task(task);
2450         }
2451
2452         /* handle running */
2453         list_for_each_entry_safe(task, tmp, &conn->mgmt_run_list, running) {
2454                 debug_scsi("flushing running mgmt task itt 0x%x\n", task->itt);
2455                 /* release ref from prep task */
2456                 __iscsi_put_task(task);
2457         }
2458
2459         conn->task = NULL;
2460 }
2461
2462 static void iscsi_start_session_recovery(struct iscsi_session *session,
2463                                          struct iscsi_conn *conn, int flag)
2464 {
2465         int old_stop_stage;
2466
2467         del_timer_sync(&conn->transport_timer);
2468
2469         mutex_lock(&session->eh_mutex);
2470         spin_lock_bh(&session->lock);
2471         if (conn->stop_stage == STOP_CONN_TERM) {
2472                 spin_unlock_bh(&session->lock);
2473                 mutex_unlock(&session->eh_mutex);
2474                 return;
2475         }
2476
2477         /*
2478          * When this is called for the in_login state, we only want to clean
2479          * up the login task and connection. We do not need to block and set
2480          * the recovery state again
2481          */
2482         if (flag == STOP_CONN_TERM)
2483                 session->state = ISCSI_STATE_TERMINATE;
2484         else if (conn->stop_stage != STOP_CONN_RECOVER)
2485                 session->state = ISCSI_STATE_IN_RECOVERY;
2486
2487         old_stop_stage = conn->stop_stage;
2488         conn->stop_stage = flag;
2489         conn->c_stage = ISCSI_CONN_STOPPED;
2490         spin_unlock_bh(&session->lock);
2491
2492         iscsi_suspend_tx(conn);
2493         /*
2494          * for connection level recovery we should not calculate
2495          * header digest. conn->hdr_size used for optimization
2496          * in hdr_extract() and will be re-negotiated at
2497          * set_param() time.
2498          */
2499         if (flag == STOP_CONN_RECOVER) {
2500                 conn->hdrdgst_en = 0;
2501                 conn->datadgst_en = 0;
2502                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
2503                     old_stop_stage != STOP_CONN_RECOVER) {
2504                         debug_scsi("blocking session\n");
2505                         iscsi_block_session(session->cls_session);
2506                 }
2507         }
2508
2509         /*
2510          * flush queues.
2511          */
2512         spin_lock_bh(&session->lock);
2513         if (flag == STOP_CONN_RECOVER)
2514                 fail_all_commands(conn, -1, DID_TRANSPORT_DISRUPTED);
2515         else
2516                 fail_all_commands(conn, -1, DID_ERROR);
2517         flush_control_queues(session, conn);
2518         spin_unlock_bh(&session->lock);
2519         mutex_unlock(&session->eh_mutex);
2520 }
2521
2522 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
2523 {
2524         struct iscsi_conn *conn = cls_conn->dd_data;
2525         struct iscsi_session *session = conn->session;
2526
2527         switch (flag) {
2528         case STOP_CONN_RECOVER:
2529         case STOP_CONN_TERM:
2530                 iscsi_start_session_recovery(session, conn, flag);
2531                 break;
2532         default:
2533                 iscsi_conn_printk(KERN_ERR, conn,
2534                                   "invalid stop flag %d\n", flag);
2535         }
2536 }
2537 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
2538
2539 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
2540                     struct iscsi_cls_conn *cls_conn, int is_leading)
2541 {
2542         struct iscsi_session *session = cls_session->dd_data;
2543         struct iscsi_conn *conn = cls_conn->dd_data;
2544
2545         spin_lock_bh(&session->lock);
2546         if (is_leading)
2547                 session->leadconn = conn;
2548         spin_unlock_bh(&session->lock);
2549
2550         /*
2551          * Unblock xmitworker(), Login Phase will pass through.
2552          */
2553         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
2554         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
2555         return 0;
2556 }
2557 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
2558
2559
2560 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
2561                     enum iscsi_param param, char *buf, int buflen)
2562 {
2563         struct iscsi_conn *conn = cls_conn->dd_data;
2564         struct iscsi_session *session = conn->session;
2565         uint32_t value;
2566
2567         switch(param) {
2568         case ISCSI_PARAM_FAST_ABORT:
2569                 sscanf(buf, "%d", &session->fast_abort);
2570                 break;
2571         case ISCSI_PARAM_ABORT_TMO:
2572                 sscanf(buf, "%d", &session->abort_timeout);
2573                 break;
2574         case ISCSI_PARAM_LU_RESET_TMO:
2575                 sscanf(buf, "%d", &session->lu_reset_timeout);
2576                 break;
2577         case ISCSI_PARAM_PING_TMO:
2578                 sscanf(buf, "%d", &conn->ping_timeout);
2579                 break;
2580         case ISCSI_PARAM_RECV_TMO:
2581                 sscanf(buf, "%d", &conn->recv_timeout);
2582                 break;
2583         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2584                 sscanf(buf, "%d", &conn->max_recv_dlength);
2585                 break;
2586         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2587                 sscanf(buf, "%d", &conn->max_xmit_dlength);
2588                 break;
2589         case ISCSI_PARAM_HDRDGST_EN:
2590                 sscanf(buf, "%d", &conn->hdrdgst_en);
2591                 break;
2592         case ISCSI_PARAM_DATADGST_EN:
2593                 sscanf(buf, "%d", &conn->datadgst_en);
2594                 break;
2595         case ISCSI_PARAM_INITIAL_R2T_EN:
2596                 sscanf(buf, "%d", &session->initial_r2t_en);
2597                 break;
2598         case ISCSI_PARAM_MAX_R2T:
2599                 sscanf(buf, "%d", &session->max_r2t);
2600                 break;
2601         case ISCSI_PARAM_IMM_DATA_EN:
2602                 sscanf(buf, "%d", &session->imm_data_en);
2603                 break;
2604         case ISCSI_PARAM_FIRST_BURST:
2605                 sscanf(buf, "%d", &session->first_burst);
2606                 break;
2607         case ISCSI_PARAM_MAX_BURST:
2608                 sscanf(buf, "%d", &session->max_burst);
2609                 break;
2610         case ISCSI_PARAM_PDU_INORDER_EN:
2611                 sscanf(buf, "%d", &session->pdu_inorder_en);
2612                 break;
2613         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2614                 sscanf(buf, "%d", &session->dataseq_inorder_en);
2615                 break;
2616         case ISCSI_PARAM_ERL:
2617                 sscanf(buf, "%d", &session->erl);
2618                 break;
2619         case ISCSI_PARAM_IFMARKER_EN:
2620                 sscanf(buf, "%d", &value);
2621                 BUG_ON(value);
2622                 break;
2623         case ISCSI_PARAM_OFMARKER_EN:
2624                 sscanf(buf, "%d", &value);
2625                 BUG_ON(value);
2626                 break;
2627         case ISCSI_PARAM_EXP_STATSN:
2628                 sscanf(buf, "%u", &conn->exp_statsn);
2629                 break;
2630         case ISCSI_PARAM_USERNAME:
2631                 kfree(session->username);
2632                 session->username = kstrdup(buf, GFP_KERNEL);
2633                 if (!session->username)
2634                         return -ENOMEM;
2635                 break;
2636         case ISCSI_PARAM_USERNAME_IN:
2637                 kfree(session->username_in);
2638                 session->username_in = kstrdup(buf, GFP_KERNEL);
2639                 if (!session->username_in)
2640                         return -ENOMEM;
2641                 break;
2642         case ISCSI_PARAM_PASSWORD:
2643                 kfree(session->password);
2644                 session->password = kstrdup(buf, GFP_KERNEL);
2645                 if (!session->password)
2646                         return -ENOMEM;
2647                 break;
2648         case ISCSI_PARAM_PASSWORD_IN:
2649                 kfree(session->password_in);
2650                 session->password_in = kstrdup(buf, GFP_KERNEL);
2651                 if (!session->password_in)
2652                         return -ENOMEM;
2653                 break;
2654         case ISCSI_PARAM_TARGET_NAME:
2655                 /* this should not change between logins */
2656                 if (session->targetname)
2657                         break;
2658
2659                 session->targetname = kstrdup(buf, GFP_KERNEL);
2660                 if (!session->targetname)
2661                         return -ENOMEM;
2662                 break;
2663         case ISCSI_PARAM_TPGT:
2664                 sscanf(buf, "%d", &session->tpgt);
2665                 break;
2666         case ISCSI_PARAM_PERSISTENT_PORT:
2667                 sscanf(buf, "%d", &conn->persistent_port);
2668                 break;
2669         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2670                 /*
2671                  * this is the address returned in discovery so it should
2672                  * not change between logins.
2673                  */
2674                 if (conn->persistent_address)
2675                         break;
2676
2677                 conn->persistent_address = kstrdup(buf, GFP_KERNEL);
2678                 if (!conn->persistent_address)
2679                         return -ENOMEM;
2680                 break;
2681         case ISCSI_PARAM_IFACE_NAME:
2682                 if (!session->ifacename)
2683                         session->ifacename = kstrdup(buf, GFP_KERNEL);
2684                 break;
2685         case ISCSI_PARAM_INITIATOR_NAME:
2686                 if (!session->initiatorname)
2687                         session->initiatorname = kstrdup(buf, GFP_KERNEL);
2688                 break;
2689         default:
2690                 return -ENOSYS;
2691         }
2692
2693         return 0;
2694 }
2695 EXPORT_SYMBOL_GPL(iscsi_set_param);
2696
2697 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
2698                             enum iscsi_param param, char *buf)
2699 {
2700         struct iscsi_session *session = cls_session->dd_data;
2701         int len;
2702
2703         switch(param) {
2704         case ISCSI_PARAM_FAST_ABORT:
2705                 len = sprintf(buf, "%d\n", session->fast_abort);
2706                 break;
2707         case ISCSI_PARAM_ABORT_TMO:
2708                 len = sprintf(buf, "%d\n", session->abort_timeout);
2709                 break;
2710         case ISCSI_PARAM_LU_RESET_TMO:
2711                 len = sprintf(buf, "%d\n", session->lu_reset_timeout);
2712                 break;
2713         case ISCSI_PARAM_INITIAL_R2T_EN:
2714                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
2715                 break;
2716         case ISCSI_PARAM_MAX_R2T:
2717                 len = sprintf(buf, "%hu\n", session->max_r2t);
2718                 break;
2719         case ISCSI_PARAM_IMM_DATA_EN:
2720                 len = sprintf(buf, "%d\n", session->imm_data_en);
2721                 break;
2722         case ISCSI_PARAM_FIRST_BURST:
2723                 len = sprintf(buf, "%u\n", session->first_burst);
2724                 break;
2725         case ISCSI_PARAM_MAX_BURST:
2726                 len = sprintf(buf, "%u\n", session->max_burst);
2727                 break;
2728         case ISCSI_PARAM_PDU_INORDER_EN:
2729                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
2730                 break;
2731         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2732                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
2733                 break;
2734         case ISCSI_PARAM_ERL:
2735                 len = sprintf(buf, "%d\n", session->erl);
2736                 break;
2737         case ISCSI_PARAM_TARGET_NAME:
2738                 len = sprintf(buf, "%s\n", session->targetname);
2739                 break;
2740         case ISCSI_PARAM_TPGT:
2741                 len = sprintf(buf, "%d\n", session->tpgt);
2742                 break;
2743         case ISCSI_PARAM_USERNAME:
2744                 len = sprintf(buf, "%s\n", session->username);
2745                 break;
2746         case ISCSI_PARAM_USERNAME_IN:
2747                 len = sprintf(buf, "%s\n", session->username_in);
2748                 break;
2749         case ISCSI_PARAM_PASSWORD:
2750                 len = sprintf(buf, "%s\n", session->password);
2751                 break;
2752         case ISCSI_PARAM_PASSWORD_IN:
2753                 len = sprintf(buf, "%s\n", session->password_in);
2754                 break;
2755         case ISCSI_PARAM_IFACE_NAME:
2756                 len = sprintf(buf, "%s\n", session->ifacename);
2757                 break;
2758         case ISCSI_PARAM_INITIATOR_NAME:
2759                 if (!session->initiatorname)
2760                         len = sprintf(buf, "%s\n", "unknown");
2761                 else
2762                         len = sprintf(buf, "%s\n", session->initiatorname);
2763                 break;
2764         default:
2765                 return -ENOSYS;
2766         }
2767
2768         return len;
2769 }
2770 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
2771
2772 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
2773                          enum iscsi_param param, char *buf)
2774 {
2775         struct iscsi_conn *conn = cls_conn->dd_data;
2776         int len;
2777
2778         switch(param) {
2779         case ISCSI_PARAM_PING_TMO:
2780                 len = sprintf(buf, "%u\n", conn->ping_timeout);
2781                 break;
2782         case ISCSI_PARAM_RECV_TMO:
2783                 len = sprintf(buf, "%u\n", conn->recv_timeout);
2784                 break;
2785         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2786                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
2787                 break;
2788         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2789                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
2790                 break;
2791         case ISCSI_PARAM_HDRDGST_EN:
2792                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
2793                 break;
2794         case ISCSI_PARAM_DATADGST_EN:
2795                 len = sprintf(buf, "%d\n", conn->datadgst_en);
2796                 break;
2797         case ISCSI_PARAM_IFMARKER_EN:
2798                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
2799                 break;
2800         case ISCSI_PARAM_OFMARKER_EN:
2801                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
2802                 break;
2803         case ISCSI_PARAM_EXP_STATSN:
2804                 len = sprintf(buf, "%u\n", conn->exp_statsn);
2805                 break;
2806         case ISCSI_PARAM_PERSISTENT_PORT:
2807                 len = sprintf(buf, "%d\n", conn->persistent_port);
2808                 break;
2809         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2810                 len = sprintf(buf, "%s\n", conn->persistent_address);
2811                 break;
2812         default:
2813                 return -ENOSYS;
2814         }
2815
2816         return len;
2817 }
2818 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
2819
2820 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2821                          char *buf)
2822 {
2823         struct iscsi_host *ihost = shost_priv(shost);
2824         int len;
2825
2826         switch (param) {
2827         case ISCSI_HOST_PARAM_NETDEV_NAME:
2828                 if (!ihost->netdev)
2829                         len = sprintf(buf, "%s\n", "default");
2830                 else
2831                         len = sprintf(buf, "%s\n", ihost->netdev);
2832                 break;
2833         case ISCSI_HOST_PARAM_HWADDRESS:
2834                 if (!ihost->hwaddress)
2835                         len = sprintf(buf, "%s\n", "default");
2836                 else
2837                         len = sprintf(buf, "%s\n", ihost->hwaddress);
2838                 break;
2839         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2840                 if (!ihost->initiatorname)
2841                         len = sprintf(buf, "%s\n", "unknown");
2842                 else
2843                         len = sprintf(buf, "%s\n", ihost->initiatorname);
2844                 break;
2845         case ISCSI_HOST_PARAM_IPADDRESS:
2846                 if (!strlen(ihost->local_address))
2847                         len = sprintf(buf, "%s\n", "unknown");
2848                 else
2849                         len = sprintf(buf, "%s\n",
2850                                       ihost->local_address);
2851                 break;
2852         default:
2853                 return -ENOSYS;
2854         }
2855
2856         return len;
2857 }
2858 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
2859
2860 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2861                          char *buf, int buflen)
2862 {
2863         struct iscsi_host *ihost = shost_priv(shost);
2864
2865         switch (param) {
2866         case ISCSI_HOST_PARAM_NETDEV_NAME:
2867                 if (!ihost->netdev)
2868                         ihost->netdev = kstrdup(buf, GFP_KERNEL);
2869                 break;
2870         case ISCSI_HOST_PARAM_HWADDRESS:
2871                 if (!ihost->hwaddress)
2872                         ihost->hwaddress = kstrdup(buf, GFP_KERNEL);
2873                 break;
2874         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2875                 if (!ihost->initiatorname)
2876                         ihost->initiatorname = kstrdup(buf, GFP_KERNEL);
2877                 break;
2878         default:
2879                 return -ENOSYS;
2880         }
2881
2882         return 0;
2883 }
2884 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
2885
2886 MODULE_AUTHOR("Mike Christie");
2887 MODULE_DESCRIPTION("iSCSI library functions");
2888 MODULE_LICENSE("GPL");