21125dfb2d4e5c0e2d09e1d883512a71f11dbc21
[openafs.git] / src / vol / salvsync-server.c
1 /*
2  * Copyright 2006-2008, Sine Nomine Associates and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * salvsync-server.c
12  *
13  * OpenAFS demand attach fileserver
14  * Salvage server synchronization with fileserver.
15  */
16
17 /* This controls the size of an fd_set; it must be defined early before
18  * the system headers define that type and the macros that operate on it.
19  * Its value should be as large as the maximum file descriptor limit we
20  * are likely to run into on any platform.  Right now, that is 65536
21  * which is the default hard fd limit on Solaris 9 */
22 #ifndef _WIN32
23 #define FD_SETSIZE 65536
24 #endif
25
26 #include <afsconfig.h>
27 #include <afs/param.h>
28
29 RCSID
30     ("$Header$");
31
32 #include <sys/types.h>
33 #include <stdio.h>
34 #ifdef AFS_NT40_ENV
35 #include <winsock2.h>
36 #include <time.h>
37 #else
38 #include <sys/param.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netdb.h>
42 #include <sys/time.h>
43 #endif
44 #include <errno.h>
45 #include <assert.h>
46 #include <signal.h>
47 #include <string.h>
48
49
50 #include <rx/xdr.h>
51 #include <afs/afsint.h>
52 #include "nfs.h"
53 #include <afs/errors.h>
54 #include "salvsync.h"
55 #include "lwp.h"
56 #include "lock.h"
57 #include <afs/afssyscalls.h>
58 #include "ihandle.h"
59 #include "vnode.h"
60 #include "volume.h"
61 #include "partition.h"
62 #include <rx/rx_queue.h>
63 #include <afs/procmgmt.h>
64
65 #if !defined(offsetof)
66 #include <stddef.h>
67 #endif
68
69 #ifdef USE_UNIX_SOCKETS
70 #include <afs/afsutil.h>
71 #include <sys/un.h>
72 #endif
73
74
75 /*@printflike@*/ extern void Log(const char *format, ...);
76
77 #define MAXHANDLERS     4       /* Up to 4 clients; must be at least 2, so that
78                                  * move = dump+restore can run on single server */
79
80 /* Forward declarations */
81 static void * SALVSYNC_syncThread(void *);
82 static void SALVSYNC_newconnection(int fd);
83 static void SALVSYNC_com(int fd);
84 static void SALVSYNC_Drop(int fd);
85 static void AcceptOn(void);
86 static void AcceptOff(void);
87 static void InitHandler(void);
88 static void CallHandler(fd_set * fdsetp);
89 static int AddHandler(int afd, void (*aproc) (int));
90 static int FindHandler(register int afd);
91 static int FindHandler_r(register int afd);
92 static int RemoveHandler(register int afd);
93 static void GetHandler(fd_set * fdsetp, int *maxfdp);
94
95
96 /*
97  * This lock controls access to the handler array.
98  */
99 struct Lock SALVSYNC_handler_lock;
100
101
102 #ifdef AFS_DEMAND_ATTACH_FS
103 /*
104  * SALVSYNC is a feature specific to the demand attach fileserver
105  */
106
107 static int AllocNode(struct SalvageQueueNode ** node);
108
109 static int AddToSalvageQueue(struct SalvageQueueNode * node);
110 static void DeleteFromSalvageQueue(struct SalvageQueueNode * node);
111 static void AddToPendingQueue(struct SalvageQueueNode * node);
112 static void DeleteFromPendingQueue(struct SalvageQueueNode * node);
113 static struct SalvageQueueNode * LookupPendingCommand(SALVSYNC_command_hdr * qry);
114 static struct SalvageQueueNode * LookupPendingCommandByPid(int pid);
115 static void UpdateCommandPrio(struct SalvageQueueNode * node);
116 static void HandlePrio(struct SalvageQueueNode * clone, 
117                        struct SalvageQueueNode * parent,
118                        afs_uint32 new_prio);
119
120 static int LinkNode(struct SalvageQueueNode * parent,
121                     struct SalvageQueueNode * clone);
122
123 static struct SalvageQueueNode * LookupNode(VolumeId vid, char * partName, 
124                                             struct SalvageQueueNode ** parent);
125 static struct SalvageQueueNode * LookupNodeByCommand(SALVSYNC_command_hdr * qry,
126                                                      struct SalvageQueueNode ** parent);
127 static void AddNodeToHash(struct SalvageQueueNode * node);
128 static void DeleteNodeFromHash(struct SalvageQueueNode * node);
129
130 static afs_int32 SALVSYNC_com_Salvage(SALVSYNC_command * com, SALVSYNC_response * res);
131 static afs_int32 SALVSYNC_com_Cancel(SALVSYNC_command * com, SALVSYNC_response * res);
132 static afs_int32 SALVSYNC_com_Query(SALVSYNC_command * com, SALVSYNC_response * res);
133 static afs_int32 SALVSYNC_com_CancelAll(SALVSYNC_command * com, SALVSYNC_response * res);
134 static afs_int32 SALVSYNC_com_Link(SALVSYNC_command * com, SALVSYNC_response * res);
135
136
137 extern int LogLevel;
138 extern int VInit;
139 extern pthread_mutex_t vol_salvsync_mutex;
140
141 /**
142  * salvsync server socket handle.
143  */
144 static SYNC_server_state_t salvsync_server_state = 
145     { -1,                       /* file descriptor */
146       SALVSYNC_ENDPOINT_DECL,   /* server endpoint */
147       SALVSYNC_PROTO_VERSION,   /* protocol version */
148       5,                        /* bind() retry limit */
149       100,                      /* listen() queue depth */
150       "SALVSYNC",               /* protocol name string */
151     };
152
153
154 /**
155  * queue of all volumes waiting to be salvaged.
156  */
157 struct SalvageQueue {
158     volatile int total_len;
159     volatile afs_int32 last_insert;    /**< id of last partition to have a salvage node inserted */
160     volatile int len[VOLMAXPARTS+1];
161     volatile struct rx_queue part[VOLMAXPARTS+1]; /**< per-partition queues of pending salvages */
162     pthread_cond_t cv;
163 };
164 static struct SalvageQueue salvageQueue;  /* volumes waiting to be salvaged */
165
166 /**
167  * queue of all volumes currently being salvaged.
168  */
169 struct QueueHead {
170     volatile struct rx_queue q;  /**< queue of salvages in progress */
171     volatile int len;            /**< length of in-progress queue */
172     pthread_cond_t queue_change_cv;
173 };
174 static struct QueueHead pendingQueue;  /* volumes being salvaged */
175
176 /* XXX
177  * whether a partition has a salvage in progress
178  *
179  * the salvager code only permits one salvage per partition at a time
180  *
181  * the following hack tries to keep salvaged parallelism high by
182  * only permitting one salvage dispatch per partition at a time
183  *
184  * unfortunately, the parallel salvager currently
185  * has a rather braindead routine that won't permit
186  * multiple salvages on the same "device".  this
187  * function happens to break pretty badly on lvm, raid luns, etc.
188  *
189  * this hack isn't good enough to stop the device limiting code from
190  * crippling performance.  someday that code needs to be rewritten
191  */
192 static int partition_salvaging[VOLMAXPARTS+1];
193
194 #define VSHASH_SIZE 64
195 #define VSHASH_MASK (VSHASH_SIZE-1)
196 #define VSHASH(vid) ((vid)&VSHASH_MASK)
197
198 static struct QueueHead  SalvageHashTable[VSHASH_SIZE];
199
200 static struct SalvageQueueNode *
201 LookupNode(afs_uint32 vid, char * partName,
202            struct SalvageQueueNode ** parent)
203 {
204     struct rx_queue *qp, *nqp;
205     struct SalvageQueueNode *vsp;
206     int idx = VSHASH(vid);
207
208     for (queue_Scan(&SalvageHashTable[idx], qp, nqp, rx_queue)) {
209         vsp = (struct SalvageQueueNode *)((char *)qp - offsetof(struct SalvageQueueNode, hash_chain));
210         if ((vsp->command.sop.volume == vid) &&
211             !strncmp(vsp->command.sop.partName, partName, sizeof(vsp->command.sop.partName))) {
212             break;
213         }
214     }
215
216     if (queue_IsEnd(&SalvageHashTable[idx], qp)) {
217         vsp = NULL;
218     }
219
220     if (parent) {
221         if (vsp) {
222             *parent = (vsp->type == SALVSYNC_VOLGROUP_CLONE) ?
223                 vsp->volgroup.parent : vsp;
224         } else {
225             *parent = NULL;
226         }
227     }
228
229     return vsp;
230 }
231
232 static struct SalvageQueueNode *
233 LookupNodeByCommand(SALVSYNC_command_hdr * qry,
234                     struct SalvageQueueNode ** parent)
235 {
236     return LookupNode(qry->volume, qry->partName, parent);
237 }
238
239 static void
240 AddNodeToHash(struct SalvageQueueNode * node)
241 {
242     int idx = VSHASH(node->command.sop.volume);
243
244     if (queue_IsOnQueue(&node->hash_chain)) {
245         return;
246     }
247
248     queue_Append(&SalvageHashTable[idx], &node->hash_chain);
249     SalvageHashTable[idx].len++;
250 }
251
252 static void
253 DeleteNodeFromHash(struct SalvageQueueNode * node)
254 {
255     int idx = VSHASH(node->command.sop.volume);
256
257     if (queue_IsNotOnQueue(&node->hash_chain)) {
258         return;
259     }
260
261     queue_Remove(&node->hash_chain);
262     SalvageHashTable[idx].len--;
263 }
264
265 void
266 SALVSYNC_salvInit(void)
267 {
268     int i;
269     pthread_t tid;
270     pthread_attr_t tattr;
271
272     /* initialize the queues */
273     Lock_Init(&SALVSYNC_handler_lock);
274     assert(pthread_cond_init(&salvageQueue.cv, NULL) == 0);
275     for (i = 0; i <= VOLMAXPARTS; i++) {
276         queue_Init(&salvageQueue.part[i]);
277         salvageQueue.len[i] = 0;
278     }
279     assert(pthread_cond_init(&pendingQueue.queue_change_cv, NULL) == 0);
280     queue_Init(&pendingQueue);
281     salvageQueue.total_len = pendingQueue.len = 0;
282     salvageQueue.last_insert = -1;
283     memset(partition_salvaging, 0, sizeof(partition_salvaging));
284
285     for (i = 0; i < VSHASH_SIZE; i++) {
286         assert(pthread_cond_init(&SalvageHashTable[i].queue_change_cv, NULL) == 0);
287         SalvageHashTable[i].len = 0;
288         queue_Init(&SalvageHashTable[i]);
289     }
290
291     /* start the salvsync thread */
292     assert(pthread_attr_init(&tattr) == 0);
293     assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
294     assert(pthread_create(&tid, &tattr, SALVSYNC_syncThread, NULL) == 0);
295 }
296
297
298 static fd_set SALVSYNC_readfds;
299
300 static void *
301 SALVSYNC_syncThread(void * args)
302 {
303     int on = 1;
304     int code;
305     int numTries;
306     int tid;
307     SYNC_server_state_t * state = &salvsync_server_state;
308
309     SYNC_getAddr(&state->endpoint, &state->addr);
310     SYNC_cleanupSock(state);
311
312 #ifndef AFS_NT40_ENV
313     (void)signal(SIGPIPE, SIG_IGN);
314 #endif
315
316     state->fd = SYNC_getSock(&state->endpoint);
317     code = SYNC_bindSock(state);
318     assert(!code);
319
320     InitHandler();
321     AcceptOn();
322
323     for (;;) {
324         int maxfd;
325         GetHandler(&SALVSYNC_readfds, &maxfd);
326         /* Note: check for >= 1 below is essential since IOMGR_select
327          * doesn't have exactly same semantics as select.
328          */
329         if (select(maxfd + 1, &SALVSYNC_readfds, NULL, NULL, NULL) >= 1)
330             CallHandler(&SALVSYNC_readfds);
331     }
332
333     return NULL;
334 }
335
336 static void
337 SALVSYNC_newconnection(int afd)
338 {
339 #ifdef USE_UNIX_SOCKETS
340     struct sockaddr_un other;
341 #else  /* USE_UNIX_SOCKETS */
342     struct sockaddr_in other;
343 #endif
344     int junk, fd;
345     junk = sizeof(other);
346     fd = accept(afd, (struct sockaddr *)&other, &junk);
347     if (fd == -1) {
348         Log("SALVSYNC_newconnection:  accept failed, errno==%d\n", errno);
349         assert(1 == 2);
350     } else if (!AddHandler(fd, SALVSYNC_com)) {
351         AcceptOff();
352         assert(AddHandler(fd, SALVSYNC_com));
353     }
354 }
355
356 /* this function processes commands from an salvsync file descriptor (fd) */
357 static afs_int32 SALV_cnt = 0;
358 static void
359 SALVSYNC_com(int fd)
360 {
361     SYNC_command com;
362     SYNC_response res;
363     SALVSYNC_response_hdr sres_hdr;
364     SALVSYNC_command scom;
365     SALVSYNC_response sres;
366     SYNC_PROTO_BUF_DECL(buf);
367     
368     com.payload.buf = (void *)buf;
369     com.payload.len = SYNC_PROTO_MAX_LEN;
370     res.payload.buf = (void *) &sres_hdr;
371     res.payload.len = sizeof(sres_hdr);
372     res.hdr.response_len = sizeof(res.hdr) + sizeof(sres_hdr);
373     res.hdr.proto_version = SALVSYNC_PROTO_VERSION;
374
375     scom.hdr = &com.hdr;
376     scom.sop = (SALVSYNC_command_hdr *) buf;
377     scom.com = &com;
378     sres.hdr = &res.hdr;
379     sres.sop = &sres_hdr;
380     sres.res = &res;
381
382     SALV_cnt++;
383     if (SYNC_getCom(fd, &com)) {
384         Log("SALVSYNC_com:  read failed; dropping connection (cnt=%d)\n", SALV_cnt);
385         SALVSYNC_Drop(fd);
386         return;
387     }
388
389     if (com.recv_len < sizeof(com.hdr)) {
390         Log("SALVSYNC_com:  invalid protocol message length (%u)\n", com.recv_len);
391         res.hdr.response = SYNC_COM_ERROR;
392         res.hdr.reason = SYNC_REASON_MALFORMED_PACKET;
393         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
394         goto respond;
395     }
396
397     if (com.hdr.proto_version != SALVSYNC_PROTO_VERSION) {
398         Log("SALVSYNC_com:  invalid protocol version (%u)\n", com.hdr.proto_version);
399         res.hdr.response = SYNC_COM_ERROR;
400         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
401         goto respond;
402     }
403
404     if (com.hdr.command == SYNC_COM_CHANNEL_CLOSE) {
405         res.hdr.response = SYNC_OK;
406         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
407         goto respond;
408     }
409
410     if (com.recv_len != (sizeof(com.hdr) + sizeof(SALVSYNC_command_hdr))) {
411         Log("SALVSYNC_com:  invalid protocol message length (%u)\n", com.recv_len);
412         res.hdr.response = SYNC_COM_ERROR;
413         res.hdr.reason = SYNC_REASON_MALFORMED_PACKET;
414         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
415         goto respond;
416     }
417
418     VOL_LOCK;
419     switch (com.hdr.command) {
420     case SALVSYNC_NOP:
421         break;
422     case SALVSYNC_SALVAGE:
423     case SALVSYNC_RAISEPRIO:
424         res.hdr.response = SALVSYNC_com_Salvage(&scom, &sres);
425         break;
426     case SALVSYNC_CANCEL:
427         /* cancel a salvage */
428         res.hdr.response = SALVSYNC_com_Cancel(&scom, &sres);
429         break;
430     case SALVSYNC_CANCELALL:
431         /* cancel all queued salvages */
432         res.hdr.response = SALVSYNC_com_CancelAll(&scom, &sres);
433         break;
434     case SALVSYNC_QUERY:
435         /* query whether a volume is done salvaging */
436         res.hdr.response = SALVSYNC_com_Query(&scom, &sres);
437         break;
438     case SALVSYNC_OP_LINK:
439         /* link a clone to its parent in the scheduler */
440         res.hdr.response = SALVSYNC_com_Link(&scom, &sres);
441         break;
442     default:
443         res.hdr.response = SYNC_BAD_COMMAND;
444         break;
445     }
446
447     sres_hdr.sq_len = salvageQueue.total_len;
448     sres_hdr.pq_len = pendingQueue.len;
449     VOL_UNLOCK;
450
451  respond:
452     SYNC_putRes(fd, &res);
453     if (res.hdr.flags & SYNC_FLAG_CHANNEL_SHUTDOWN) {
454         SALVSYNC_Drop(fd);
455     }
456 }
457
458 /**
459  * request that a volume be salvaged.
460  *
461  * @param[in]  com  inbound command object
462  * @param[out] res  outbound response object
463  *
464  * @return operation status
465  *    @retval SYNC_OK success
466  *    @retval SYNC_DENIED failed to enqueue request
467  *    @retval SYNC_FAILED malformed command packet
468  *
469  * @note this is a SALVSYNC protocol rpc handler
470  *
471  * @internal
472  *
473  * @post the volume is enqueued in the to-be-salvaged queue.  
474  *       if the volume was already in the salvage queue, its 
475  *       priority (and thus its location in the queue) are 
476  *       updated.
477  */
478 static afs_int32
479 SALVSYNC_com_Salvage(SALVSYNC_command * com, SALVSYNC_response * res)
480 {
481     afs_int32 code = SYNC_OK;
482     struct SalvageQueueNode * node, * clone;
483     int hash = 0;
484
485     if (SYNC_verifyProtocolString(com->sop->partName, sizeof(com->sop->partName))) {
486         code = SYNC_FAILED;
487         res->hdr->reason = SYNC_REASON_MALFORMED_PACKET;
488         goto done;
489     }
490
491     clone = LookupNodeByCommand(com->sop, &node);
492
493     if (node == NULL) {
494         if (AllocNode(&node)) {
495             code = SYNC_DENIED;
496             res->hdr->reason = SYNC_REASON_NOMEM;
497             goto done;
498         }
499         clone = node;
500         hash = 1;
501     }
502
503     HandlePrio(clone, node, com->sop->prio);
504
505     switch (node->state) {
506     case SALVSYNC_STATE_QUEUED:
507         UpdateCommandPrio(node);
508         break;
509
510     case SALVSYNC_STATE_ERROR:
511     case SALVSYNC_STATE_DONE:
512     case SALVSYNC_STATE_UNKNOWN:
513         memcpy(&clone->command.com, com->hdr, sizeof(SYNC_command_hdr));
514         memcpy(&clone->command.sop, com->sop, sizeof(SALVSYNC_command_hdr));
515
516         /* 
517          * make sure volgroup parent partition path is kept coherent
518          *
519          * If we ever want to support non-COW clones on a machine holding
520          * the RW site, please note that this code does not work under the
521          * conditions where someone zaps a COW clone on partition X, and
522          * subsequently creates a full clone on partition Y -- we'd need
523          * an inverse to SALVSYNC_com_Link.
524          *  -- tkeiser 11/28/2007
525          */
526         strcpy(node->command.sop.partName, com->sop->partName);
527
528         if (AddToSalvageQueue(node)) {
529             code = SYNC_DENIED;
530         }
531         break;
532
533     default:
534         break;
535     }
536
537     if (hash) {
538         AddNodeToHash(node);
539     }
540
541     res->hdr->flags |= SALVSYNC_FLAG_VOL_STATS_VALID;
542     res->sop->state = node->state;
543     res->sop->prio = node->command.sop.prio;
544
545  done:
546     return code;
547 }
548
549 /**
550  * cancel a pending salvage request.
551  *
552  * @param[in]  com  inbound command object
553  * @param[out] res  outbound response object
554  *
555  * @return operation status
556  *    @retval SYNC_OK success
557  *    @retval SYNC_FAILED malformed command packet
558  *
559  * @note this is a SALVSYNC protocol rpc handler
560  *
561  * @internal
562  */
563 static afs_int32
564 SALVSYNC_com_Cancel(SALVSYNC_command * com, SALVSYNC_response * res)
565 {
566     afs_int32 code = SYNC_OK;
567     struct SalvageQueueNode * node;
568
569     if (SYNC_verifyProtocolString(com->sop->partName, sizeof(com->sop->partName))) {
570         code = SYNC_FAILED;
571         res->hdr->reason = SYNC_REASON_MALFORMED_PACKET;
572         goto done;
573     }
574
575     node = LookupNodeByCommand(com->sop, NULL);
576
577     if (node == NULL) {
578         res->sop->state = SALVSYNC_STATE_UNKNOWN;
579         res->sop->prio = 0;
580     } else {
581         res->hdr->flags |= SALVSYNC_FLAG_VOL_STATS_VALID;
582         res->sop->prio = node->command.sop.prio;
583         res->sop->state = node->state;
584         if ((node->type == SALVSYNC_VOLGROUP_PARENT) && 
585             (node->state == SALVSYNC_STATE_QUEUED)) {
586             DeleteFromSalvageQueue(node);
587         }
588     }
589
590  done:
591     return code;
592 }
593
594 /**
595  * cancel all pending salvage requests.
596  *
597  * @param[in]  com  incoming command object
598  * @param[out] res  outbound response object
599  *
600  * @return operation status
601  *    @retval SYNC_OK success
602  *
603  * @note this is a SALVSYNC protocol rpc handler
604  *
605  * @internal
606  */
607 static afs_int32
608 SALVSYNC_com_CancelAll(SALVSYNC_command * com, SALVSYNC_response * res)
609 {
610     struct SalvageQueueNode * np, *nnp;
611     struct DiskPartition64 * dp;
612
613     for (dp = DiskPartitionList ; dp ; dp = dp->next) {
614         for (queue_Scan(&salvageQueue.part[dp->index], np, nnp, SalvageQueueNode)) {
615             DeleteFromSalvageQueue(np);
616         }
617     }
618
619     return SYNC_OK;
620 }
621
622 /**
623  * link a queue node for a clone to its parent volume.
624  *
625  * @param[in]  com   inbound command object
626  * @param[out] res   outbound response object
627  *
628  * @return operation status
629  *    @retval SYNC_OK success
630  *    @retval SYNC_FAILED malformed command packet
631  *    @retval SYNC_DENIED the request could not be completed
632  *
633  * @note this is a SALVSYNC protocol rpc handler
634  *
635  * @post the requested volume is marked as a child of another volume.
636  *       thus, future salvage requests for this volume will result in the
637  *       parent of the volume group being scheduled for salvage instead
638  *       of this clone.
639  *
640  * @internal
641  */
642 static afs_int32
643 SALVSYNC_com_Link(SALVSYNC_command * com, SALVSYNC_response * res)
644 {
645     afs_int32 code = SYNC_OK;
646     struct SalvageQueueNode * clone, * parent;
647
648     if (SYNC_verifyProtocolString(com->sop->partName, sizeof(com->sop->partName))) {
649         code = SYNC_FAILED;
650         res->hdr->reason = SYNC_REASON_MALFORMED_PACKET;
651         goto done;
652     }
653
654     /* lookup clone's salvage scheduling node */
655     clone = LookupNodeByCommand(com->sop, NULL);
656     if (clone == NULL) {
657         code = SYNC_DENIED;
658         res->hdr->reason = SALVSYNC_REASON_ERROR;
659         goto done;
660     }
661
662     /* lookup parent's salvage scheduling node */
663     parent = LookupNode(com->sop->parent, com->sop->partName, NULL);
664     if (parent == NULL) {
665         if (AllocNode(&parent)) {
666             code = SYNC_DENIED;
667             res->hdr->reason = SYNC_REASON_NOMEM;
668             goto done;
669         }
670         memcpy(&parent->command.com, com->hdr, sizeof(SYNC_command_hdr));
671         memcpy(&parent->command.sop, com->sop, sizeof(SALVSYNC_command_hdr));
672         parent->command.sop.volume = parent->command.sop.parent = com->sop->parent;
673         AddNodeToHash(parent);
674     }
675
676     if (LinkNode(parent, clone)) {
677         code = SYNC_DENIED;
678         goto done;
679     }
680
681  done:
682     return code;
683 }
684
685 /**
686  * query the status of a volume salvage request.
687  *
688  * @param[in]  com   inbound command object
689  * @param[out] res   outbound response object
690  *
691  * @return operation status
692  *    @retval SYNC_OK success
693  *    @retval SYNC_FAILED malformed command packet
694  *
695  * @note this is a SALVSYNC protocol rpc handler
696  *
697  * @internal
698  */
699 static afs_int32
700 SALVSYNC_com_Query(SALVSYNC_command * com, SALVSYNC_response * res)
701 {
702     afs_int32 code = SYNC_OK;
703     struct SalvageQueueNode * node;
704
705     if (SYNC_verifyProtocolString(com->sop->partName, sizeof(com->sop->partName))) {
706         code = SYNC_FAILED;
707         res->hdr->reason = SYNC_REASON_MALFORMED_PACKET;
708         goto done;
709     }
710
711     LookupNodeByCommand(com->sop, &node);
712
713     /* query whether a volume is done salvaging */
714     if (node == NULL) {
715         res->sop->state = SALVSYNC_STATE_UNKNOWN;
716         res->sop->prio = 0;
717     } else {
718         res->hdr->flags |= SALVSYNC_FLAG_VOL_STATS_VALID;
719         res->sop->state = node->state;
720         res->sop->prio = node->command.sop.prio;
721     }
722
723  done:
724     return code;
725 }
726
727 static void
728 SALVSYNC_Drop(int fd)
729 {
730     RemoveHandler(fd);
731 #ifdef AFS_NT40_ENV
732     closesocket(fd);
733 #else
734     close(fd);
735 #endif
736     AcceptOn();
737 }
738
739 static int AcceptHandler = -1;  /* handler id for accept, if turned on */
740
741 static void
742 AcceptOn(void)
743 {
744     if (AcceptHandler == -1) {
745         assert(AddHandler(salvsync_server_state.fd, SALVSYNC_newconnection));
746         AcceptHandler = FindHandler(salvsync_server_state.fd);
747     }
748 }
749
750 static void
751 AcceptOff(void)
752 {
753     if (AcceptHandler != -1) {
754         assert(RemoveHandler(salvsync_server_state.fd));
755         AcceptHandler = -1;
756     }
757 }
758
759 /* The multiple FD handling code. */
760
761 static int HandlerFD[MAXHANDLERS];
762 static void (*HandlerProc[MAXHANDLERS]) (int);
763
764 static void
765 InitHandler(void)
766 {
767     register int i;
768     ObtainWriteLock(&SALVSYNC_handler_lock);
769     for (i = 0; i < MAXHANDLERS; i++) {
770         HandlerFD[i] = -1;
771         HandlerProc[i] = NULL;
772     }
773     ReleaseWriteLock(&SALVSYNC_handler_lock);
774 }
775
776 static void
777 CallHandler(fd_set * fdsetp)
778 {
779     register int i;
780     ObtainReadLock(&SALVSYNC_handler_lock);
781     for (i = 0; i < MAXHANDLERS; i++) {
782         if (HandlerFD[i] >= 0 && FD_ISSET(HandlerFD[i], fdsetp)) {
783             ReleaseReadLock(&SALVSYNC_handler_lock);
784             (*HandlerProc[i]) (HandlerFD[i]);
785             ObtainReadLock(&SALVSYNC_handler_lock);
786         }
787     }
788     ReleaseReadLock(&SALVSYNC_handler_lock);
789 }
790
791 static int
792 AddHandler(int afd, void (*aproc) (int))
793 {
794     register int i;
795     ObtainWriteLock(&SALVSYNC_handler_lock);
796     for (i = 0; i < MAXHANDLERS; i++)
797         if (HandlerFD[i] == -1)
798             break;
799     if (i >= MAXHANDLERS) {
800         ReleaseWriteLock(&SALVSYNC_handler_lock);
801         return 0;
802     }
803     HandlerFD[i] = afd;
804     HandlerProc[i] = aproc;
805     ReleaseWriteLock(&SALVSYNC_handler_lock);
806     return 1;
807 }
808
809 static int
810 FindHandler(register int afd)
811 {
812     register int i;
813     ObtainReadLock(&SALVSYNC_handler_lock);
814     for (i = 0; i < MAXHANDLERS; i++)
815         if (HandlerFD[i] == afd) {
816             ReleaseReadLock(&SALVSYNC_handler_lock);
817             return i;
818         }
819     ReleaseReadLock(&SALVSYNC_handler_lock);    /* just in case */
820     assert(1 == 2);
821     return -1;                  /* satisfy compiler */
822 }
823
824 static int
825 FindHandler_r(register int afd)
826 {
827     register int i;
828     for (i = 0; i < MAXHANDLERS; i++)
829         if (HandlerFD[i] == afd) {
830             return i;
831         }
832     assert(1 == 2);
833     return -1;                  /* satisfy compiler */
834 }
835
836 static int
837 RemoveHandler(register int afd)
838 {
839     ObtainWriteLock(&SALVSYNC_handler_lock);
840     HandlerFD[FindHandler_r(afd)] = -1;
841     ReleaseWriteLock(&SALVSYNC_handler_lock);
842     return 1;
843 }
844
845 static void
846 GetHandler(fd_set * fdsetp, int *maxfdp)
847 {
848     register int i;
849     register int maxfd = -1;
850     FD_ZERO(fdsetp);
851     ObtainReadLock(&SALVSYNC_handler_lock);     /* just in case */
852     for (i = 0; i < MAXHANDLERS; i++)
853         if (HandlerFD[i] != -1) {
854             FD_SET(HandlerFD[i], fdsetp);
855             if (maxfd < HandlerFD[i])
856                 maxfd = HandlerFD[i];
857         }
858     *maxfdp = maxfd;
859     ReleaseReadLock(&SALVSYNC_handler_lock);    /* just in case */
860 }
861
862 /**
863  * allocate a salvage queue node.
864  *
865  * @param[out] node_out  address in which to store new node pointer
866  *
867  * @return operation status
868  *    @retval 0 success
869  *    @retval 1 failed to allocate node
870  *
871  * @internal
872  */
873 static int
874 AllocNode(struct SalvageQueueNode ** node_out)
875 {
876     int code = 0;
877     struct SalvageQueueNode * node;
878
879     *node_out = node = (struct SalvageQueueNode *) 
880         malloc(sizeof(struct SalvageQueueNode));
881     if (node == NULL) {
882         code = 1;
883         goto done;
884     }
885
886     memset(node, 0, sizeof(struct SalvageQueueNode));
887     node->type = SALVSYNC_VOLGROUP_PARENT;
888     node->state = SALVSYNC_STATE_UNKNOWN;
889
890  done:
891     return code;
892 }
893
894 /**
895  * link a salvage queue node to its parent.
896  *
897  * @param[in] parent  pointer to queue node for parent of volume group
898  * @param[in] clone   pointer to queue node for a clone
899  *
900  * @return operation status
901  *    @retval 0 success
902  *    @retval 1 failure
903  *
904  * @internal
905  */
906 static int
907 LinkNode(struct SalvageQueueNode * parent,
908          struct SalvageQueueNode * clone)
909 {
910     int code = 0;
911     int idx;
912
913     /* check for attaching a clone to a clone */
914     if (parent->type != SALVSYNC_VOLGROUP_PARENT) {
915         code = 1;
916         goto done;
917     }
918
919     /* check for pre-existing registration and openings */
920     for (idx = 0; idx < VOLMAXTYPES; idx++) {
921         if (parent->volgroup.children[idx] == clone) {
922             goto linked;
923         }
924         if (parent->volgroup.children[idx] == NULL) {
925             break;
926         }
927     }
928     if (idx == VOLMAXTYPES) {
929         code = 1;
930         goto done;
931     }
932
933     /* link parent and child */
934     parent->volgroup.children[idx] = clone;
935     clone->type = SALVSYNC_VOLGROUP_CLONE;
936     clone->volgroup.parent = parent;
937
938
939  linked:
940     switch (clone->state) {
941     case SALVSYNC_STATE_QUEUED:
942         DeleteFromSalvageQueue(clone);
943
944     case SALVSYNC_STATE_SALVAGING:
945         switch (parent->state) {
946         case SALVSYNC_STATE_UNKNOWN:
947         case SALVSYNC_STATE_ERROR:
948         case SALVSYNC_STATE_DONE:
949             parent->command.sop.prio = clone->command.sop.prio;
950             AddToSalvageQueue(parent);
951             break;
952
953         case SALVSYNC_STATE_QUEUED:
954             if (clone->command.sop.prio) {
955                 parent->command.sop.prio += clone->command.sop.prio;
956                 UpdateCommandPrio(parent);
957             }
958             break;
959
960         default:
961             break;
962         }
963         break;
964
965     default:
966         break;
967     }
968
969  done:
970     return code;
971 }
972
973 static void
974 HandlePrio(struct SalvageQueueNode * clone, 
975            struct SalvageQueueNode * node,
976            afs_uint32 new_prio)
977 {
978     afs_uint32 delta;
979
980     switch (node->state) {
981     case SALVSYNC_STATE_ERROR:
982     case SALVSYNC_STATE_DONE:
983     case SALVSYNC_STATE_UNKNOWN:
984         node->command.sop.prio = 0;
985         break;
986     }
987
988     if (new_prio < clone->command.sop.prio) {
989         /* strange. let's just set our delta to 1 */
990         delta = 1;
991     } else {
992         delta = new_prio - clone->command.sop.prio;
993     }
994
995     if (clone->type == SALVSYNC_VOLGROUP_CLONE) {
996         clone->command.sop.prio = new_prio;
997     }
998
999     node->command.sop.prio += delta;
1000 }
1001
1002 static int
1003 AddToSalvageQueue(struct SalvageQueueNode * node)
1004 {
1005     afs_int32 id;
1006     struct SalvageQueueNode * last = NULL;
1007
1008     id = volutil_GetPartitionID(node->command.sop.partName);
1009     if (id < 0 || id > VOLMAXPARTS) {
1010         return 1;
1011     }
1012     if (!VGetPartitionById_r(id, 0)) {
1013         /* don't enqueue salvage requests for unmounted partitions */
1014         return 1;
1015     }
1016     if (queue_IsOnQueue(node)) {
1017         return 0;
1018     }
1019
1020     if (queue_IsNotEmpty(&salvageQueue.part[id])) {
1021         last = queue_Last(&salvageQueue.part[id], SalvageQueueNode);
1022     }
1023     queue_Append(&salvageQueue.part[id], node);
1024     salvageQueue.len[id]++;
1025     salvageQueue.total_len++;
1026     salvageQueue.last_insert = id;
1027     node->partition_id = id;
1028     node->state = SALVSYNC_STATE_QUEUED;
1029
1030     /* reorder, if necessary */
1031     if (last && last->command.sop.prio < node->command.sop.prio) {
1032         UpdateCommandPrio(node);
1033     }
1034
1035     assert(pthread_cond_broadcast(&salvageQueue.cv) == 0);
1036     return 0;
1037 }
1038
1039 static void
1040 DeleteFromSalvageQueue(struct SalvageQueueNode * node)
1041 {
1042     if (queue_IsOnQueue(node)) {
1043         queue_Remove(node);
1044         salvageQueue.len[node->partition_id]--;
1045         salvageQueue.total_len--;
1046         node->state = SALVSYNC_STATE_UNKNOWN;
1047         assert(pthread_cond_broadcast(&salvageQueue.cv) == 0);
1048     }
1049 }
1050
1051 static void
1052 AddToPendingQueue(struct SalvageQueueNode * node)
1053 {
1054     queue_Append(&pendingQueue, node);
1055     pendingQueue.len++;
1056     node->state = SALVSYNC_STATE_SALVAGING;
1057     assert(pthread_cond_broadcast(&pendingQueue.queue_change_cv) == 0);
1058 }
1059
1060 static void
1061 DeleteFromPendingQueue(struct SalvageQueueNode * node)
1062 {
1063     if (queue_IsOnQueue(node)) {
1064         queue_Remove(node);
1065         pendingQueue.len--;
1066         node->state = SALVSYNC_STATE_UNKNOWN;
1067         assert(pthread_cond_broadcast(&pendingQueue.queue_change_cv) == 0);
1068     }
1069 }
1070
1071 static struct SalvageQueueNode *
1072 LookupPendingCommand(SALVSYNC_command_hdr * qry)
1073 {
1074     struct SalvageQueueNode * np, * nnp;
1075
1076     for (queue_Scan(&pendingQueue, np, nnp, SalvageQueueNode)) {
1077         if ((np->command.sop.volume == qry->volume) && 
1078             !strncmp(np->command.sop.partName, qry->partName,
1079                      sizeof(qry->partName)))
1080             break;
1081     }
1082
1083     if (queue_IsEnd(&pendingQueue, np))
1084         np = NULL;
1085     return np;
1086 }
1087
1088 static struct SalvageQueueNode *
1089 LookupPendingCommandByPid(int pid)
1090 {
1091     struct SalvageQueueNode * np, * nnp;
1092
1093     for (queue_Scan(&pendingQueue, np, nnp, SalvageQueueNode)) {
1094         if (np->pid == pid)
1095             break;
1096     }
1097
1098     if (queue_IsEnd(&pendingQueue, np))
1099         np = NULL;
1100     return np;
1101 }
1102
1103
1104 /* raise the priority of a previously scheduled salvage */
1105 static void
1106 UpdateCommandPrio(struct SalvageQueueNode * node)
1107 {
1108     struct SalvageQueueNode *np, *nnp;
1109     afs_int32 id;
1110     afs_uint32 prio;
1111
1112     assert(queue_IsOnQueue(node));
1113
1114     prio = node->command.sop.prio;
1115     id = node->partition_id;
1116     if (queue_First(&salvageQueue.part[id], SalvageQueueNode)->command.sop.prio < prio) {
1117         queue_Remove(node);
1118         queue_Prepend(&salvageQueue.part[id], node);
1119     } else {
1120         for (queue_ScanBackwardsFrom(&salvageQueue.part[id], node, np, nnp, SalvageQueueNode)) {
1121             if (np->command.sop.prio > prio)
1122                 break;
1123         }
1124         if (queue_IsEnd(&salvageQueue.part[id], np)) {
1125             queue_Remove(node);
1126             queue_Prepend(&salvageQueue.part[id], node);
1127         } else if (node != np) {
1128             queue_Remove(node);
1129             queue_InsertAfter(np, node);
1130         }
1131     }
1132 }
1133
1134 /* this will need to be rearchitected if we ever want more than one thread
1135  * to wait for new salvage nodes */
1136 struct SalvageQueueNode * 
1137 SALVSYNC_getWork(void)
1138 {
1139     int i, ret;
1140     struct DiskPartition64 * dp = NULL, * fdp;
1141     static afs_int32 next_part_sched = 0;
1142     struct SalvageQueueNode *node = NULL, *np;
1143
1144     VOL_LOCK;
1145
1146     /*
1147      * wait for work to be scheduled
1148      * if there are no disk partitions, just sit in this wait loop forever
1149      */
1150     while (!salvageQueue.total_len || !DiskPartitionList) {
1151         VOL_CV_WAIT(&salvageQueue.cv);
1152     }
1153
1154     /* 
1155      * short circuit for simple case where only one partition has
1156      * scheduled salvages
1157      */
1158     if (salvageQueue.last_insert >= 0 && salvageQueue.last_insert <= VOLMAXPARTS &&
1159         (salvageQueue.total_len == salvageQueue.len[salvageQueue.last_insert])) {
1160         node = queue_First(&salvageQueue.part[salvageQueue.last_insert], SalvageQueueNode);
1161         goto have_node;
1162     }
1163
1164
1165     /* 
1166      * ok, more than one partition has scheduled salvages.
1167      * now search for partitions with scheduled salvages, but no pending salvages. 
1168      */
1169     dp = VGetPartitionById_r(next_part_sched, 0);
1170     if (!dp) {
1171         dp = DiskPartitionList;
1172     }
1173     fdp = dp;
1174
1175     for (i=0 ; 
1176          !i || dp != fdp ; 
1177          dp = (dp->next) ? dp->next : DiskPartitionList, i++ ) {
1178         if (!partition_salvaging[dp->index] && salvageQueue.len[dp->index]) {
1179             node = queue_First(&salvageQueue.part[dp->index], SalvageQueueNode);
1180             goto have_node;
1181         }
1182     }
1183
1184
1185     /*
1186      * all partitions with scheduled salvages have at least one pending.
1187      * now do an exhaustive search for a scheduled salvage.
1188      */
1189     dp = fdp;
1190
1191     for (i=0 ; 
1192          !i || dp != fdp ; 
1193          dp = (dp->next) ? dp->next : DiskPartitionList, i++ ) {
1194         if (salvageQueue.len[dp->index]) {
1195             node = queue_First(&salvageQueue.part[dp->index], SalvageQueueNode);
1196             goto have_node;
1197         }
1198     }
1199
1200     /* we should never reach this line */
1201     assert(1==2);
1202
1203  have_node:
1204     assert(node != NULL);
1205     node->pid = 0;
1206     partition_salvaging[node->partition_id]++;
1207     DeleteFromSalvageQueue(node);
1208     AddToPendingQueue(node);
1209
1210     if (dp) {
1211         /* update next_part_sched field */
1212         if (dp->next) {
1213             next_part_sched = dp->next->index;
1214         } else if (DiskPartitionList) {
1215             next_part_sched = DiskPartitionList->index;
1216         } else {
1217             next_part_sched = -1;
1218         }
1219     }
1220
1221  bail:
1222     VOL_UNLOCK;
1223     return node;
1224 }
1225
1226 /**
1227  * update internal scheduler state to reflect completion of a work unit.
1228  *
1229  * @param[in]  node    salvage queue node object pointer
1230  * @param[in]  result  worker process result code
1231  *
1232  * @post scheduler state is updated.
1233  *
1234  * @internal
1235  */
1236 static void
1237 SALVSYNC_doneWork_r(struct SalvageQueueNode * node, int result)
1238 {
1239     afs_int32 partid;
1240     int idx;
1241
1242     DeleteFromPendingQueue(node);
1243     partid = node->partition_id;
1244     if (partid >=0 && partid <= VOLMAXPARTS) {
1245         partition_salvaging[partid]--;
1246     }
1247     if (result == 0) {
1248         node->state = SALVSYNC_STATE_DONE;
1249     } else if (result != SALSRV_EXIT_VOLGROUP_LINK) {
1250         node->state = SALVSYNC_STATE_ERROR;
1251     }
1252
1253     if (node->type == SALVSYNC_VOLGROUP_PARENT) {
1254         for (idx = 0; idx < VOLMAXTYPES; idx++) {
1255             if (node->volgroup.children[idx]) {
1256                 node->volgroup.children[idx]->state = node->state;
1257             }
1258         }
1259     }
1260 }
1261
1262 /**
1263  * check whether worker child failed.
1264  *
1265  * @param[in] status  status bitfield return by wait()
1266  *
1267  * @return boolean failure code
1268  *    @retval 0 child succeeded
1269  *    @retval 1 child failed
1270  *
1271  * @internal
1272  */
1273 static int
1274 ChildFailed(int status)
1275 {
1276     return (WCOREDUMP(status) || 
1277             WIFSIGNALED(status) || 
1278             ((WEXITSTATUS(status) != 0) && 
1279              (WEXITSTATUS(status) != SALSRV_EXIT_VOLGROUP_LINK)));
1280 }
1281
1282
1283 /**
1284  * notify salvsync scheduler of node completion, by child pid.
1285  *
1286  * @param[in]  pid     pid of worker child
1287  * @param[in]  status  worker status bitfield from wait()
1288  *
1289  * @post scheduler state is updated.
1290  *       if status code is a failure, fileserver notification was attempted
1291  *
1292  * @see SALVSYNC_doneWork_r
1293  */
1294 void
1295 SALVSYNC_doneWorkByPid(int pid, int status)
1296 {
1297     struct SalvageQueueNode * node;
1298     char partName[16];
1299     afs_uint32 volids[VOLMAXTYPES+1];
1300     unsigned int idx;
1301
1302     memset(volids, 0, sizeof(volids));
1303
1304     VOL_LOCK;
1305     node = LookupPendingCommandByPid(pid);
1306     if (node != NULL) {
1307         SALVSYNC_doneWork_r(node, status);
1308
1309         if (ChildFailed(status)) {
1310             /* populate volume id list for later processing outside the glock */
1311             volids[0] = node->command.sop.volume;
1312             strcpy(partName, node->command.sop.partName);
1313             if (node->type == SALVSYNC_VOLGROUP_PARENT) {
1314                 for (idx = 0; idx < VOLMAXTYPES; idx++) {
1315                     if (node->volgroup.children[idx]) {
1316                         volids[idx+1] = node->volgroup.children[idx]->command.sop.volume;
1317                     }
1318                 }
1319             }
1320         }
1321     }
1322     VOL_UNLOCK;
1323
1324     /*
1325      * if necessary, notify fileserver of
1326      * failure to salvage volume group
1327      * [we cannot guarantee that the child made the
1328      *  appropriate notifications (e.g. SIGSEGV)]
1329      *  -- tkeiser 11/28/2007
1330      */
1331     if (ChildFailed(status)) {
1332         for (idx = 0; idx <= VOLMAXTYPES; idx++) {
1333             if (volids[idx]) {
1334                 FSYNC_VolOp(volids[idx],
1335                             partName,
1336                             FSYNC_VOL_FORCE_ERROR,
1337                             FSYNC_WHATEVER,
1338                             NULL);
1339             }
1340         }
1341     }
1342 }
1343
1344 #endif /* AFS_DEMAND_ATTACH_FS */