[SCSI] iscsi: Some fixes in preparation for bidirectional support - exp_datasn
[safe/jmp/linux-2.6] / drivers / scsi / iscsi_tcp.c
1 /*
2  * iSCSI Initiator over TCP/IP Data-Path
3  *
4  * Copyright (C) 2004 Dmitry Yusupov
5  * Copyright (C) 2004 Alex Aizman
6  * Copyright (C) 2005 - 2006 Mike Christie
7  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
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
12  * by 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, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * See the file COPYING included with this distribution for more details.
21  *
22  * Credits:
23  *      Christoph Hellwig
24  *      FUJITA Tomonori
25  *      Arne Redlich
26  *      Zhenyu Wang
27  */
28
29 #include <linux/types.h>
30 #include <linux/list.h>
31 #include <linux/inet.h>
32 #include <linux/blkdev.h>
33 #include <linux/crypto.h>
34 #include <linux/delay.h>
35 #include <linux/kfifo.h>
36 #include <linux/scatterlist.h>
37 #include <linux/mutex.h>
38 #include <net/tcp.h>
39 #include <scsi/scsi_cmnd.h>
40 #include <scsi/scsi_host.h>
41 #include <scsi/scsi.h>
42 #include <scsi/scsi_transport_iscsi.h>
43
44 #include "iscsi_tcp.h"
45
46 MODULE_AUTHOR("Dmitry Yusupov <dmitry_yus@yahoo.com>, "
47               "Alex Aizman <itn780@yahoo.com>");
48 MODULE_DESCRIPTION("iSCSI/TCP data-path");
49 MODULE_LICENSE("GPL");
50 /* #define DEBUG_TCP */
51 #define DEBUG_ASSERT
52
53 #ifdef DEBUG_TCP
54 #define debug_tcp(fmt...) printk(KERN_INFO "tcp: " fmt)
55 #else
56 #define debug_tcp(fmt...)
57 #endif
58
59 #ifndef DEBUG_ASSERT
60 #ifdef BUG_ON
61 #undef BUG_ON
62 #endif
63 #define BUG_ON(expr)
64 #endif
65
66 static unsigned int iscsi_max_lun = 512;
67 module_param_named(max_lun, iscsi_max_lun, uint, S_IRUGO);
68
69 static inline void
70 iscsi_buf_init_iov(struct iscsi_buf *ibuf, char *vbuf, int size)
71 {
72         ibuf->sg.page = virt_to_page(vbuf);
73         ibuf->sg.offset = offset_in_page(vbuf);
74         ibuf->sg.length = size;
75         ibuf->sent = 0;
76         ibuf->use_sendmsg = 1;
77 }
78
79 static inline void
80 iscsi_buf_init_sg(struct iscsi_buf *ibuf, struct scatterlist *sg)
81 {
82         ibuf->sg.page = sg->page;
83         ibuf->sg.offset = sg->offset;
84         ibuf->sg.length = sg->length;
85         /*
86          * Fastpath: sg element fits into single page
87          */
88         if (sg->length + sg->offset <= PAGE_SIZE && !PageSlab(sg->page))
89                 ibuf->use_sendmsg = 0;
90         else
91                 ibuf->use_sendmsg = 1;
92         ibuf->sent = 0;
93 }
94
95 static inline int
96 iscsi_buf_left(struct iscsi_buf *ibuf)
97 {
98         int rc;
99
100         rc = ibuf->sg.length - ibuf->sent;
101         BUG_ON(rc < 0);
102         return rc;
103 }
104
105 static inline void
106 iscsi_hdr_digest(struct iscsi_conn *conn, struct iscsi_buf *buf,
107                  u8* crc)
108 {
109         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
110
111         crypto_hash_digest(&tcp_conn->tx_hash, &buf->sg, buf->sg.length, crc);
112         buf->sg.length = tcp_conn->hdr_size;
113 }
114
115 static inline int
116 iscsi_hdr_extract(struct iscsi_tcp_conn *tcp_conn)
117 {
118         struct sk_buff *skb = tcp_conn->in.skb;
119
120         tcp_conn->in.zero_copy_hdr = 0;
121
122         if (tcp_conn->in.copy >= tcp_conn->hdr_size &&
123             tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER) {
124                 /*
125                  * Zero-copy PDU Header: using connection context
126                  * to store header pointer.
127                  */
128                 if (skb_shinfo(skb)->frag_list == NULL &&
129                     !skb_shinfo(skb)->nr_frags) {
130                         tcp_conn->in.hdr = (struct iscsi_hdr *)
131                                 ((char*)skb->data + tcp_conn->in.offset);
132                         tcp_conn->in.zero_copy_hdr = 1;
133                 } else {
134                         /* ignoring return code since we checked
135                          * in.copy before */
136                         skb_copy_bits(skb, tcp_conn->in.offset,
137                                 &tcp_conn->hdr, tcp_conn->hdr_size);
138                         tcp_conn->in.hdr = &tcp_conn->hdr;
139                 }
140                 tcp_conn->in.offset += tcp_conn->hdr_size;
141                 tcp_conn->in.copy -= tcp_conn->hdr_size;
142         } else {
143                 int hdr_remains;
144                 int copylen;
145
146                 /*
147                  * PDU header scattered across SKB's,
148                  * copying it... This'll happen quite rarely.
149                  */
150
151                 if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER)
152                         tcp_conn->in.hdr_offset = 0;
153
154                 hdr_remains = tcp_conn->hdr_size - tcp_conn->in.hdr_offset;
155                 BUG_ON(hdr_remains <= 0);
156
157                 copylen = min(tcp_conn->in.copy, hdr_remains);
158                 skb_copy_bits(skb, tcp_conn->in.offset,
159                         (char*)&tcp_conn->hdr + tcp_conn->in.hdr_offset,
160                         copylen);
161
162                 debug_tcp("PDU gather offset %d bytes %d in.offset %d "
163                        "in.copy %d\n", tcp_conn->in.hdr_offset, copylen,
164                        tcp_conn->in.offset, tcp_conn->in.copy);
165
166                 tcp_conn->in.offset += copylen;
167                 tcp_conn->in.copy -= copylen;
168                 if (copylen < hdr_remains)  {
169                         tcp_conn->in_progress = IN_PROGRESS_HEADER_GATHER;
170                         tcp_conn->in.hdr_offset += copylen;
171                         return -EAGAIN;
172                 }
173                 tcp_conn->in.hdr = &tcp_conn->hdr;
174                 tcp_conn->discontiguous_hdr_cnt++;
175                 tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
176         }
177
178         return 0;
179 }
180
181 /*
182  * must be called with session lock
183  */
184 static void
185 iscsi_tcp_cleanup_ctask(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
186 {
187         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
188         struct iscsi_r2t_info *r2t;
189         struct scsi_cmnd *sc;
190
191         /* flush ctask's r2t queues */
192         while (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*))) {
193                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
194                             sizeof(void*));
195                 debug_scsi("iscsi_tcp_cleanup_ctask pending r2t dropped\n");
196         }
197
198         sc = ctask->sc;
199         if (unlikely(!sc))
200                 return;
201
202         tcp_ctask->xmstate = XMSTATE_IDLE;
203         tcp_ctask->r2t = NULL;
204 }
205
206 /**
207  * iscsi_data_rsp - SCSI Data-In Response processing
208  * @conn: iscsi connection
209  * @ctask: scsi command task
210  **/
211 static int
212 iscsi_data_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
213 {
214         int rc;
215         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
216         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
217         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)tcp_conn->in.hdr;
218         struct iscsi_session *session = conn->session;
219         int datasn = be32_to_cpu(rhdr->datasn);
220
221         rc = iscsi_check_assign_cmdsn(session, (struct iscsi_nopin*)rhdr);
222         if (rc)
223                 return rc;
224         /*
225          * setup Data-In byte counter (gets decremented..)
226          */
227         ctask->data_count = tcp_conn->in.datalen;
228
229         if (tcp_conn->in.datalen == 0)
230                 return 0;
231
232         if (tcp_ctask->exp_datasn != datasn) {
233                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->datasn(%d)\n",
234                           __FUNCTION__, tcp_ctask->exp_datasn, datasn);
235                 return ISCSI_ERR_DATASN;
236         }
237
238         tcp_ctask->exp_datasn++;
239
240         tcp_ctask->data_offset = be32_to_cpu(rhdr->offset);
241         if (tcp_ctask->data_offset + tcp_conn->in.datalen > ctask->total_length)
242                 return ISCSI_ERR_DATA_OFFSET;
243
244         if (rhdr->flags & ISCSI_FLAG_DATA_STATUS) {
245                 struct scsi_cmnd *sc = ctask->sc;
246
247                 conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
248                 if (rhdr->flags & ISCSI_FLAG_DATA_UNDERFLOW) {
249                         int res_count = be32_to_cpu(rhdr->residual_count);
250
251                         if (res_count > 0 &&
252                             res_count <= sc->request_bufflen) {
253                                 sc->resid = res_count;
254                                 sc->result = (DID_OK << 16) | rhdr->cmd_status;
255                         } else
256                                 sc->result = (DID_BAD_TARGET << 16) |
257                                         rhdr->cmd_status;
258                 } else if (rhdr->flags & ISCSI_FLAG_DATA_OVERFLOW) {
259                         sc->resid = be32_to_cpu(rhdr->residual_count);
260                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
261                 } else
262                         sc->result = (DID_OK << 16) | rhdr->cmd_status;
263         }
264
265         conn->datain_pdus_cnt++;
266         return 0;
267 }
268
269 /**
270  * iscsi_solicit_data_init - initialize first Data-Out
271  * @conn: iscsi connection
272  * @ctask: scsi command task
273  * @r2t: R2T info
274  *
275  * Notes:
276  *      Initialize first Data-Out within this R2T sequence and finds
277  *      proper data_offset within this SCSI command.
278  *
279  *      This function is called with connection lock taken.
280  **/
281 static void
282 iscsi_solicit_data_init(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
283                         struct iscsi_r2t_info *r2t)
284 {
285         struct iscsi_data *hdr;
286         struct scsi_cmnd *sc = ctask->sc;
287
288         hdr = &r2t->dtask.hdr;
289         memset(hdr, 0, sizeof(struct iscsi_data));
290         hdr->ttt = r2t->ttt;
291         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
292         r2t->solicit_datasn++;
293         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
294         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
295         hdr->itt = ctask->hdr->itt;
296         hdr->exp_statsn = r2t->exp_statsn;
297         hdr->offset = cpu_to_be32(r2t->data_offset);
298         if (r2t->data_length > conn->max_xmit_dlength) {
299                 hton24(hdr->dlength, conn->max_xmit_dlength);
300                 r2t->data_count = conn->max_xmit_dlength;
301                 hdr->flags = 0;
302         } else {
303                 hton24(hdr->dlength, r2t->data_length);
304                 r2t->data_count = r2t->data_length;
305                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
306         }
307         conn->dataout_pdus_cnt++;
308
309         r2t->sent = 0;
310
311         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
312                            sizeof(struct iscsi_hdr));
313
314         if (sc->use_sg) {
315                 int i, sg_count = 0;
316                 struct scatterlist *sg = sc->request_buffer;
317
318                 r2t->sg = NULL;
319                 for (i = 0; i < sc->use_sg; i++, sg += 1) {
320                         /* FIXME: prefetch ? */
321                         if (sg_count + sg->length > r2t->data_offset) {
322                                 int page_offset;
323
324                                 /* sg page found! */
325
326                                 /* offset within this page */
327                                 page_offset = r2t->data_offset - sg_count;
328
329                                 /* fill in this buffer */
330                                 iscsi_buf_init_sg(&r2t->sendbuf, sg);
331                                 r2t->sendbuf.sg.offset += page_offset;
332                                 r2t->sendbuf.sg.length -= page_offset;
333
334                                 /* xmit logic will continue with next one */
335                                 r2t->sg = sg + 1;
336                                 break;
337                         }
338                         sg_count += sg->length;
339                 }
340                 BUG_ON(r2t->sg == NULL);
341         } else {
342                 iscsi_buf_init_iov(&r2t->sendbuf,
343                             (char*)sc->request_buffer + r2t->data_offset,
344                             r2t->data_count);
345                 r2t->sg = NULL;
346         }
347 }
348
349 /**
350  * iscsi_r2t_rsp - iSCSI R2T Response processing
351  * @conn: iscsi connection
352  * @ctask: scsi command task
353  **/
354 static int
355 iscsi_r2t_rsp(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
356 {
357         struct iscsi_r2t_info *r2t;
358         struct iscsi_session *session = conn->session;
359         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
360         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
361         struct iscsi_r2t_rsp *rhdr = (struct iscsi_r2t_rsp *)tcp_conn->in.hdr;
362         int r2tsn = be32_to_cpu(rhdr->r2tsn);
363         int rc;
364
365         if (tcp_conn->in.datalen) {
366                 printk(KERN_ERR "iscsi_tcp: invalid R2t with datalen %d\n",
367                        tcp_conn->in.datalen);
368                 return ISCSI_ERR_DATALEN;
369         }
370
371         if (tcp_ctask->exp_datasn != r2tsn){
372                 debug_tcp("%s: ctask->exp_datasn(%d) != rhdr->r2tsn(%d)\n",
373                           __FUNCTION__, tcp_ctask->exp_datasn, r2tsn);
374                 return ISCSI_ERR_R2TSN;
375         }
376
377         rc = iscsi_check_assign_cmdsn(session, (struct iscsi_nopin*)rhdr);
378         if (rc)
379                 return rc;
380
381         /* fill-in new R2T associated with the task */
382         spin_lock(&session->lock);
383         if (!ctask->sc || ctask->mtask ||
384              session->state != ISCSI_STATE_LOGGED_IN) {
385                 printk(KERN_INFO "iscsi_tcp: dropping R2T itt %d in "
386                        "recovery...\n", ctask->itt);
387                 spin_unlock(&session->lock);
388                 return 0;
389         }
390
391         rc = __kfifo_get(tcp_ctask->r2tpool.queue, (void*)&r2t, sizeof(void*));
392         BUG_ON(!rc);
393
394         r2t->exp_statsn = rhdr->statsn;
395         r2t->data_length = be32_to_cpu(rhdr->data_length);
396         if (r2t->data_length == 0) {
397                 printk(KERN_ERR "iscsi_tcp: invalid R2T with zero data len\n");
398                 spin_unlock(&session->lock);
399                 return ISCSI_ERR_DATALEN;
400         }
401
402         if (r2t->data_length > session->max_burst)
403                 debug_scsi("invalid R2T with data len %u and max burst %u."
404                            "Attempting to execute request.\n",
405                             r2t->data_length, session->max_burst);
406
407         r2t->data_offset = be32_to_cpu(rhdr->data_offset);
408         if (r2t->data_offset + r2t->data_length > ctask->total_length) {
409                 spin_unlock(&session->lock);
410                 printk(KERN_ERR "iscsi_tcp: invalid R2T with data len %u at "
411                        "offset %u and total length %d\n", r2t->data_length,
412                        r2t->data_offset, ctask->total_length);
413                 return ISCSI_ERR_DATALEN;
414         }
415
416         r2t->ttt = rhdr->ttt; /* no flip */
417         r2t->solicit_datasn = 0;
418
419         iscsi_solicit_data_init(conn, ctask, r2t);
420
421         tcp_ctask->exp_datasn = r2tsn + 1;
422         __kfifo_put(tcp_ctask->r2tqueue, (void*)&r2t, sizeof(void*));
423         tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
424         list_move_tail(&ctask->running, &conn->xmitqueue);
425
426         scsi_queue_work(session->host, &conn->xmitwork);
427         conn->r2t_pdus_cnt++;
428         spin_unlock(&session->lock);
429
430         return 0;
431 }
432
433 static int
434 iscsi_tcp_hdr_recv(struct iscsi_conn *conn)
435 {
436         int rc = 0, opcode, ahslen;
437         struct iscsi_hdr *hdr;
438         struct iscsi_session *session = conn->session;
439         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
440         uint32_t cdgst, rdgst = 0, itt;
441
442         hdr = tcp_conn->in.hdr;
443
444         /* verify PDU length */
445         tcp_conn->in.datalen = ntoh24(hdr->dlength);
446         if (tcp_conn->in.datalen > conn->max_recv_dlength) {
447                 printk(KERN_ERR "iscsi_tcp: datalen %d > %d\n",
448                        tcp_conn->in.datalen, conn->max_recv_dlength);
449                 return ISCSI_ERR_DATALEN;
450         }
451         tcp_conn->data_copied = 0;
452
453         /* read AHS */
454         ahslen = hdr->hlength << 2;
455         tcp_conn->in.offset += ahslen;
456         tcp_conn->in.copy -= ahslen;
457         if (tcp_conn->in.copy < 0) {
458                 printk(KERN_ERR "iscsi_tcp: can't handle AHS with length "
459                        "%d bytes\n", ahslen);
460                 return ISCSI_ERR_AHSLEN;
461         }
462
463         /* calculate read padding */
464         tcp_conn->in.padding = tcp_conn->in.datalen & (ISCSI_PAD_LEN-1);
465         if (tcp_conn->in.padding) {
466                 tcp_conn->in.padding = ISCSI_PAD_LEN - tcp_conn->in.padding;
467                 debug_scsi("read padding %d bytes\n", tcp_conn->in.padding);
468         }
469
470         if (conn->hdrdgst_en) {
471                 struct scatterlist sg;
472
473                 sg_init_one(&sg, (u8 *)hdr,
474                             sizeof(struct iscsi_hdr) + ahslen);
475                 crypto_hash_digest(&tcp_conn->rx_hash, &sg, sg.length,
476                                    (u8 *)&cdgst);
477                 rdgst = *(uint32_t*)((char*)hdr + sizeof(struct iscsi_hdr) +
478                                      ahslen);
479                 if (cdgst != rdgst) {
480                         printk(KERN_ERR "iscsi_tcp: hdrdgst error "
481                                "recv 0x%x calc 0x%x\n", rdgst, cdgst);
482                         return ISCSI_ERR_HDR_DGST;
483                 }
484         }
485
486         opcode = hdr->opcode & ISCSI_OPCODE_MASK;
487         /* verify itt (itt encoding: age+cid+itt) */
488         rc = iscsi_verify_itt(conn, hdr, &itt);
489         if (rc == ISCSI_ERR_NO_SCSI_CMD) {
490                 tcp_conn->in.datalen = 0; /* force drop */
491                 return 0;
492         } else if (rc)
493                 return rc;
494
495         debug_tcp("opcode 0x%x offset %d copy %d ahslen %d datalen %d\n",
496                   opcode, tcp_conn->in.offset, tcp_conn->in.copy,
497                   ahslen, tcp_conn->in.datalen);
498
499         switch(opcode) {
500         case ISCSI_OP_SCSI_DATA_IN:
501                 tcp_conn->in.ctask = session->cmds[itt];
502                 rc = iscsi_data_rsp(conn, tcp_conn->in.ctask);
503                 if (rc)
504                         return rc;
505                 /* fall through */
506         case ISCSI_OP_SCSI_CMD_RSP:
507                 tcp_conn->in.ctask = session->cmds[itt];
508                 if (tcp_conn->in.datalen)
509                         goto copy_hdr;
510
511                 spin_lock(&session->lock);
512                 rc = __iscsi_complete_pdu(conn, hdr, NULL, 0);
513                 spin_unlock(&session->lock);
514                 break;
515         case ISCSI_OP_R2T:
516                 tcp_conn->in.ctask = session->cmds[itt];
517                 if (ahslen)
518                         rc = ISCSI_ERR_AHSLEN;
519                 else if (tcp_conn->in.ctask->sc->sc_data_direction ==
520                                                                 DMA_TO_DEVICE)
521                         rc = iscsi_r2t_rsp(conn, tcp_conn->in.ctask);
522                 else
523                         rc = ISCSI_ERR_PROTO;
524                 break;
525         case ISCSI_OP_LOGIN_RSP:
526         case ISCSI_OP_TEXT_RSP:
527         case ISCSI_OP_REJECT:
528         case ISCSI_OP_ASYNC_EVENT:
529                 /*
530                  * It is possible that we could get a PDU with a buffer larger
531                  * than 8K, but there are no targets that currently do this.
532                  * For now we fail until we find a vendor that needs it
533                  */
534                 if (ISCSI_DEF_MAX_RECV_SEG_LEN <
535                     tcp_conn->in.datalen) {
536                         printk(KERN_ERR "iscsi_tcp: received buffer of len %u "
537                               "but conn buffer is only %u (opcode %0x)\n",
538                               tcp_conn->in.datalen,
539                               ISCSI_DEF_MAX_RECV_SEG_LEN, opcode);
540                         rc = ISCSI_ERR_PROTO;
541                         break;
542                 }
543
544                 if (tcp_conn->in.datalen)
545                         goto copy_hdr;
546         /* fall through */
547         case ISCSI_OP_LOGOUT_RSP:
548         case ISCSI_OP_NOOP_IN:
549         case ISCSI_OP_SCSI_TMFUNC_RSP:
550                 rc = iscsi_complete_pdu(conn, hdr, NULL, 0);
551                 break;
552         default:
553                 rc = ISCSI_ERR_BAD_OPCODE;
554                 break;
555         }
556
557         return rc;
558
559 copy_hdr:
560         /*
561          * if we did zero copy for the header but we will need multiple
562          * skbs to complete the command then we have to copy the header
563          * for later use
564          */
565         if (tcp_conn->in.zero_copy_hdr && tcp_conn->in.copy <=
566            (tcp_conn->in.datalen + tcp_conn->in.padding +
567             (conn->datadgst_en ? 4 : 0))) {
568                 debug_tcp("Copying header for later use. in.copy %d in.datalen"
569                           " %d\n", tcp_conn->in.copy, tcp_conn->in.datalen);
570                 memcpy(&tcp_conn->hdr, tcp_conn->in.hdr,
571                        sizeof(struct iscsi_hdr));
572                 tcp_conn->in.hdr = &tcp_conn->hdr;
573                 tcp_conn->in.zero_copy_hdr = 0;
574         }
575         return 0;
576 }
577
578 /**
579  * iscsi_ctask_copy - copy skb bits to the destanation cmd task
580  * @conn: iscsi tcp connection
581  * @ctask: scsi command task
582  * @buf: buffer to copy to
583  * @buf_size: size of buffer
584  * @offset: offset within the buffer
585  *
586  * Notes:
587  *      The function calls skb_copy_bits() and updates per-connection and
588  *      per-cmd byte counters.
589  *
590  *      Read counters (in bytes):
591  *
592  *      conn->in.offset         offset within in progress SKB
593  *      conn->in.copy           left to copy from in progress SKB
594  *                              including padding
595  *      conn->in.copied         copied already from in progress SKB
596  *      conn->data_copied       copied already from in progress buffer
597  *      ctask->sent             total bytes sent up to the MidLayer
598  *      ctask->data_count       left to copy from in progress Data-In
599  *      buf_left                left to copy from in progress buffer
600  **/
601 static inline int
602 iscsi_ctask_copy(struct iscsi_tcp_conn *tcp_conn, struct iscsi_cmd_task *ctask,
603                 void *buf, int buf_size, int offset)
604 {
605         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
606         int buf_left = buf_size - (tcp_conn->data_copied + offset);
607         int size = min(tcp_conn->in.copy, buf_left);
608         int rc;
609
610         size = min(size, ctask->data_count);
611
612         debug_tcp("ctask_copy %d bytes at offset %d copied %d\n",
613                size, tcp_conn->in.offset, tcp_conn->in.copied);
614
615         BUG_ON(size <= 0);
616         BUG_ON(tcp_ctask->sent + size > ctask->total_length);
617
618         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
619                            (char*)buf + (offset + tcp_conn->data_copied), size);
620         /* must fit into skb->len */
621         BUG_ON(rc);
622
623         tcp_conn->in.offset += size;
624         tcp_conn->in.copy -= size;
625         tcp_conn->in.copied += size;
626         tcp_conn->data_copied += size;
627         tcp_ctask->sent += size;
628         ctask->data_count -= size;
629
630         BUG_ON(tcp_conn->in.copy < 0);
631         BUG_ON(ctask->data_count < 0);
632
633         if (buf_size != (tcp_conn->data_copied + offset)) {
634                 if (!ctask->data_count) {
635                         BUG_ON(buf_size - tcp_conn->data_copied < 0);
636                         /* done with this PDU */
637                         return buf_size - tcp_conn->data_copied;
638                 }
639                 return -EAGAIN;
640         }
641
642         /* done with this buffer or with both - PDU and buffer */
643         tcp_conn->data_copied = 0;
644         return 0;
645 }
646
647 /**
648  * iscsi_tcp_copy - copy skb bits to the destanation buffer
649  * @conn: iscsi tcp connection
650  *
651  * Notes:
652  *      The function calls skb_copy_bits() and updates per-connection
653  *      byte counters.
654  **/
655 static inline int
656 iscsi_tcp_copy(struct iscsi_conn *conn, int buf_size)
657 {
658         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
659         int buf_left = buf_size - tcp_conn->data_copied;
660         int size = min(tcp_conn->in.copy, buf_left);
661         int rc;
662
663         debug_tcp("tcp_copy %d bytes at offset %d copied %d\n",
664                size, tcp_conn->in.offset, tcp_conn->data_copied);
665         BUG_ON(size <= 0);
666
667         rc = skb_copy_bits(tcp_conn->in.skb, tcp_conn->in.offset,
668                            (char*)conn->data + tcp_conn->data_copied, size);
669         BUG_ON(rc);
670
671         tcp_conn->in.offset += size;
672         tcp_conn->in.copy -= size;
673         tcp_conn->in.copied += size;
674         tcp_conn->data_copied += size;
675
676         if (buf_size != tcp_conn->data_copied)
677                 return -EAGAIN;
678
679         return 0;
680 }
681
682 static inline void
683 partial_sg_digest_update(struct hash_desc *desc, struct scatterlist *sg,
684                          int offset, int length)
685 {
686         struct scatterlist temp;
687
688         memcpy(&temp, sg, sizeof(struct scatterlist));
689         temp.offset = offset;
690         temp.length = length;
691         crypto_hash_update(desc, &temp, length);
692 }
693
694 static void
695 iscsi_recv_digest_update(struct iscsi_tcp_conn *tcp_conn, char* buf, int len)
696 {
697         struct scatterlist tmp;
698
699         sg_init_one(&tmp, buf, len);
700         crypto_hash_update(&tcp_conn->rx_hash, &tmp, len);
701 }
702
703 static int iscsi_scsi_data_in(struct iscsi_conn *conn)
704 {
705         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
706         struct iscsi_cmd_task *ctask = tcp_conn->in.ctask;
707         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
708         struct scsi_cmnd *sc = ctask->sc;
709         struct scatterlist *sg;
710         int i, offset, rc = 0;
711
712         BUG_ON((void*)ctask != sc->SCp.ptr);
713
714         /*
715          * copying Data-In into the Scsi_Cmnd
716          */
717         if (!sc->use_sg) {
718                 i = ctask->data_count;
719                 rc = iscsi_ctask_copy(tcp_conn, ctask, sc->request_buffer,
720                                       sc->request_bufflen,
721                                       tcp_ctask->data_offset);
722                 if (rc == -EAGAIN)
723                         return rc;
724                 if (conn->datadgst_en)
725                         iscsi_recv_digest_update(tcp_conn, sc->request_buffer,
726                                                  i);
727                 rc = 0;
728                 goto done;
729         }
730
731         offset = tcp_ctask->data_offset;
732         sg = sc->request_buffer;
733
734         if (tcp_ctask->data_offset)
735                 for (i = 0; i < tcp_ctask->sg_count; i++)
736                         offset -= sg[i].length;
737         /* we've passed through partial sg*/
738         if (offset < 0)
739                 offset = 0;
740
741         for (i = tcp_ctask->sg_count; i < sc->use_sg; i++) {
742                 char *dest;
743
744                 dest = kmap_atomic(sg[i].page, KM_SOFTIRQ0);
745                 rc = iscsi_ctask_copy(tcp_conn, ctask, dest + sg[i].offset,
746                                       sg[i].length, offset);
747                 kunmap_atomic(dest, KM_SOFTIRQ0);
748                 if (rc == -EAGAIN)
749                         /* continue with the next SKB/PDU */
750                         return rc;
751                 if (!rc) {
752                         if (conn->datadgst_en) {
753                                 if (!offset)
754                                         crypto_hash_update(
755                                                         &tcp_conn->rx_hash,
756                                                         &sg[i], sg[i].length);
757                                 else
758                                         partial_sg_digest_update(
759                                                         &tcp_conn->rx_hash,
760                                                         &sg[i],
761                                                         sg[i].offset + offset,
762                                                         sg[i].length - offset);
763                         }
764                         offset = 0;
765                         tcp_ctask->sg_count++;
766                 }
767
768                 if (!ctask->data_count) {
769                         if (rc && conn->datadgst_en)
770                                 /*
771                                  * data-in is complete, but buffer not...
772                                  */
773                                 partial_sg_digest_update(&tcp_conn->rx_hash,
774                                                          &sg[i],
775                                                          sg[i].offset,
776                                                          sg[i].length-rc);
777                         rc = 0;
778                         break;
779                 }
780
781                 if (!tcp_conn->in.copy)
782                         return -EAGAIN;
783         }
784         BUG_ON(ctask->data_count);
785
786 done:
787         /* check for non-exceptional status */
788         if (tcp_conn->in.hdr->flags & ISCSI_FLAG_DATA_STATUS) {
789                 debug_scsi("done [sc %lx res %d itt 0x%x flags 0x%x]\n",
790                            (long)sc, sc->result, ctask->itt,
791                            tcp_conn->in.hdr->flags);
792                 spin_lock(&conn->session->lock);
793                 __iscsi_complete_pdu(conn, tcp_conn->in.hdr, NULL, 0);
794                 spin_unlock(&conn->session->lock);
795         }
796
797         return rc;
798 }
799
800 static int
801 iscsi_data_recv(struct iscsi_conn *conn)
802 {
803         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
804         int rc = 0, opcode;
805
806         opcode = tcp_conn->in.hdr->opcode & ISCSI_OPCODE_MASK;
807         switch (opcode) {
808         case ISCSI_OP_SCSI_DATA_IN:
809                 rc = iscsi_scsi_data_in(conn);
810                 break;
811         case ISCSI_OP_SCSI_CMD_RSP:
812         case ISCSI_OP_TEXT_RSP:
813         case ISCSI_OP_LOGIN_RSP:
814         case ISCSI_OP_ASYNC_EVENT:
815         case ISCSI_OP_REJECT:
816                 /*
817                  * Collect data segment to the connection's data
818                  * placeholder
819                  */
820                 if (iscsi_tcp_copy(conn, tcp_conn->in.datalen)) {
821                         rc = -EAGAIN;
822                         goto exit;
823                 }
824
825                 rc = iscsi_complete_pdu(conn, tcp_conn->in.hdr, conn->data,
826                                         tcp_conn->in.datalen);
827                 if (!rc && conn->datadgst_en && opcode != ISCSI_OP_LOGIN_RSP)
828                         iscsi_recv_digest_update(tcp_conn, conn->data,
829                                                 tcp_conn->in.datalen);
830                 break;
831         default:
832                 BUG_ON(1);
833         }
834 exit:
835         return rc;
836 }
837
838 /**
839  * iscsi_tcp_data_recv - TCP receive in sendfile fashion
840  * @rd_desc: read descriptor
841  * @skb: socket buffer
842  * @offset: offset in skb
843  * @len: skb->len - offset
844  **/
845 static int
846 iscsi_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
847                 unsigned int offset, size_t len)
848 {
849         int rc;
850         struct iscsi_conn *conn = rd_desc->arg.data;
851         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
852         int processed;
853         char pad[ISCSI_PAD_LEN];
854         struct scatterlist sg;
855
856         /*
857          * Save current SKB and its offset in the corresponding
858          * connection context.
859          */
860         tcp_conn->in.copy = skb->len - offset;
861         tcp_conn->in.offset = offset;
862         tcp_conn->in.skb = skb;
863         tcp_conn->in.len = tcp_conn->in.copy;
864         BUG_ON(tcp_conn->in.copy <= 0);
865         debug_tcp("in %d bytes\n", tcp_conn->in.copy);
866
867 more:
868         tcp_conn->in.copied = 0;
869         rc = 0;
870
871         if (unlikely(conn->suspend_rx)) {
872                 debug_tcp("conn %d Rx suspended!\n", conn->id);
873                 return 0;
874         }
875
876         if (tcp_conn->in_progress == IN_PROGRESS_WAIT_HEADER ||
877             tcp_conn->in_progress == IN_PROGRESS_HEADER_GATHER) {
878                 rc = iscsi_hdr_extract(tcp_conn);
879                 if (rc) {
880                        if (rc == -EAGAIN)
881                                 goto nomore;
882                        else {
883                                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
884                                 return 0;
885                        }
886                 }
887
888                 /*
889                  * Verify and process incoming PDU header.
890                  */
891                 rc = iscsi_tcp_hdr_recv(conn);
892                 if (!rc && tcp_conn->in.datalen) {
893                         if (conn->datadgst_en)
894                                 crypto_hash_init(&tcp_conn->rx_hash);
895                         tcp_conn->in_progress = IN_PROGRESS_DATA_RECV;
896                 } else if (rc) {
897                         iscsi_conn_failure(conn, rc);
898                         return 0;
899                 }
900         }
901
902         if (tcp_conn->in_progress == IN_PROGRESS_DDIGEST_RECV) {
903                 uint32_t recv_digest;
904
905                 debug_tcp("extra data_recv offset %d copy %d\n",
906                           tcp_conn->in.offset, tcp_conn->in.copy);
907                 rc = iscsi_tcp_copy(conn, sizeof(uint32_t));
908                 if (rc) {
909                         if (rc == -EAGAIN)
910                                 goto again;
911                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
912                         return 0;
913                 }
914
915                 memcpy(&recv_digest, conn->data, sizeof(uint32_t));
916                 if (recv_digest != tcp_conn->in.datadgst) {
917                         debug_tcp("iscsi_tcp: data digest error!"
918                                   "0x%x != 0x%x\n", recv_digest,
919                                   tcp_conn->in.datadgst);
920                         iscsi_conn_failure(conn, ISCSI_ERR_DATA_DGST);
921                         return 0;
922                 } else {
923                         debug_tcp("iscsi_tcp: data digest match!"
924                                   "0x%x == 0x%x\n", recv_digest,
925                                   tcp_conn->in.datadgst);
926                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
927                 }
928         }
929
930         if (tcp_conn->in_progress == IN_PROGRESS_DATA_RECV &&
931            tcp_conn->in.copy) {
932
933                 debug_tcp("data_recv offset %d copy %d\n",
934                        tcp_conn->in.offset, tcp_conn->in.copy);
935
936                 rc = iscsi_data_recv(conn);
937                 if (rc) {
938                         if (rc == -EAGAIN)
939                                 goto again;
940                         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
941                         return 0;
942                 }
943                 tcp_conn->in.copy -= tcp_conn->in.padding;
944                 tcp_conn->in.offset += tcp_conn->in.padding;
945                 if (conn->datadgst_en) {
946                         if (tcp_conn->in.padding) {
947                                 debug_tcp("padding -> %d\n",
948                                           tcp_conn->in.padding);
949                                 memset(pad, 0, tcp_conn->in.padding);
950                                 sg_init_one(&sg, pad, tcp_conn->in.padding);
951                                 crypto_hash_update(&tcp_conn->rx_hash,
952                                                    &sg, sg.length);
953                         }
954                         crypto_hash_final(&tcp_conn->rx_hash,
955                                           (u8 *) &tcp_conn->in.datadgst);
956                         debug_tcp("rx digest 0x%x\n", tcp_conn->in.datadgst);
957                         tcp_conn->in_progress = IN_PROGRESS_DDIGEST_RECV;
958                         tcp_conn->data_copied = 0;
959                 } else
960                         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
961         }
962
963         debug_tcp("f, processed %d from out of %d padding %d\n",
964                tcp_conn->in.offset - offset, (int)len, tcp_conn->in.padding);
965         BUG_ON(tcp_conn->in.offset - offset > len);
966
967         if (tcp_conn->in.offset - offset != len) {
968                 debug_tcp("continue to process %d bytes\n",
969                        (int)len - (tcp_conn->in.offset - offset));
970                 goto more;
971         }
972
973 nomore:
974         processed = tcp_conn->in.offset - offset;
975         BUG_ON(processed == 0);
976         return processed;
977
978 again:
979         processed = tcp_conn->in.offset - offset;
980         debug_tcp("c, processed %d from out of %d rd_desc_cnt %d\n",
981                   processed, (int)len, (int)rd_desc->count);
982         BUG_ON(processed == 0);
983         BUG_ON(processed > len);
984
985         conn->rxdata_octets += processed;
986         return processed;
987 }
988
989 static void
990 iscsi_tcp_data_ready(struct sock *sk, int flag)
991 {
992         struct iscsi_conn *conn = sk->sk_user_data;
993         read_descriptor_t rd_desc;
994
995         read_lock(&sk->sk_callback_lock);
996
997         /*
998          * Use rd_desc to pass 'conn' to iscsi_tcp_data_recv.
999          * We set count to 1 because we want the network layer to
1000          * hand us all the skbs that are available. iscsi_tcp_data_recv
1001          * handled pdus that cross buffers or pdus that still need data.
1002          */
1003         rd_desc.arg.data = conn;
1004         rd_desc.count = 1;
1005         tcp_read_sock(sk, &rd_desc, iscsi_tcp_data_recv);
1006
1007         read_unlock(&sk->sk_callback_lock);
1008 }
1009
1010 static void
1011 iscsi_tcp_state_change(struct sock *sk)
1012 {
1013         struct iscsi_tcp_conn *tcp_conn;
1014         struct iscsi_conn *conn;
1015         struct iscsi_session *session;
1016         void (*old_state_change)(struct sock *);
1017
1018         read_lock(&sk->sk_callback_lock);
1019
1020         conn = (struct iscsi_conn*)sk->sk_user_data;
1021         session = conn->session;
1022
1023         if ((sk->sk_state == TCP_CLOSE_WAIT ||
1024              sk->sk_state == TCP_CLOSE) &&
1025             !atomic_read(&sk->sk_rmem_alloc)) {
1026                 debug_tcp("iscsi_tcp_state_change: TCP_CLOSE|TCP_CLOSE_WAIT\n");
1027                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1028         }
1029
1030         tcp_conn = conn->dd_data;
1031         old_state_change = tcp_conn->old_state_change;
1032
1033         read_unlock(&sk->sk_callback_lock);
1034
1035         old_state_change(sk);
1036 }
1037
1038 /**
1039  * iscsi_write_space - Called when more output buffer space is available
1040  * @sk: socket space is available for
1041  **/
1042 static void
1043 iscsi_write_space(struct sock *sk)
1044 {
1045         struct iscsi_conn *conn = (struct iscsi_conn*)sk->sk_user_data;
1046         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1047
1048         tcp_conn->old_write_space(sk);
1049         debug_tcp("iscsi_write_space: cid %d\n", conn->id);
1050         scsi_queue_work(conn->session->host, &conn->xmitwork);
1051 }
1052
1053 static void
1054 iscsi_conn_set_callbacks(struct iscsi_conn *conn)
1055 {
1056         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1057         struct sock *sk = tcp_conn->sock->sk;
1058
1059         /* assign new callbacks */
1060         write_lock_bh(&sk->sk_callback_lock);
1061         sk->sk_user_data = conn;
1062         tcp_conn->old_data_ready = sk->sk_data_ready;
1063         tcp_conn->old_state_change = sk->sk_state_change;
1064         tcp_conn->old_write_space = sk->sk_write_space;
1065         sk->sk_data_ready = iscsi_tcp_data_ready;
1066         sk->sk_state_change = iscsi_tcp_state_change;
1067         sk->sk_write_space = iscsi_write_space;
1068         write_unlock_bh(&sk->sk_callback_lock);
1069 }
1070
1071 static void
1072 iscsi_conn_restore_callbacks(struct iscsi_tcp_conn *tcp_conn)
1073 {
1074         struct sock *sk = tcp_conn->sock->sk;
1075
1076         /* restore socket callbacks, see also: iscsi_conn_set_callbacks() */
1077         write_lock_bh(&sk->sk_callback_lock);
1078         sk->sk_user_data    = NULL;
1079         sk->sk_data_ready   = tcp_conn->old_data_ready;
1080         sk->sk_state_change = tcp_conn->old_state_change;
1081         sk->sk_write_space  = tcp_conn->old_write_space;
1082         sk->sk_no_check  = 0;
1083         write_unlock_bh(&sk->sk_callback_lock);
1084 }
1085
1086 /**
1087  * iscsi_send - generic send routine
1088  * @sk: kernel's socket
1089  * @buf: buffer to write from
1090  * @size: actual size to write
1091  * @flags: socket's flags
1092  */
1093 static inline int
1094 iscsi_send(struct iscsi_conn *conn, struct iscsi_buf *buf, int size, int flags)
1095 {
1096         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1097         struct socket *sk = tcp_conn->sock;
1098         int offset = buf->sg.offset + buf->sent, res;
1099
1100         /*
1101          * if we got use_sg=0 or are sending something we kmallocd
1102          * then we did not have to do kmap (kmap returns page_address)
1103          *
1104          * if we got use_sg > 0, but had to drop down, we do not
1105          * set clustering so this should only happen for that
1106          * slab case.
1107          */
1108         if (buf->use_sendmsg)
1109                 res = sock_no_sendpage(sk, buf->sg.page, offset, size, flags);
1110         else
1111                 res = tcp_conn->sendpage(sk, buf->sg.page, offset, size, flags);
1112
1113         if (res >= 0) {
1114                 conn->txdata_octets += res;
1115                 buf->sent += res;
1116                 return res;
1117         }
1118
1119         tcp_conn->sendpage_failures_cnt++;
1120         if (res == -EAGAIN)
1121                 res = -ENOBUFS;
1122         else
1123                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1124         return res;
1125 }
1126
1127 /**
1128  * iscsi_sendhdr - send PDU Header via tcp_sendpage()
1129  * @conn: iscsi connection
1130  * @buf: buffer to write from
1131  * @datalen: lenght of data to be sent after the header
1132  *
1133  * Notes:
1134  *      (Tx, Fast Path)
1135  **/
1136 static inline int
1137 iscsi_sendhdr(struct iscsi_conn *conn, struct iscsi_buf *buf, int datalen)
1138 {
1139         int flags = 0; /* MSG_DONTWAIT; */
1140         int res, size;
1141
1142         size = buf->sg.length - buf->sent;
1143         BUG_ON(buf->sent + size > buf->sg.length);
1144         if (buf->sent + size != buf->sg.length || datalen)
1145                 flags |= MSG_MORE;
1146
1147         res = iscsi_send(conn, buf, size, flags);
1148         debug_tcp("sendhdr %d bytes, sent %d res %d\n", size, buf->sent, res);
1149         if (res >= 0) {
1150                 if (size != res)
1151                         return -EAGAIN;
1152                 return 0;
1153         }
1154
1155         return res;
1156 }
1157
1158 /**
1159  * iscsi_sendpage - send one page of iSCSI Data-Out.
1160  * @conn: iscsi connection
1161  * @buf: buffer to write from
1162  * @count: remaining data
1163  * @sent: number of bytes sent
1164  *
1165  * Notes:
1166  *      (Tx, Fast Path)
1167  **/
1168 static inline int
1169 iscsi_sendpage(struct iscsi_conn *conn, struct iscsi_buf *buf,
1170                int *count, int *sent)
1171 {
1172         int flags = 0; /* MSG_DONTWAIT; */
1173         int res, size;
1174
1175         size = buf->sg.length - buf->sent;
1176         BUG_ON(buf->sent + size > buf->sg.length);
1177         if (size > *count)
1178                 size = *count;
1179         if (buf->sent + size != buf->sg.length || *count != size)
1180                 flags |= MSG_MORE;
1181
1182         res = iscsi_send(conn, buf, size, flags);
1183         debug_tcp("sendpage: %d bytes, sent %d left %d sent %d res %d\n",
1184                   size, buf->sent, *count, *sent, res);
1185         if (res >= 0) {
1186                 *count -= res;
1187                 *sent += res;
1188                 if (size != res)
1189                         return -EAGAIN;
1190                 return 0;
1191         }
1192
1193         return res;
1194 }
1195
1196 static inline void
1197 iscsi_data_digest_init(struct iscsi_tcp_conn *tcp_conn,
1198                       struct iscsi_tcp_cmd_task *tcp_ctask)
1199 {
1200         crypto_hash_init(&tcp_conn->tx_hash);
1201         tcp_ctask->digest_count = 4;
1202 }
1203
1204 /**
1205  * iscsi_solicit_data_cont - initialize next Data-Out
1206  * @conn: iscsi connection
1207  * @ctask: scsi command task
1208  * @r2t: R2T info
1209  * @left: bytes left to transfer
1210  *
1211  * Notes:
1212  *      Initialize next Data-Out within this R2T sequence and continue
1213  *      to process next Scatter-Gather element(if any) of this SCSI command.
1214  *
1215  *      Called under connection lock.
1216  **/
1217 static void
1218 iscsi_solicit_data_cont(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1219                         struct iscsi_r2t_info *r2t, int left)
1220 {
1221         struct iscsi_data *hdr;
1222         struct scsi_cmnd *sc = ctask->sc;
1223         int new_offset;
1224
1225         hdr = &r2t->dtask.hdr;
1226         memset(hdr, 0, sizeof(struct iscsi_data));
1227         hdr->ttt = r2t->ttt;
1228         hdr->datasn = cpu_to_be32(r2t->solicit_datasn);
1229         r2t->solicit_datasn++;
1230         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
1231         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1232         hdr->itt = ctask->hdr->itt;
1233         hdr->exp_statsn = r2t->exp_statsn;
1234         new_offset = r2t->data_offset + r2t->sent;
1235         hdr->offset = cpu_to_be32(new_offset);
1236         if (left > conn->max_xmit_dlength) {
1237                 hton24(hdr->dlength, conn->max_xmit_dlength);
1238                 r2t->data_count = conn->max_xmit_dlength;
1239         } else {
1240                 hton24(hdr->dlength, left);
1241                 r2t->data_count = left;
1242                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
1243         }
1244         conn->dataout_pdus_cnt++;
1245
1246         iscsi_buf_init_iov(&r2t->headbuf, (char*)hdr,
1247                            sizeof(struct iscsi_hdr));
1248
1249         if (iscsi_buf_left(&r2t->sendbuf))
1250                 return;
1251
1252         if (sc->use_sg) {
1253                 iscsi_buf_init_sg(&r2t->sendbuf, r2t->sg);
1254                 r2t->sg += 1;
1255         } else {
1256                 iscsi_buf_init_iov(&r2t->sendbuf,
1257                             (char*)sc->request_buffer + new_offset,
1258                             r2t->data_count);
1259                 r2t->sg = NULL;
1260         }
1261 }
1262
1263 static void iscsi_set_padding(struct iscsi_tcp_cmd_task *tcp_ctask,
1264                               unsigned long len)
1265 {
1266         tcp_ctask->pad_count = len & (ISCSI_PAD_LEN - 1);
1267         if (!tcp_ctask->pad_count)
1268                 return;
1269
1270         tcp_ctask->pad_count = ISCSI_PAD_LEN - tcp_ctask->pad_count;
1271         debug_scsi("write padding %d bytes\n", tcp_ctask->pad_count);
1272         tcp_ctask->xmstate |= XMSTATE_W_PAD;
1273 }
1274
1275 /**
1276  * iscsi_tcp_cmd_init - Initialize iSCSI SCSI_READ or SCSI_WRITE commands
1277  * @conn: iscsi connection
1278  * @ctask: scsi command task
1279  * @sc: scsi command
1280  **/
1281 static void
1282 iscsi_tcp_cmd_init(struct iscsi_cmd_task *ctask)
1283 {
1284         struct scsi_cmnd *sc = ctask->sc;
1285         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1286
1287         BUG_ON(__kfifo_len(tcp_ctask->r2tqueue));
1288
1289         tcp_ctask->sent = 0;
1290         tcp_ctask->sg_count = 0;
1291         tcp_ctask->exp_datasn = 0;
1292
1293         if (sc->sc_data_direction == DMA_TO_DEVICE) {
1294                 tcp_ctask->xmstate = XMSTATE_W_HDR;
1295                 BUG_ON(ctask->total_length == 0);
1296
1297                 if (sc->use_sg) {
1298                         struct scatterlist *sg = sc->request_buffer;
1299
1300                         iscsi_buf_init_sg(&tcp_ctask->sendbuf, sg);
1301                         tcp_ctask->sg = sg + 1;
1302                         tcp_ctask->bad_sg = sg + sc->use_sg;
1303                 } else {
1304                         iscsi_buf_init_iov(&tcp_ctask->sendbuf,
1305                                            sc->request_buffer,
1306                                            sc->request_bufflen);
1307                         tcp_ctask->sg = NULL;
1308                         tcp_ctask->bad_sg = NULL;
1309                 }
1310                 debug_scsi("cmd [itt 0x%x total %d imm_data %d "
1311                            "unsol count %d, unsol offset %d]\n",
1312                            ctask->itt, ctask->total_length, ctask->imm_count,
1313                            ctask->unsol_count, ctask->unsol_offset);
1314         } else
1315                 tcp_ctask->xmstate = XMSTATE_R_HDR;
1316
1317         iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)ctask->hdr,
1318                             sizeof(struct iscsi_hdr));
1319 }
1320
1321 /**
1322  * iscsi_tcp_mtask_xmit - xmit management(immediate) task
1323  * @conn: iscsi connection
1324  * @mtask: task management task
1325  *
1326  * Notes:
1327  *      The function can return -EAGAIN in which case caller must
1328  *      call it again later, or recover. '0' return code means successful
1329  *      xmit.
1330  *
1331  *      Management xmit state machine consists of two states:
1332  *              IN_PROGRESS_IMM_HEAD - PDU Header xmit in progress
1333  *              IN_PROGRESS_IMM_DATA - PDU Data xmit in progress
1334  **/
1335 static int
1336 iscsi_tcp_mtask_xmit(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask)
1337 {
1338         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1339         int rc;
1340
1341         debug_scsi("mtask deq [cid %d state %x itt 0x%x]\n",
1342                 conn->id, tcp_mtask->xmstate, mtask->itt);
1343
1344         if (tcp_mtask->xmstate & XMSTATE_IMM_HDR) {
1345                 tcp_mtask->xmstate &= ~XMSTATE_IMM_HDR;
1346                 if (mtask->data_count)
1347                         tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1348                 if (conn->c_stage != ISCSI_CONN_INITIAL_STAGE &&
1349                     conn->stop_stage != STOP_CONN_RECOVER &&
1350                     conn->hdrdgst_en)
1351                         iscsi_hdr_digest(conn, &tcp_mtask->headbuf,
1352                                         (u8*)tcp_mtask->hdrext);
1353                 rc = iscsi_sendhdr(conn, &tcp_mtask->headbuf,
1354                                    mtask->data_count);
1355                 if (rc) {
1356                         tcp_mtask->xmstate |= XMSTATE_IMM_HDR;
1357                         if (mtask->data_count)
1358                                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1359                         return rc;
1360                 }
1361         }
1362
1363         if (tcp_mtask->xmstate & XMSTATE_IMM_DATA) {
1364                 BUG_ON(!mtask->data_count);
1365                 tcp_mtask->xmstate &= ~XMSTATE_IMM_DATA;
1366                 /* FIXME: implement.
1367                  * Virtual buffer could be spreaded across multiple pages...
1368                  */
1369                 do {
1370                         int rc;
1371
1372                         rc = iscsi_sendpage(conn, &tcp_mtask->sendbuf,
1373                                         &mtask->data_count, &tcp_mtask->sent);
1374                         if (rc) {
1375                                 tcp_mtask->xmstate |= XMSTATE_IMM_DATA;
1376                                 return rc;
1377                         }
1378                 } while (mtask->data_count);
1379         }
1380
1381         BUG_ON(tcp_mtask->xmstate != XMSTATE_IDLE);
1382         if (mtask->hdr->itt == RESERVED_ITT) {
1383                 struct iscsi_session *session = conn->session;
1384
1385                 spin_lock_bh(&session->lock);
1386                 list_del(&conn->mtask->running);
1387                 __kfifo_put(session->mgmtpool.queue, (void*)&conn->mtask,
1388                             sizeof(void*));
1389                 spin_unlock_bh(&session->lock);
1390         }
1391         return 0;
1392 }
1393
1394 static inline int
1395 iscsi_send_read_hdr(struct iscsi_conn *conn,
1396                     struct iscsi_tcp_cmd_task *tcp_ctask)
1397 {
1398         int rc;
1399
1400         tcp_ctask->xmstate &= ~XMSTATE_R_HDR;
1401         if (conn->hdrdgst_en)
1402                 iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1403                                  (u8*)tcp_ctask->hdrext);
1404         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, 0);
1405         if (!rc) {
1406                 BUG_ON(tcp_ctask->xmstate != XMSTATE_IDLE);
1407                 return 0; /* wait for Data-In */
1408         }
1409         tcp_ctask->xmstate |= XMSTATE_R_HDR;
1410         return rc;
1411 }
1412
1413 static inline int
1414 iscsi_send_write_hdr(struct iscsi_conn *conn,
1415                      struct iscsi_cmd_task *ctask)
1416 {
1417         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1418         int rc;
1419
1420         tcp_ctask->xmstate &= ~XMSTATE_W_HDR;
1421         if (conn->hdrdgst_en)
1422                 iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1423                                  (u8*)tcp_ctask->hdrext);
1424         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->imm_count);
1425         if (rc) {
1426                 tcp_ctask->xmstate |= XMSTATE_W_HDR;
1427                 return rc;
1428         }
1429
1430         if (ctask->imm_count) {
1431                 tcp_ctask->xmstate |= XMSTATE_IMM_DATA;
1432                 iscsi_set_padding(tcp_ctask, ctask->imm_count);
1433
1434                 if (ctask->conn->datadgst_en) {
1435                         iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1436                         tcp_ctask->immdigest = 0;
1437                 }
1438         }
1439
1440         if (ctask->unsol_count)
1441                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR | XMSTATE_UNS_INIT;
1442         return 0;
1443 }
1444
1445 static int
1446 iscsi_send_padding(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1447 {
1448         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1449         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1450         int sent = 0, rc;
1451
1452         if (tcp_ctask->xmstate & XMSTATE_W_PAD) {
1453                 iscsi_buf_init_iov(&tcp_ctask->sendbuf, (char*)&tcp_ctask->pad,
1454                                    tcp_ctask->pad_count);
1455                 if (conn->datadgst_en)
1456                         crypto_hash_update(&tcp_conn->tx_hash,
1457                                            &tcp_ctask->sendbuf.sg,
1458                                            tcp_ctask->sendbuf.sg.length);
1459         } else if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_PAD))
1460                 return 0;
1461
1462         tcp_ctask->xmstate &= ~XMSTATE_W_PAD;
1463         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_PAD;
1464         debug_scsi("sending %d pad bytes for itt 0x%x\n",
1465                    tcp_ctask->pad_count, ctask->itt);
1466         rc = iscsi_sendpage(conn, &tcp_ctask->sendbuf, &tcp_ctask->pad_count,
1467                            &sent);
1468         if (rc) {
1469                 debug_scsi("padding send failed %d\n", rc);
1470                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_PAD;
1471         }
1472         return rc;
1473 }
1474
1475 static int
1476 iscsi_send_digest(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1477                         struct iscsi_buf *buf, uint32_t *digest)
1478 {
1479         struct iscsi_tcp_cmd_task *tcp_ctask;
1480         struct iscsi_tcp_conn *tcp_conn;
1481         int rc, sent = 0;
1482
1483         if (!conn->datadgst_en)
1484                 return 0;
1485
1486         tcp_ctask = ctask->dd_data;
1487         tcp_conn = conn->dd_data;
1488
1489         if (!(tcp_ctask->xmstate & XMSTATE_W_RESEND_DATA_DIGEST)) {
1490                 crypto_hash_final(&tcp_conn->tx_hash, (u8*)digest);
1491                 iscsi_buf_init_iov(buf, (char*)digest, 4);
1492         }
1493         tcp_ctask->xmstate &= ~XMSTATE_W_RESEND_DATA_DIGEST;
1494
1495         rc = iscsi_sendpage(conn, buf, &tcp_ctask->digest_count, &sent);
1496         if (!rc)
1497                 debug_scsi("sent digest 0x%x for itt 0x%x\n", *digest,
1498                           ctask->itt);
1499         else {
1500                 debug_scsi("sending digest 0x%x failed for itt 0x%x!\n",
1501                           *digest, ctask->itt);
1502                 tcp_ctask->xmstate |= XMSTATE_W_RESEND_DATA_DIGEST;
1503         }
1504         return rc;
1505 }
1506
1507 static int
1508 iscsi_send_data(struct iscsi_cmd_task *ctask, struct iscsi_buf *sendbuf,
1509                 struct scatterlist **sg, int *sent, int *count,
1510                 struct iscsi_buf *digestbuf, uint32_t *digest)
1511 {
1512         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1513         struct iscsi_conn *conn = ctask->conn;
1514         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1515         int rc, buf_sent, offset;
1516
1517         while (*count) {
1518                 buf_sent = 0;
1519                 offset = sendbuf->sent;
1520
1521                 rc = iscsi_sendpage(conn, sendbuf, count, &buf_sent);
1522                 *sent = *sent + buf_sent;
1523                 if (buf_sent && conn->datadgst_en)
1524                         partial_sg_digest_update(&tcp_conn->tx_hash,
1525                                 &sendbuf->sg, sendbuf->sg.offset + offset,
1526                                 buf_sent);
1527                 if (!iscsi_buf_left(sendbuf) && *sg != tcp_ctask->bad_sg) {
1528                         iscsi_buf_init_sg(sendbuf, *sg);
1529                         *sg = *sg + 1;
1530                 }
1531
1532                 if (rc)
1533                         return rc;
1534         }
1535
1536         rc = iscsi_send_padding(conn, ctask);
1537         if (rc)
1538                 return rc;
1539
1540         return iscsi_send_digest(conn, ctask, digestbuf, digest);
1541 }
1542
1543 static int
1544 iscsi_send_unsol_hdr(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1545 {
1546         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1547         struct iscsi_data_task *dtask;
1548         int rc;
1549
1550         tcp_ctask->xmstate |= XMSTATE_UNS_DATA;
1551         if (tcp_ctask->xmstate & XMSTATE_UNS_INIT) {
1552                 dtask = &tcp_ctask->unsol_dtask;
1553
1554                 iscsi_prep_unsolicit_data_pdu(ctask, &dtask->hdr);
1555                 iscsi_buf_init_iov(&tcp_ctask->headbuf, (char*)&dtask->hdr,
1556                                    sizeof(struct iscsi_hdr));
1557                 if (conn->hdrdgst_en)
1558                         iscsi_hdr_digest(conn, &tcp_ctask->headbuf,
1559                                         (u8*)dtask->hdrext);
1560
1561                 tcp_ctask->xmstate &= ~XMSTATE_UNS_INIT;
1562                 iscsi_set_padding(tcp_ctask, ctask->data_count);
1563         }
1564
1565         rc = iscsi_sendhdr(conn, &tcp_ctask->headbuf, ctask->data_count);
1566         if (rc) {
1567                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1568                 tcp_ctask->xmstate |= XMSTATE_UNS_HDR;
1569                 return rc;
1570         }
1571
1572         if (conn->datadgst_en) {
1573                 dtask = &tcp_ctask->unsol_dtask;
1574                 iscsi_data_digest_init(ctask->conn->dd_data, tcp_ctask);
1575                 dtask->digest = 0;
1576         }
1577
1578         debug_scsi("uns dout [itt 0x%x dlen %d sent %d]\n",
1579                    ctask->itt, ctask->unsol_count, tcp_ctask->sent);
1580         return 0;
1581 }
1582
1583 static int
1584 iscsi_send_unsol_pdu(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1585 {
1586         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1587         int rc;
1588
1589         if (tcp_ctask->xmstate & XMSTATE_UNS_HDR) {
1590                 BUG_ON(!ctask->unsol_count);
1591                 tcp_ctask->xmstate &= ~XMSTATE_UNS_HDR;
1592 send_hdr:
1593                 rc = iscsi_send_unsol_hdr(conn, ctask);
1594                 if (rc)
1595                         return rc;
1596         }
1597
1598         if (tcp_ctask->xmstate & XMSTATE_UNS_DATA) {
1599                 struct iscsi_data_task *dtask = &tcp_ctask->unsol_dtask;
1600                 int start = tcp_ctask->sent;
1601
1602                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1603                                      &tcp_ctask->sent, &ctask->data_count,
1604                                      &dtask->digestbuf, &dtask->digest);
1605                 ctask->unsol_count -= tcp_ctask->sent - start;
1606                 if (rc)
1607                         return rc;
1608                 tcp_ctask->xmstate &= ~XMSTATE_UNS_DATA;
1609                 /*
1610                  * Done with the Data-Out. Next, check if we need
1611                  * to send another unsolicited Data-Out.
1612                  */
1613                 if (ctask->unsol_count) {
1614                         debug_scsi("sending more uns\n");
1615                         tcp_ctask->xmstate |= XMSTATE_UNS_INIT;
1616                         goto send_hdr;
1617                 }
1618         }
1619         return 0;
1620 }
1621
1622 static int iscsi_send_sol_pdu(struct iscsi_conn *conn,
1623                               struct iscsi_cmd_task *ctask)
1624 {
1625         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1626         struct iscsi_session *session = conn->session;
1627         struct iscsi_r2t_info *r2t;
1628         struct iscsi_data_task *dtask;
1629         int left, rc;
1630
1631         if (tcp_ctask->xmstate & XMSTATE_SOL_HDR) {
1632                 tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1633                 tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1634                 if (!tcp_ctask->r2t) {
1635                         spin_lock_bh(&session->lock);
1636                         __kfifo_get(tcp_ctask->r2tqueue, (void*)&tcp_ctask->r2t,
1637                                     sizeof(void*));
1638                         spin_unlock_bh(&session->lock);
1639                 }
1640 send_hdr:
1641                 r2t = tcp_ctask->r2t;
1642                 dtask = &r2t->dtask;
1643
1644                 if (conn->hdrdgst_en)
1645                         iscsi_hdr_digest(conn, &r2t->headbuf,
1646                                         (u8*)dtask->hdrext);
1647                 rc = iscsi_sendhdr(conn, &r2t->headbuf, r2t->data_count);
1648                 if (rc) {
1649                         tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1650                         tcp_ctask->xmstate |= XMSTATE_SOL_HDR;
1651                         return rc;
1652                 }
1653
1654                 if (conn->datadgst_en) {
1655                         iscsi_data_digest_init(conn->dd_data, tcp_ctask);
1656                         dtask->digest = 0;
1657                 }
1658
1659                 iscsi_set_padding(tcp_ctask, r2t->data_count);
1660                 debug_scsi("sol dout [dsn %d itt 0x%x dlen %d sent %d]\n",
1661                         r2t->solicit_datasn - 1, ctask->itt, r2t->data_count,
1662                         r2t->sent);
1663         }
1664
1665         if (tcp_ctask->xmstate & XMSTATE_SOL_DATA) {
1666                 r2t = tcp_ctask->r2t;
1667                 dtask = &r2t->dtask;
1668
1669                 rc = iscsi_send_data(ctask, &r2t->sendbuf, &r2t->sg,
1670                                      &r2t->sent, &r2t->data_count,
1671                                      &dtask->digestbuf, &dtask->digest);
1672                 if (rc)
1673                         return rc;
1674                 tcp_ctask->xmstate &= ~XMSTATE_SOL_DATA;
1675
1676                 /*
1677                  * Done with this Data-Out. Next, check if we have
1678                  * to send another Data-Out for this R2T.
1679                  */
1680                 BUG_ON(r2t->data_length - r2t->sent < 0);
1681                 left = r2t->data_length - r2t->sent;
1682                 if (left) {
1683                         iscsi_solicit_data_cont(conn, ctask, r2t, left);
1684                         tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1685                         tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1686                         goto send_hdr;
1687                 }
1688
1689                 /*
1690                  * Done with this R2T. Check if there are more
1691                  * outstanding R2Ts ready to be processed.
1692                  */
1693                 spin_lock_bh(&session->lock);
1694                 tcp_ctask->r2t = NULL;
1695                 __kfifo_put(tcp_ctask->r2tpool.queue, (void*)&r2t,
1696                             sizeof(void*));
1697                 if (__kfifo_get(tcp_ctask->r2tqueue, (void*)&r2t,
1698                                 sizeof(void*))) {
1699                         tcp_ctask->r2t = r2t;
1700                         tcp_ctask->xmstate |= XMSTATE_SOL_DATA;
1701                         tcp_ctask->xmstate &= ~XMSTATE_SOL_HDR;
1702                         spin_unlock_bh(&session->lock);
1703                         goto send_hdr;
1704                 }
1705                 spin_unlock_bh(&session->lock);
1706         }
1707         return 0;
1708 }
1709
1710 static int
1711 iscsi_tcp_ctask_xmit(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask)
1712 {
1713         struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1714         int rc = 0;
1715
1716         debug_scsi("ctask deq [cid %d xmstate %x itt 0x%x]\n",
1717                 conn->id, tcp_ctask->xmstate, ctask->itt);
1718
1719         /*
1720          * serialize with TMF AbortTask
1721          */
1722         if (ctask->mtask)
1723                 return rc;
1724
1725         if (tcp_ctask->xmstate & XMSTATE_R_HDR)
1726                 return iscsi_send_read_hdr(conn, tcp_ctask);
1727
1728         if (tcp_ctask->xmstate & XMSTATE_W_HDR) {
1729                 rc = iscsi_send_write_hdr(conn, ctask);
1730                 if (rc)
1731                         return rc;
1732         }
1733
1734         if (tcp_ctask->xmstate & XMSTATE_IMM_DATA) {
1735                 rc = iscsi_send_data(ctask, &tcp_ctask->sendbuf, &tcp_ctask->sg,
1736                                      &tcp_ctask->sent, &ctask->imm_count,
1737                                      &tcp_ctask->immbuf, &tcp_ctask->immdigest);
1738                 if (rc)
1739                         return rc;
1740                 tcp_ctask->xmstate &= ~XMSTATE_IMM_DATA;
1741         }
1742
1743         rc = iscsi_send_unsol_pdu(conn, ctask);
1744         if (rc)
1745                 return rc;
1746
1747         rc = iscsi_send_sol_pdu(conn, ctask);
1748         if (rc)
1749                 return rc;
1750
1751         return rc;
1752 }
1753
1754 static struct iscsi_cls_conn *
1755 iscsi_tcp_conn_create(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1756 {
1757         struct iscsi_conn *conn;
1758         struct iscsi_cls_conn *cls_conn;
1759         struct iscsi_tcp_conn *tcp_conn;
1760
1761         cls_conn = iscsi_conn_setup(cls_session, conn_idx);
1762         if (!cls_conn)
1763                 return NULL;
1764         conn = cls_conn->dd_data;
1765         /*
1766          * due to strange issues with iser these are not set
1767          * in iscsi_conn_setup
1768          */
1769         conn->max_recv_dlength = ISCSI_DEF_MAX_RECV_SEG_LEN;
1770
1771         tcp_conn = kzalloc(sizeof(*tcp_conn), GFP_KERNEL);
1772         if (!tcp_conn)
1773                 goto tcp_conn_alloc_fail;
1774
1775         conn->dd_data = tcp_conn;
1776         tcp_conn->iscsi_conn = conn;
1777         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1778         /* initial operational parameters */
1779         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1780
1781         tcp_conn->tx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1782                                                   CRYPTO_ALG_ASYNC);
1783         tcp_conn->tx_hash.flags = 0;
1784         if (IS_ERR(tcp_conn->tx_hash.tfm)) {
1785                 printk(KERN_ERR "Could not create connection due to crc32c "
1786                        "loading error %ld. Make sure the crc32c module is "
1787                        "built as a module or into the kernel\n",
1788                         PTR_ERR(tcp_conn->tx_hash.tfm));
1789                 goto free_tcp_conn;
1790         }
1791
1792         tcp_conn->rx_hash.tfm = crypto_alloc_hash("crc32c", 0,
1793                                                   CRYPTO_ALG_ASYNC);
1794         tcp_conn->rx_hash.flags = 0;
1795         if (IS_ERR(tcp_conn->rx_hash.tfm)) {
1796                 printk(KERN_ERR "Could not create connection due to crc32c "
1797                        "loading error %ld. Make sure the crc32c module is "
1798                        "built as a module or into the kernel\n",
1799                         PTR_ERR(tcp_conn->rx_hash.tfm));
1800                 goto free_tx_tfm;
1801         }
1802
1803         return cls_conn;
1804
1805 free_tx_tfm:
1806         crypto_free_hash(tcp_conn->tx_hash.tfm);
1807 free_tcp_conn:
1808         kfree(tcp_conn);
1809 tcp_conn_alloc_fail:
1810         iscsi_conn_teardown(cls_conn);
1811         return NULL;
1812 }
1813
1814 static void
1815 iscsi_tcp_release_conn(struct iscsi_conn *conn)
1816 {
1817         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1818
1819         if (!tcp_conn->sock)
1820                 return;
1821
1822         sock_hold(tcp_conn->sock->sk);
1823         iscsi_conn_restore_callbacks(tcp_conn);
1824         sock_put(tcp_conn->sock->sk);
1825
1826         sock_release(tcp_conn->sock);
1827         tcp_conn->sock = NULL;
1828         conn->recv_lock = NULL;
1829 }
1830
1831 static void
1832 iscsi_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn)
1833 {
1834         struct iscsi_conn *conn = cls_conn->dd_data;
1835         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1836
1837         iscsi_tcp_release_conn(conn);
1838         iscsi_conn_teardown(cls_conn);
1839
1840         if (tcp_conn->tx_hash.tfm)
1841                 crypto_free_hash(tcp_conn->tx_hash.tfm);
1842         if (tcp_conn->rx_hash.tfm)
1843                 crypto_free_hash(tcp_conn->rx_hash.tfm);
1844
1845         kfree(tcp_conn);
1846 }
1847
1848 static void
1849 iscsi_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1850 {
1851         struct iscsi_conn *conn = cls_conn->dd_data;
1852         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1853
1854         iscsi_conn_stop(cls_conn, flag);
1855         iscsi_tcp_release_conn(conn);
1856         tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
1857 }
1858
1859 static int
1860 iscsi_tcp_conn_bind(struct iscsi_cls_session *cls_session,
1861                     struct iscsi_cls_conn *cls_conn, uint64_t transport_eph,
1862                     int is_leading)
1863 {
1864         struct iscsi_conn *conn = cls_conn->dd_data;
1865         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1866         struct sock *sk;
1867         struct socket *sock;
1868         int err;
1869
1870         /* lookup for existing socket */
1871         sock = sockfd_lookup((int)transport_eph, &err);
1872         if (!sock) {
1873                 printk(KERN_ERR "iscsi_tcp: sockfd_lookup failed %d\n", err);
1874                 return -EEXIST;
1875         }
1876
1877         err = iscsi_conn_bind(cls_session, cls_conn, is_leading);
1878         if (err)
1879                 return err;
1880
1881         /* bind iSCSI connection and socket */
1882         tcp_conn->sock = sock;
1883
1884         /* setup Socket parameters */
1885         sk = sock->sk;
1886         sk->sk_reuse = 1;
1887         sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */
1888         sk->sk_allocation = GFP_ATOMIC;
1889
1890         /* FIXME: disable Nagle's algorithm */
1891
1892         /*
1893          * Intercept TCP callbacks for sendfile like receive
1894          * processing.
1895          */
1896         conn->recv_lock = &sk->sk_callback_lock;
1897         iscsi_conn_set_callbacks(conn);
1898         tcp_conn->sendpage = tcp_conn->sock->ops->sendpage;
1899         /*
1900          * set receive state machine into initial state
1901          */
1902         tcp_conn->in_progress = IN_PROGRESS_WAIT_HEADER;
1903
1904         return 0;
1905 }
1906
1907 /* called with host lock */
1908 static void
1909 iscsi_tcp_mgmt_init(struct iscsi_conn *conn, struct iscsi_mgmt_task *mtask,
1910                     char *data, uint32_t data_size)
1911 {
1912         struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
1913
1914         iscsi_buf_init_iov(&tcp_mtask->headbuf, (char*)mtask->hdr,
1915                            sizeof(struct iscsi_hdr));
1916         tcp_mtask->xmstate = XMSTATE_IMM_HDR;
1917         tcp_mtask->sent = 0;
1918
1919         if (mtask->data_count)
1920                 iscsi_buf_init_iov(&tcp_mtask->sendbuf, (char*)mtask->data,
1921                                     mtask->data_count);
1922 }
1923
1924 static int
1925 iscsi_r2tpool_alloc(struct iscsi_session *session)
1926 {
1927         int i;
1928         int cmd_i;
1929
1930         /*
1931          * initialize per-task: R2T pool and xmit queue
1932          */
1933         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1934                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1935                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1936
1937                 /*
1938                  * pre-allocated x4 as much r2ts to handle race when
1939                  * target acks DataOut faster than we data_xmit() queues
1940                  * could replenish r2tqueue.
1941                  */
1942
1943                 /* R2T pool */
1944                 if (iscsi_pool_init(&tcp_ctask->r2tpool, session->max_r2t * 4,
1945                                     (void***)&tcp_ctask->r2ts,
1946                                     sizeof(struct iscsi_r2t_info))) {
1947                         goto r2t_alloc_fail;
1948                 }
1949
1950                 /* R2T xmit queue */
1951                 tcp_ctask->r2tqueue = kfifo_alloc(
1952                       session->max_r2t * 4 * sizeof(void*), GFP_KERNEL, NULL);
1953                 if (tcp_ctask->r2tqueue == ERR_PTR(-ENOMEM)) {
1954                         iscsi_pool_free(&tcp_ctask->r2tpool,
1955                                         (void**)tcp_ctask->r2ts);
1956                         goto r2t_alloc_fail;
1957                 }
1958         }
1959
1960         return 0;
1961
1962 r2t_alloc_fail:
1963         for (i = 0; i < cmd_i; i++) {
1964                 struct iscsi_cmd_task *ctask = session->cmds[i];
1965                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1966
1967                 kfifo_free(tcp_ctask->r2tqueue);
1968                 iscsi_pool_free(&tcp_ctask->r2tpool,
1969                                 (void**)tcp_ctask->r2ts);
1970         }
1971         return -ENOMEM;
1972 }
1973
1974 static void
1975 iscsi_r2tpool_free(struct iscsi_session *session)
1976 {
1977         int i;
1978
1979         for (i = 0; i < session->cmds_max; i++) {
1980                 struct iscsi_cmd_task *ctask = session->cmds[i];
1981                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
1982
1983                 kfifo_free(tcp_ctask->r2tqueue);
1984                 iscsi_pool_free(&tcp_ctask->r2tpool,
1985                                 (void**)tcp_ctask->r2ts);
1986         }
1987 }
1988
1989 static int
1990 iscsi_conn_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param,
1991                      char *buf, int buflen)
1992 {
1993         struct iscsi_conn *conn = cls_conn->dd_data;
1994         struct iscsi_session *session = conn->session;
1995         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
1996         int value;
1997
1998         switch(param) {
1999         case ISCSI_PARAM_HDRDGST_EN:
2000                 iscsi_set_param(cls_conn, param, buf, buflen);
2001                 tcp_conn->hdr_size = sizeof(struct iscsi_hdr);
2002                 if (conn->hdrdgst_en)
2003                         tcp_conn->hdr_size += sizeof(__u32);
2004                 break;
2005         case ISCSI_PARAM_DATADGST_EN:
2006                 iscsi_set_param(cls_conn, param, buf, buflen);
2007                 tcp_conn->sendpage = conn->datadgst_en ?
2008                         sock_no_sendpage : tcp_conn->sock->ops->sendpage;
2009                 break;
2010         case ISCSI_PARAM_MAX_R2T:
2011                 sscanf(buf, "%d", &value);
2012                 if (session->max_r2t == roundup_pow_of_two(value))
2013                         break;
2014                 iscsi_r2tpool_free(session);
2015                 iscsi_set_param(cls_conn, param, buf, buflen);
2016                 if (session->max_r2t & (session->max_r2t - 1))
2017                         session->max_r2t = roundup_pow_of_two(session->max_r2t);
2018                 if (iscsi_r2tpool_alloc(session))
2019                         return -ENOMEM;
2020                 break;
2021         default:
2022                 return iscsi_set_param(cls_conn, param, buf, buflen);
2023         }
2024
2025         return 0;
2026 }
2027
2028 static int
2029 iscsi_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn,
2030                          enum iscsi_param param, char *buf)
2031 {
2032         struct iscsi_conn *conn = cls_conn->dd_data;
2033         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2034         struct inet_sock *inet;
2035         struct ipv6_pinfo *np;
2036         struct sock *sk;
2037         int len;
2038
2039         switch(param) {
2040         case ISCSI_PARAM_CONN_PORT:
2041                 mutex_lock(&conn->xmitmutex);
2042                 if (!tcp_conn->sock) {
2043                         mutex_unlock(&conn->xmitmutex);
2044                         return -EINVAL;
2045                 }
2046
2047                 inet = inet_sk(tcp_conn->sock->sk);
2048                 len = sprintf(buf, "%hu\n", be16_to_cpu(inet->dport));
2049                 mutex_unlock(&conn->xmitmutex);
2050                 break;
2051         case ISCSI_PARAM_CONN_ADDRESS:
2052                 mutex_lock(&conn->xmitmutex);
2053                 if (!tcp_conn->sock) {
2054                         mutex_unlock(&conn->xmitmutex);
2055                         return -EINVAL;
2056                 }
2057
2058                 sk = tcp_conn->sock->sk;
2059                 if (sk->sk_family == PF_INET) {
2060                         inet = inet_sk(sk);
2061                         len = sprintf(buf, NIPQUAD_FMT "\n",
2062                                       NIPQUAD(inet->daddr));
2063                 } else {
2064                         np = inet6_sk(sk);
2065                         len = sprintf(buf, NIP6_FMT "\n", NIP6(np->daddr));
2066                 }
2067                 mutex_unlock(&conn->xmitmutex);
2068                 break;
2069         default:
2070                 return iscsi_conn_get_param(cls_conn, param, buf);
2071         }
2072
2073         return len;
2074 }
2075
2076 static void
2077 iscsi_conn_get_stats(struct iscsi_cls_conn *cls_conn, struct iscsi_stats *stats)
2078 {
2079         struct iscsi_conn *conn = cls_conn->dd_data;
2080         struct iscsi_tcp_conn *tcp_conn = conn->dd_data;
2081
2082         stats->txdata_octets = conn->txdata_octets;
2083         stats->rxdata_octets = conn->rxdata_octets;
2084         stats->scsicmd_pdus = conn->scsicmd_pdus_cnt;
2085         stats->dataout_pdus = conn->dataout_pdus_cnt;
2086         stats->scsirsp_pdus = conn->scsirsp_pdus_cnt;
2087         stats->datain_pdus = conn->datain_pdus_cnt;
2088         stats->r2t_pdus = conn->r2t_pdus_cnt;
2089         stats->tmfcmd_pdus = conn->tmfcmd_pdus_cnt;
2090         stats->tmfrsp_pdus = conn->tmfrsp_pdus_cnt;
2091         stats->custom_length = 3;
2092         strcpy(stats->custom[0].desc, "tx_sendpage_failures");
2093         stats->custom[0].value = tcp_conn->sendpage_failures_cnt;
2094         strcpy(stats->custom[1].desc, "rx_discontiguous_hdr");
2095         stats->custom[1].value = tcp_conn->discontiguous_hdr_cnt;
2096         strcpy(stats->custom[2].desc, "eh_abort_cnt");
2097         stats->custom[2].value = conn->eh_abort_cnt;
2098 }
2099
2100 static struct iscsi_cls_session *
2101 iscsi_tcp_session_create(struct iscsi_transport *iscsit,
2102                          struct scsi_transport_template *scsit,
2103                          uint32_t initial_cmdsn, uint32_t *hostno)
2104 {
2105         struct iscsi_cls_session *cls_session;
2106         struct iscsi_session *session;
2107         uint32_t hn;
2108         int cmd_i;
2109
2110         cls_session = iscsi_session_setup(iscsit, scsit,
2111                                          sizeof(struct iscsi_tcp_cmd_task),
2112                                          sizeof(struct iscsi_tcp_mgmt_task),
2113                                          initial_cmdsn, &hn);
2114         if (!cls_session)
2115                 return NULL;
2116         *hostno = hn;
2117
2118         session = class_to_transport_session(cls_session);
2119         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2120                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
2121                 struct iscsi_tcp_cmd_task *tcp_ctask = ctask->dd_data;
2122
2123                 ctask->hdr = &tcp_ctask->hdr;
2124         }
2125
2126         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
2127                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
2128                 struct iscsi_tcp_mgmt_task *tcp_mtask = mtask->dd_data;
2129
2130                 mtask->hdr = &tcp_mtask->hdr;
2131         }
2132
2133         if (iscsi_r2tpool_alloc(class_to_transport_session(cls_session)))
2134                 goto r2tpool_alloc_fail;
2135
2136         return cls_session;
2137
2138 r2tpool_alloc_fail:
2139         iscsi_session_teardown(cls_session);
2140         return NULL;
2141 }
2142
2143 static void iscsi_tcp_session_destroy(struct iscsi_cls_session *cls_session)
2144 {
2145         iscsi_r2tpool_free(class_to_transport_session(cls_session));
2146         iscsi_session_teardown(cls_session);
2147 }
2148
2149 static struct scsi_host_template iscsi_sht = {
2150         .name                   = "iSCSI Initiator over TCP/IP",
2151         .queuecommand           = iscsi_queuecommand,
2152         .change_queue_depth     = iscsi_change_queue_depth,
2153         .can_queue              = ISCSI_XMIT_CMDS_MAX - 1,
2154         .sg_tablesize           = ISCSI_SG_TABLESIZE,
2155         .max_sectors            = 0xFFFF,
2156         .cmd_per_lun            = ISCSI_DEF_CMD_PER_LUN,
2157         .eh_abort_handler       = iscsi_eh_abort,
2158         .eh_host_reset_handler  = iscsi_eh_host_reset,
2159         .use_clustering         = DISABLE_CLUSTERING,
2160         .proc_name              = "iscsi_tcp",
2161         .this_id                = -1,
2162 };
2163
2164 static struct iscsi_transport iscsi_tcp_transport = {
2165         .owner                  = THIS_MODULE,
2166         .name                   = "tcp",
2167         .caps                   = CAP_RECOVERY_L0 | CAP_MULTI_R2T | CAP_HDRDGST
2168                                   | CAP_DATADGST,
2169         .param_mask             = ISCSI_MAX_RECV_DLENGTH |
2170                                   ISCSI_MAX_XMIT_DLENGTH |
2171                                   ISCSI_HDRDGST_EN |
2172                                   ISCSI_DATADGST_EN |
2173                                   ISCSI_INITIAL_R2T_EN |
2174                                   ISCSI_MAX_R2T |
2175                                   ISCSI_IMM_DATA_EN |
2176                                   ISCSI_FIRST_BURST |
2177                                   ISCSI_MAX_BURST |
2178                                   ISCSI_PDU_INORDER_EN |
2179                                   ISCSI_DATASEQ_INORDER_EN |
2180                                   ISCSI_ERL |
2181                                   ISCSI_CONN_PORT |
2182                                   ISCSI_CONN_ADDRESS |
2183                                   ISCSI_EXP_STATSN |
2184                                   ISCSI_PERSISTENT_PORT |
2185                                   ISCSI_PERSISTENT_ADDRESS |
2186                                   ISCSI_TARGET_NAME |
2187                                   ISCSI_TPGT,
2188         .host_param_mask        = ISCSI_HOST_HWADDRESS |
2189                                   ISCSI_HOST_INITIATOR_NAME,
2190         .host_template          = &iscsi_sht,
2191         .conndata_size          = sizeof(struct iscsi_conn),
2192         .max_conn               = 1,
2193         .max_cmd_len            = ISCSI_TCP_MAX_CMD_LEN,
2194         /* session management */
2195         .create_session         = iscsi_tcp_session_create,
2196         .destroy_session        = iscsi_tcp_session_destroy,
2197         /* connection management */
2198         .create_conn            = iscsi_tcp_conn_create,
2199         .bind_conn              = iscsi_tcp_conn_bind,
2200         .destroy_conn           = iscsi_tcp_conn_destroy,
2201         .set_param              = iscsi_conn_set_param,
2202         .get_conn_param         = iscsi_tcp_conn_get_param,
2203         .get_session_param      = iscsi_session_get_param,
2204         .start_conn             = iscsi_conn_start,
2205         .stop_conn              = iscsi_tcp_conn_stop,
2206         /* iscsi host params */
2207         .get_host_param         = iscsi_host_get_param,
2208         .set_host_param         = iscsi_host_set_param,
2209         /* IO */
2210         .send_pdu               = iscsi_conn_send_pdu,
2211         .get_stats              = iscsi_conn_get_stats,
2212         .init_cmd_task          = iscsi_tcp_cmd_init,
2213         .init_mgmt_task         = iscsi_tcp_mgmt_init,
2214         .xmit_cmd_task          = iscsi_tcp_ctask_xmit,
2215         .xmit_mgmt_task         = iscsi_tcp_mtask_xmit,
2216         .cleanup_cmd_task       = iscsi_tcp_cleanup_ctask,
2217         /* recovery */
2218         .session_recovery_timedout = iscsi_session_recovery_timedout,
2219 };
2220
2221 static int __init
2222 iscsi_tcp_init(void)
2223 {
2224         if (iscsi_max_lun < 1) {
2225                 printk(KERN_ERR "iscsi_tcp: Invalid max_lun value of %u\n",
2226                        iscsi_max_lun);
2227                 return -EINVAL;
2228         }
2229         iscsi_tcp_transport.max_lun = iscsi_max_lun;
2230
2231         if (!iscsi_register_transport(&iscsi_tcp_transport))
2232                 return -ENODEV;
2233
2234         return 0;
2235 }
2236
2237 static void __exit
2238 iscsi_tcp_exit(void)
2239 {
2240         iscsi_unregister_transport(&iscsi_tcp_transport);
2241 }
2242
2243 module_init(iscsi_tcp_init);
2244 module_exit(iscsi_tcp_exit);