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